From b771c654cab511b172484479cafd006d52588103 Mon Sep 17 00:00:00 2001 From: Denys Vlasenko Date: Mon, 13 Sep 2010 00:34:26 +0200 Subject: shell: shrink arith code; and prepare for returning text error codes function old new delta arith 701 680 -21 Signed-off-by: Denys Vlasenko --- shell/hush.c | 8 ++-- shell/math.c | 120 +++++++++++++++++++++++++++++------------------------------ 2 files changed, 63 insertions(+), 65 deletions(-) (limited to 'shell') diff --git a/shell/hush.c b/shell/hush.c index 752efd0c8..ef0c454ec 100644 --- a/shell/hush.c +++ b/shell/hush.c @@ -4728,9 +4728,9 @@ static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, cha if (beg < 0) /* bash compat */ beg = 0; debug_printf_varexp("from val:'%s'\n", val); - if (len == 0 || !val || beg >= strlen(val)) - val = ""; - else { + if (len == 0 || !val || beg >= strlen(val)) { + val = NULL; + } else { /* Paranoia. What if user entered 9999999999999 * which fits in arith_t but not int? */ if (len >= INT_MAX) @@ -4742,7 +4742,7 @@ static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, cha #endif { die_if_script("malformed ${%s:...}", var); - val = ""; + val = NULL; } } else { /* one of "-=+?" */ /* Standard-mandated substitution ops: diff --git a/shell/math.c b/shell/math.c index a4c55a4d0..2f093391f 100644 --- a/shell/math.c +++ b/shell/math.c @@ -124,9 +124,6 @@ #define setvar (math_hooks->setvar ) //#define endofname (math_hooks->endofname) -#define arith_isspace(arithval) \ - (arithval == ' ' || arithval == '\n' || arithval == '\t') - typedef unsigned char operator; /* An operator's token id is a bit of a bitfield. The lower 5 bits are the @@ -156,7 +153,7 @@ typedef unsigned char operator; #define TOK_REM_ASSIGN tok_decl(3,2) /* all assign is right associativity and precedence eq, but (7+3)<<5 > 256 */ -#define convert_prec_is_assing(prec) do { if (prec == 3) prec = 2; } while (0) +#define convert_prec_is_assign(prec) do { if (prec == 3) prec = 2; } while (0) /* conditional is right associativity too */ #define TOK_CONDITIONAL tok_decl(4,0) @@ -223,7 +220,7 @@ tok_have_assign(operator op) { operator prec = PREC(op); - convert_prec_is_assing(prec); + convert_prec_is_assign(prec); return (prec == PREC(TOK_ASSIGN) || prec == PREC_PRE || prec == PREC_POST); } @@ -477,7 +474,7 @@ static const char op_tokens[] ALIGN1 = { 0 }; /* ptr to ")" */ -#define endexpression (&op_tokens[sizeof(op_tokens)-7]) +#define ptr_to_rparen (&op_tokens[sizeof(op_tokens)-7]) const char* FAST_FUNC endofname(const char *name) @@ -494,32 +491,36 @@ endofname(const char *name) arith_t arith(const char *expr, int *perrcode, a_e_h_t *math_hooks) { - char arithval; /* Current character under analysis */ - operator lasttok, op; - operator prec; - operator *stack, *stackptr; - const char *p = endexpression; + operator lasttok; int errcode; - v_n_t *numstack, *numstackptr; - unsigned datasizes = strlen(expr) + 2; - + const char *start_expr = expr = skip_whitespace(expr); + unsigned expr_len = strlen(expr) + 2; /* Stack of integers */ /* The proof that there can be no more than strlen(startbuf)/2+1 integers * in any given correct or incorrect expression is left as an exercise to * the reader. */ - numstackptr = numstack = alloca((datasizes / 2) * sizeof(numstack[0])); + v_n_t *const numstack = alloca((expr_len / 2) * sizeof(numstack[0])); + v_n_t *numstackptr = numstack; /* Stack of operator tokens */ - stackptr = stack = alloca(datasizes * sizeof(stack[0])); + operator *const stack = alloca(expr_len * sizeof(stack[0])); + operator *stackptr = stack; *stackptr++ = lasttok = TOK_LPAREN; /* start off with a left paren */ - *perrcode = errcode = 0; + errcode = 0; while (1) { + const char *p; + operator op; + operator prec; + char arithval; + + expr = skip_whitespace(expr); arithval = *expr; - if (arithval == 0) { - if (p == endexpression) { + if (arithval == '\0') { + if (expr == start_expr) { /* Null expression. */ - return 0; + numstack->val = 0; + goto ret; } /* This is only reached after all tokens have been extracted from the @@ -527,38 +528,29 @@ arith(const char *expr, int *perrcode, a_e_h_t *math_hooks) * are to be applied in order. At the end, there should be a final * result on the integer stack */ - if (expr != endexpression + 1) { + if (expr != ptr_to_rparen + 1) { /* If we haven't done so already, */ /* append a closing right paren */ - expr = endexpression; + expr = ptr_to_rparen; /* and let the loop process it. */ continue; } /* At this point, we're done with the expression. */ - if (numstackptr != numstack+1) { + if (numstackptr != numstack + 1) { /* ... but if there isn't, it's bad */ - err: - *perrcode = -1; - return *perrcode; + goto err; } if (numstack->var) { /* expression is $((var)) only, lookup now */ errcode = arith_lookup_val(numstack, math_hooks); } - ret: - *perrcode = errcode; - return numstack->val; + goto ret; } - /* Continue processing the expression. */ - if (arith_isspace(arithval)) { - /* Skip whitespace */ - goto prologue; - } p = endofname(expr); if (p != expr) { - size_t var_name_size = (p-expr) + 1; /* trailing zero */ - + /* Name */ + size_t var_name_size = (p-expr) + 1; /* +1 for NUL */ numstackptr->var = alloca(var_name_size); safe_strncpy(numstackptr->var, expr, var_name_size); expr = p; @@ -568,36 +560,37 @@ arith(const char *expr, int *perrcode, a_e_h_t *math_hooks) lasttok = TOK_NUM; continue; } + if (isdigit(arithval)) { + /* Number */ numstackptr->var = NULL; errno = 0; - /* call strtoul[l]: */ - numstackptr->val = strto_arith_t(expr, (char **) &expr, 0); + numstackptr->val = strto_arith_t(expr, (char**) &expr, 0); if (errno) numstackptr->val = 0; /* bash compat */ goto num; } - for (p = op_tokens; ; p++) { - const char *o; - if (*p == 0) { - /* strange operator not found */ - goto err; - } - for (o = expr; *p && *o == *p; p++) - o++; - if (!*p) { - /* found */ - expr = o - 1; + /* Should be an operator */ + p = op_tokens; + while (1) { + const char *e = expr; + /* Compare expr to current op_tokens[] element */ + while (*p && *e == *p) + p++, e++; + if (*p == '\0') { /* match: operator is found */ + expr = e; break; } - /* skip tail uncompared token */ + /* Go to next element of op_tokens[] */ while (*p) p++; - /* skip zero delim */ - p++; + p += 2; /* skip NUL and TOK_foo bytes */ + if (*p == '\0') /* no next element, operator not found */ + goto err; } - op = p[1]; + op = p[1]; /* fetch TOK_foo value */ + /* NB: expr now points past the operator */ /* post grammar: a++ reduce to num */ if (lasttok == TOK_POST_INC || lasttok == TOK_POST_DEC) @@ -651,13 +644,12 @@ arith(const char *expr, int *perrcode, a_e_h_t *math_hooks) /* Any operator directly after a */ lasttok = TOK_NUM; /* close paren should consider itself binary */ - goto prologue; + goto next; } } else { operator prev_prec = PREC(stackptr[-1]); - - convert_prec_is_assing(prec); - convert_prec_is_assing(prev_prec); + convert_prec_is_assign(prec); + convert_prec_is_assign(prev_prec); if (prev_prec < prec) break; /* check right assoc */ @@ -665,7 +657,8 @@ arith(const char *expr, int *perrcode, a_e_h_t *math_hooks) break; } errcode = arith_apply(*--stackptr, numstack, &numstackptr, math_hooks); - if (errcode) goto ret; + if (errcode) + goto ret; } if (op == TOK_RPAREN) { goto err; @@ -674,9 +667,14 @@ arith(const char *expr, int *perrcode, a_e_h_t *math_hooks) /* Push this operator to the stack and remember it. */ *stackptr++ = lasttok = op; - prologue: - ++expr; - } /* while */ + next: ; + } /* while (1) */ + + err: + numstack->val = errcode = -1; + ret: + *perrcode = errcode; + return numstack->val; } /* -- cgit v1.2.3-55-g6feb From 51850c818cf909cde0e07091a8015532cc645b7a Mon Sep 17 00:00:00 2001 From: Denys Vlasenko Date: Mon, 13 Sep 2010 01:09:11 +0200 Subject: shell: small code shrink function old new delta arith 680 675 -5 Signed-off-by: Denys Vlasenko --- shell/math.c | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) (limited to 'shell') diff --git a/shell/math.c b/shell/math.c index 2f093391f..c698a442b 100644 --- a/shell/math.c +++ b/shell/math.c @@ -635,28 +635,29 @@ arith(const char *expr, int *perrcode, a_e_h_t *math_hooks) goto err; } while (stackptr != stack) { + operator prev_op = *--stackptr; if (op == TOK_RPAREN) { /* The algorithm employed here is simple: while we don't * hit an open paren nor the bottom of the stack, pop * tokens and apply them */ - if (stackptr[-1] == TOK_LPAREN) { - --stackptr; + if (prev_op == TOK_LPAREN) { /* Any operator directly after a */ lasttok = TOK_NUM; /* close paren should consider itself binary */ goto next; } } else { - operator prev_prec = PREC(stackptr[-1]); + operator prev_prec = PREC(prev_op); convert_prec_is_assign(prec); convert_prec_is_assign(prev_prec); - if (prev_prec < prec) - break; - /* check right assoc */ - if (prev_prec == prec && is_right_associativity(prec)) + if (prev_prec < prec + || (prev_prec == prec && is_right_associativity(prec)) + ) { + stackptr++; break; + } } - errcode = arith_apply(*--stackptr, numstack, &numstackptr, math_hooks); + errcode = arith_apply(prev_op, numstack, &numstackptr, math_hooks); if (errcode) goto ret; } -- cgit v1.2.3-55-g6feb From bd14770b0c8594ce5b0ab9b0b1249b72fc781dd3 Mon Sep 17 00:00:00 2001 From: Denys Vlasenko Date: Mon, 13 Sep 2010 11:11:40 +0200 Subject: shell/math.c: small code shrink; fixed incomprehensible comments function old new delta arith_apply 1334 1304 -30 Signed-off-by: Denys Vlasenko --- shell/math.c | 225 ++++++++++++++++++++++++++++++----------------------------- 1 file changed, 113 insertions(+), 112 deletions(-) (limited to 'shell') diff --git a/shell/math.c b/shell/math.c index c698a442b..a9fbc8910 100644 --- a/shell/math.c +++ b/shell/math.c @@ -52,17 +52,18 @@ * than a comparable parser written in yacc. The supported operators are * listed in #defines below. Parens, order of operations, and error handling * are supported. This code is thread safe. The exact expression format should - * be that which POSIX specifies for shells. */ - -/* The code uses a simple two-stack algorithm. See + * be that which POSIX specifies for shells. + * + * The code uses a simple two-stack algorithm. See * http://www.onthenet.com.au/~grahamis/int2008/week02/lect02.html * for a detailed explanation of the infix-to-postfix algorithm on which * this is based (this code differs in that it applies operators immediately * to the stack instead of adding them to a queue to end up with an - * expression). */ - -/* To use the routine, call it with an expression string and error return - * pointer */ + * expression). + * + * To use the routine, call it with an expression string and error return + * pointer + */ /* * Aug 24, 2001 Manuel Novoa III @@ -104,22 +105,21 @@ * (C) 2003 Vladimir Oleynik * * - allow access to variable, - * used recursive find value indirection (c=2*2; a="c"; $((a+=2)) produce 6) - * - realize assign syntax (VAR=expr, +=, *= etc) - * - realize exponentiation (** operator) - * - realize comma separated - expr, expr - * - realise ++expr --expr expr++ expr-- - * - realise expr ? expr : expr (but, second expr calculate always) + * use recursive value indirection: c="2*2"; a="c"; echo $((a+=2)) produce 6 + * - implement assign syntax (VAR=expr, +=, *= etc) + * - implement exponentiation (** operator) + * - implement comma separated - expr, expr + * - implement ++expr --expr expr++ expr-- + * - implement expr ? expr : expr (but second expr is always calculated) * - allow hexadecimal and octal numbers - * - was restored loses XOR operator - * - remove one goto label, added three ;-) - * - protect $((num num)) as true zero expr (Manuel`s error) + * - restore lost XOR operator + * - protect $((num num)) as true zero expr (Manuel's error) * - always use special isspace(), see comment from bash ;-) */ #include "libbb.h" #include "math.h" -#define a_e_h_t arith_eval_hooks_t +#define a_e_h_t arith_eval_hooks_t #define lookupvar (math_hooks->lookupvar) #define setvar (math_hooks->setvar ) //#define endofname (math_hooks->endofname) @@ -130,103 +130,104 @@ typedef unsigned char operator; * precedence, and 3 high bits are an ID unique across operators of that * precedence. The ID portion is so that multiple operators can have the * same precedence, ensuring that the leftmost one is evaluated first. - * Consider * and /. */ - -#define tok_decl(prec,id) (((id)<<5)|(prec)) -#define PREC(op) ((op) & 0x1F) - -#define TOK_LPAREN tok_decl(0,0) + * Consider * and / + */ +#define tok_decl(prec,id) (((id)<<5) | (prec)) +#define PREC(op) ((op) & 0x1F) -#define TOK_COMMA tok_decl(1,0) +#define TOK_LPAREN tok_decl(0,0) -#define TOK_ASSIGN tok_decl(2,0) -#define TOK_AND_ASSIGN tok_decl(2,1) -#define TOK_OR_ASSIGN tok_decl(2,2) -#define TOK_XOR_ASSIGN tok_decl(2,3) -#define TOK_PLUS_ASSIGN tok_decl(2,4) -#define TOK_MINUS_ASSIGN tok_decl(2,5) -#define TOK_LSHIFT_ASSIGN tok_decl(2,6) -#define TOK_RSHIFT_ASSIGN tok_decl(2,7) +#define TOK_COMMA tok_decl(1,0) -#define TOK_MUL_ASSIGN tok_decl(3,0) -#define TOK_DIV_ASSIGN tok_decl(3,1) -#define TOK_REM_ASSIGN tok_decl(3,2) +/* All assignments are right associative and have the same precedence, + * but there are 11 of them, which doesn't fit into 3 bits for unique id. + * Abusing another precedence level: + */ +#define TOK_ASSIGN tok_decl(2,0) +#define TOK_AND_ASSIGN tok_decl(2,1) +#define TOK_OR_ASSIGN tok_decl(2,2) +#define TOK_XOR_ASSIGN tok_decl(2,3) +#define TOK_PLUS_ASSIGN tok_decl(2,4) +#define TOK_MINUS_ASSIGN tok_decl(2,5) +#define TOK_LSHIFT_ASSIGN tok_decl(2,6) +#define TOK_RSHIFT_ASSIGN tok_decl(2,7) -/* all assign is right associativity and precedence eq, but (7+3)<<5 > 256 */ -#define convert_prec_is_assign(prec) do { if (prec == 3) prec = 2; } while (0) +#define TOK_MUL_ASSIGN tok_decl(3,0) +#define TOK_DIV_ASSIGN tok_decl(3,1) +#define TOK_REM_ASSIGN tok_decl(3,2) -/* conditional is right associativity too */ -#define TOK_CONDITIONAL tok_decl(4,0) -#define TOK_CONDITIONAL_SEP tok_decl(4,1) +#define fix_assignment_prec(prec) do { if (prec == 3) prec = 2; } while (0) -#define TOK_OR tok_decl(5,0) +/* ternary conditional operator is right associative too */ +#define TOK_CONDITIONAL tok_decl(4,0) +#define TOK_CONDITIONAL_SEP tok_decl(4,1) -#define TOK_AND tok_decl(6,0) +#define TOK_OR tok_decl(5,0) -#define TOK_BOR tok_decl(7,0) +#define TOK_AND tok_decl(6,0) -#define TOK_BXOR tok_decl(8,0) +#define TOK_BOR tok_decl(7,0) -#define TOK_BAND tok_decl(9,0) +#define TOK_BXOR tok_decl(8,0) -#define TOK_EQ tok_decl(10,0) -#define TOK_NE tok_decl(10,1) +#define TOK_BAND tok_decl(9,0) -#define TOK_LT tok_decl(11,0) -#define TOK_GT tok_decl(11,1) -#define TOK_GE tok_decl(11,2) -#define TOK_LE tok_decl(11,3) +#define TOK_EQ tok_decl(10,0) +#define TOK_NE tok_decl(10,1) -#define TOK_LSHIFT tok_decl(12,0) -#define TOK_RSHIFT tok_decl(12,1) +#define TOK_LT tok_decl(11,0) +#define TOK_GT tok_decl(11,1) +#define TOK_GE tok_decl(11,2) +#define TOK_LE tok_decl(11,3) -#define TOK_ADD tok_decl(13,0) -#define TOK_SUB tok_decl(13,1) +#define TOK_LSHIFT tok_decl(12,0) +#define TOK_RSHIFT tok_decl(12,1) -#define TOK_MUL tok_decl(14,0) -#define TOK_DIV tok_decl(14,1) -#define TOK_REM tok_decl(14,2) +#define TOK_ADD tok_decl(13,0) +#define TOK_SUB tok_decl(13,1) -/* exponent is right associativity */ -#define TOK_EXPONENT tok_decl(15,1) +#define TOK_MUL tok_decl(14,0) +#define TOK_DIV tok_decl(14,1) +#define TOK_REM tok_decl(14,2) -/* For now unary operators. */ -#define UNARYPREC 16 -#define TOK_BNOT tok_decl(UNARYPREC,0) -#define TOK_NOT tok_decl(UNARYPREC,1) +/* exponent is right associative */ +#define TOK_EXPONENT tok_decl(15,1) -#define TOK_UMINUS tok_decl(UNARYPREC+1,0) -#define TOK_UPLUS tok_decl(UNARYPREC+1,1) +/* unary operators */ +#define UNARYPREC 16 +#define TOK_BNOT tok_decl(UNARYPREC,0) +#define TOK_NOT tok_decl(UNARYPREC,1) -#define PREC_PRE (UNARYPREC+2) +#define TOK_UMINUS tok_decl(UNARYPREC+1,0) +#define TOK_UPLUS tok_decl(UNARYPREC+1,1) -#define TOK_PRE_INC tok_decl(PREC_PRE, 0) -#define TOK_PRE_DEC tok_decl(PREC_PRE, 1) +#define PREC_PRE (UNARYPREC+2) -#define PREC_POST (UNARYPREC+3) +#define TOK_PRE_INC tok_decl(PREC_PRE, 0) +#define TOK_PRE_DEC tok_decl(PREC_PRE, 1) -#define TOK_POST_INC tok_decl(PREC_POST, 0) -#define TOK_POST_DEC tok_decl(PREC_POST, 1) +#define PREC_POST (UNARYPREC+3) -#define SPEC_PREC (UNARYPREC+4) +#define TOK_POST_INC tok_decl(PREC_POST, 0) +#define TOK_POST_DEC tok_decl(PREC_POST, 1) -#define TOK_NUM tok_decl(SPEC_PREC, 0) -#define TOK_RPAREN tok_decl(SPEC_PREC, 1) +#define SPEC_PREC (UNARYPREC+4) -#define NUMPTR (*numstackptr) +#define TOK_NUM tok_decl(SPEC_PREC, 0) +#define TOK_RPAREN tok_decl(SPEC_PREC, 1) static int tok_have_assign(operator op) { operator prec = PREC(op); - convert_prec_is_assign(prec); + fix_assignment_prec(prec); return (prec == PREC(TOK_ASSIGN) || prec == PREC_PRE || prec == PREC_POST); } static int -is_right_associativity(operator prec) +is_right_associative(operator prec) { return (prec == PREC(TOK_ASSIGN) || prec == PREC(TOK_EXPONENT) || prec == PREC(TOK_CONDITIONAL)); @@ -255,25 +256,25 @@ arith_lookup_val(v_n_t *t, a_e_h_t *math_hooks) if (p) { int errcode; - - /* recursive try as expression */ chk_var_recursive_looped_t *cur; chk_var_recursive_looped_t cur_save; + /* recursively try p as expression */ + for (cur = prev_chk_var_recursive; cur; cur = cur->next) { if (strcmp(cur->var, t->var) == 0) { /* expression recursion loop detected */ return -5; } } - /* save current lookuped var name */ + /* save current var name */ cur = prev_chk_var_recursive; cur_save.var = t->var; cur_save.next = cur; prev_chk_var_recursive = &cur_save; - t->val = arith (p, &errcode, math_hooks); - /* restore previous ptr after recursiving */ + t->val = arith(p, &errcode, math_hooks); + /* restore previous ptr after recursion */ prev_chk_var_recursive = cur; return errcode; } @@ -283,21 +284,24 @@ arith_lookup_val(v_n_t *t, a_e_h_t *math_hooks) return 0; } -/* "applying" a token means performing it on the top elements on the integer - * stack. For a unary operator it will only change the top element, but a - * binary operator will pop two arguments and push a result */ +/* "Applying" a token means performing it on the top elements on the integer + * stack. For an unary operator it will only change the top element, but a + * binary operator will pop two arguments and push the result */ static NOINLINE int arith_apply(operator op, v_n_t *numstack, v_n_t **numstackptr, a_e_h_t *math_hooks) { +#define NUMPTR (*numstackptr) + v_n_t *numptr_m1; arith_t numptr_val, rez; int ret_arith_lookup_val; /* There is no operator that can work without arguments */ - if (NUMPTR == numstack) goto err; + if (NUMPTR == numstack) + goto err; numptr_m1 = NUMPTR - 1; - /* check operand is var with noninteger value */ + /* Check operand is var with noninteger value */ ret_arith_lookup_val = arith_lookup_val(numptr_m1, math_hooks); if (ret_arith_lookup_val) return ret_arith_lookup_val; @@ -388,16 +392,13 @@ arith_apply(operator op, v_n_t *numstack, v_n_t **numstackptr, a_e_h_t *math_hoo rez = rez ? numptr_val : numptr_m1->contidional_second_val; } else if (op == TOK_EXPONENT) { + arith_t c; if (numptr_val < 0) return -3; /* exponent less than 0 */ - else { - arith_t c = 1; - - if (numptr_val) - while (numptr_val--) - c *= rez; - rez = c; - } + c = 1; + while (--numptr_val >= 0) + c *= rez; + rez = c; } else if (numptr_val==0) /* zero divisor check */ return -2; else if (op == TOK_DIV || op == TOK_DIV_ASSIGN) @@ -422,11 +423,12 @@ arith_apply(operator op, v_n_t *numstack, v_n_t **numstackptr, a_e_h_t *math_hoo rez++; } numptr_m1->val = rez; - /* protect geting var value, is number now */ + /* erase var name, it is just a number now */ numptr_m1->var = NULL; return 0; err: return -1; +#undef NUMPTR } /* longest must be first */ @@ -473,7 +475,6 @@ static const char op_tokens[] ALIGN1 = { '(', 0, TOK_LPAREN, 0 }; -/* ptr to ")" */ #define ptr_to_rparen (&op_tokens[sizeof(op_tokens)-7]) const char* FAST_FUNC @@ -529,15 +530,15 @@ arith(const char *expr, int *perrcode, a_e_h_t *math_hooks) * result on the integer stack */ if (expr != ptr_to_rparen + 1) { - /* If we haven't done so already, */ - /* append a closing right paren */ + /* If we haven't done so already, + * append a closing right paren + * and let the loop process it */ expr = ptr_to_rparen; - /* and let the loop process it. */ continue; } - /* At this point, we're done with the expression. */ + /* At this point, we're done with the expression */ if (numstackptr != numstack + 1) { - /* ... but if there isn't, it's bad */ + /* ...but if there isn't, it's bad */ goto err; } if (numstack->var) { @@ -619,11 +620,11 @@ arith(const char *expr, int *perrcode, a_e_h_t *math_hooks) /* We don't want an unary operator to cause recursive descent on the * stack, because there can be many in a row and it could cause an * operator to be evaluated before its argument is pushed onto the - * integer stack. */ - /* But for binary operators, "apply" everything on the operator + * integer stack. + * But for binary operators, "apply" everything on the operator * stack until we find an operator with a lesser priority than the - * one we have just extracted. */ - /* Left paren is given the lowest priority so it will never be + * one we have just extracted. + * Left paren is given the lowest priority so it will never be * "applied" in this way. * if associativity is right and priority eq, applied also skip */ @@ -641,17 +642,17 @@ arith(const char *expr, int *perrcode, a_e_h_t *math_hooks) * hit an open paren nor the bottom of the stack, pop * tokens and apply them */ if (prev_op == TOK_LPAREN) { - /* Any operator directly after a */ + /* Any operator directly after a + * close paren should consider itself binary */ lasttok = TOK_NUM; - /* close paren should consider itself binary */ goto next; } } else { operator prev_prec = PREC(prev_op); - convert_prec_is_assign(prec); - convert_prec_is_assign(prev_prec); + fix_assignment_prec(prec); + fix_assignment_prec(prev_prec); if (prev_prec < prec - || (prev_prec == prec && is_right_associativity(prec)) + || (prev_prec == prec && is_right_associative(prec)) ) { stackptr++; break; -- cgit v1.2.3-55-g6feb From 06d44d7dfb709bfe02e74d187cceb8591bbda3b4 Mon Sep 17 00:00:00 2001 From: Denys Vlasenko Date: Mon, 13 Sep 2010 12:49:03 +0200 Subject: shell/math.c: rename arith_eval_hooks to arith_state, put error code into it function old new delta expand_and_evaluate_arith 79 89 +10 arith 675 674 -1 arith_lookup_val 151 142 -9 ash_arith 135 122 -13 arith_apply 1304 1269 -35 ------------------------------------------------------------------------------ (add/remove: 0/0 grow/shrink: 1/4 up/down: 10/-58) Total: -48 bytes Signed-off-by: Denys Vlasenko --- shell/ash.c | 19 ++++++------- shell/hush.c | 11 ++++---- shell/math.c | 38 ++++++++++++------------- shell/math.h | 91 ++++++++++++++++++++++++++++++------------------------------ 4 files changed, 78 insertions(+), 81 deletions(-) (limited to 'shell') diff --git a/shell/ash.c b/shell/ash.c index f631e3d25..c27ab7de2 100644 --- a/shell/ash.c +++ b/shell/ash.c @@ -5442,22 +5442,21 @@ redirectsafe(union node *redir, int flags) static arith_t ash_arith(const char *s) { - arith_eval_hooks_t math_hooks; + arith_state_t math_state; arith_t result; - int errcode = 0; - math_hooks.lookupvar = lookupvar; - math_hooks.setvar = setvar2; - //math_hooks.endofname = endofname; + math_state.lookupvar = lookupvar; + math_state.setvar = setvar2; + //math_state.endofname = endofname; INT_OFF; - result = arith(s, &errcode, &math_hooks); - if (errcode < 0) { - if (errcode == -3) + result = arith(&math_state, s); + if (math_state.errcode < 0) { + if (math_state.errcode == -3) ash_msg_and_raise_error("exponent less than 0"); - if (errcode == -2) + if (math_state.errcode == -2) ash_msg_and_raise_error("divide by zero"); - if (errcode == -5) + if (math_state.errcode == -5) ash_msg_and_raise_error("expression recursion loop detected"); raise_error_syntax(s); } diff --git a/shell/hush.c b/shell/hush.c index ef0c454ec..4ca5403de 100644 --- a/shell/hush.c +++ b/shell/hush.c @@ -4463,15 +4463,16 @@ static char *encode_then_expand_string(const char *str, int process_bkslash, int #if ENABLE_SH_MATH_SUPPORT static arith_t expand_and_evaluate_arith(const char *arg, int *errcode_p) { - arith_eval_hooks_t hooks; + arith_state_t math_state; arith_t res; char *exp_str; - hooks.lookupvar = get_local_var_value; - hooks.setvar = set_local_var_from_halves; - //hooks.endofname = endofname; + math_state.lookupvar = get_local_var_value; + math_state.setvar = set_local_var_from_halves; + //math_state.endofname = endofname; exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1); - res = arith(exp_str ? exp_str : arg, errcode_p, &hooks); + res = arith(&math_state, exp_str ? exp_str : arg); + *errcode_p = math_state.errcode; free(exp_str); return res; } diff --git a/shell/math.c b/shell/math.c index a9fbc8910..555559a26 100644 --- a/shell/math.c +++ b/shell/math.c @@ -119,10 +119,9 @@ #include "libbb.h" #include "math.h" -#define a_e_h_t arith_eval_hooks_t -#define lookupvar (math_hooks->lookupvar) -#define setvar (math_hooks->setvar ) -//#define endofname (math_hooks->endofname) +#define lookupvar (math_state->lookupvar) +#define setvar (math_state->setvar ) +//#define endofname (math_state->endofname) typedef unsigned char operator; @@ -249,13 +248,12 @@ typedef struct chk_var_recursive_looped_t { static chk_var_recursive_looped_t *prev_chk_var_recursive; static int -arith_lookup_val(v_n_t *t, a_e_h_t *math_hooks) +arith_lookup_val(arith_state_t *math_state, v_n_t *t) { if (t->var) { const char *p = lookupvar(t->var); if (p) { - int errcode; chk_var_recursive_looped_t *cur; chk_var_recursive_looped_t cur_save; @@ -273,10 +271,10 @@ arith_lookup_val(v_n_t *t, a_e_h_t *math_hooks) cur_save.next = cur; prev_chk_var_recursive = &cur_save; - t->val = arith(p, &errcode, math_hooks); + t->val = arith(math_state, p); /* restore previous ptr after recursion */ prev_chk_var_recursive = cur; - return errcode; + return math_state->errcode; } /* allow undefined var as 0 */ t->val = 0; @@ -288,13 +286,13 @@ arith_lookup_val(v_n_t *t, a_e_h_t *math_hooks) * stack. For an unary operator it will only change the top element, but a * binary operator will pop two arguments and push the result */ static NOINLINE int -arith_apply(operator op, v_n_t *numstack, v_n_t **numstackptr, a_e_h_t *math_hooks) +arith_apply(arith_state_t *math_state, operator op, v_n_t *numstack, v_n_t **numstackptr) { #define NUMPTR (*numstackptr) v_n_t *numptr_m1; arith_t numptr_val, rez; - int ret_arith_lookup_val; + int err; /* There is no operator that can work without arguments */ if (NUMPTR == numstack) @@ -302,9 +300,9 @@ arith_apply(operator op, v_n_t *numstack, v_n_t **numstackptr, a_e_h_t *math_hoo numptr_m1 = NUMPTR - 1; /* Check operand is var with noninteger value */ - ret_arith_lookup_val = arith_lookup_val(numptr_m1, math_hooks); - if (ret_arith_lookup_val) - return ret_arith_lookup_val; + err = arith_lookup_val(math_state, numptr_m1); + if (err) + return err; rez = numptr_m1->val; if (op == TOK_UMINUS) @@ -339,9 +337,9 @@ arith_apply(operator op, v_n_t *numstack, v_n_t **numstackptr, a_e_h_t *math_hoo numptr_m1 = NUMPTR - 1; if (op != TOK_ASSIGN) { /* check operand is var with noninteger value for not '=' */ - ret_arith_lookup_val = arith_lookup_val(numptr_m1, math_hooks); - if (ret_arith_lookup_val) - return ret_arith_lookup_val; + err = arith_lookup_val(math_state, numptr_m1); + if (err) + return err; } if (op == TOK_CONDITIONAL) { numptr_m1->contidional_second_val = rez; @@ -490,7 +488,7 @@ endofname(const char *name) } arith_t -arith(const char *expr, int *perrcode, a_e_h_t *math_hooks) +arith(arith_state_t *math_state, const char *expr) { operator lasttok; int errcode; @@ -543,7 +541,7 @@ arith(const char *expr, int *perrcode, a_e_h_t *math_hooks) } if (numstack->var) { /* expression is $((var)) only, lookup now */ - errcode = arith_lookup_val(numstack, math_hooks); + errcode = arith_lookup_val(math_state, numstack); } goto ret; } @@ -658,7 +656,7 @@ arith(const char *expr, int *perrcode, a_e_h_t *math_hooks) break; } } - errcode = arith_apply(prev_op, numstack, &numstackptr, math_hooks); + errcode = arith_apply(math_state, prev_op, numstack, &numstackptr); if (errcode) goto ret; } @@ -675,7 +673,7 @@ arith(const char *expr, int *perrcode, a_e_h_t *math_hooks) err: numstack->val = errcode = -1; ret: - *perrcode = errcode; + math_state->errcode = errcode; return numstack->val; } diff --git a/shell/math.h b/shell/math.h index 96088b4d2..9f3da7f59 100644 --- a/shell/math.h +++ b/shell/math.h @@ -9,61 +9,59 @@ /* The math library has just one function: * - * arith_t arith(const char *expr, int *perrcode, arith_eval_hooks_t *hooks); + * arith_t arith(arith_state_t *states, const char *expr); * - * The first argument is the math string to parse. All normal expansions must - * be done already. i.e. no dollar symbols should be present. + * The expr argument is the math string to parse. All normal expansions must + * be done already. i.e. no dollar symbols should be present. * - * The second argument is a semi-detailed error description in case something - * goes wrong in the parsing steps. Currently, those values are (for - * compatibility, you should assume all negative values are errors): - * 0 - no errors (yay!) - * -1 - unspecified problem - * -2 - divide by zero - * -3 - exponent less than 0 - * -5 - expression recursion loop detected + * The state argument is a pointer to a struct of hooks for your shell (see below), + * and a semi-detailed error code. Currently, those values are (for + * compatibility, you should assume all negative values are errors): + * 0 - no errors (yay!) + * -1 - unspecified problem + * -2 - divide by zero + * -3 - exponent less than 0 + * -5 - expression recursion loop detected * - * The third argument is a struct pointer of hooks for your shell (see below). - * - * The function returns the answer to the expression. So if you called it - * with the expression: - * "1 + 2 + 3" - * You would obviously get back 6. + * The function returns the answer to the expression. So if you called it + * with the expression: + * "1 + 2 + 3" + * you would obviously get back 6. */ /* To add support to a shell, you need to implement three functions: * - * lookupvar() - look up and return the value of a variable + * lookupvar() - look up and return the value of a variable * - * If the shell does: - * foo=123 - * Then the code: - * const char *val = lookupvar("foo"); - * Will result in val pointing to "123" + * If the shell does: + * foo=123 + * Then the code: + * const char *val = lookupvar("foo"); + * will result in val pointing to "123" * - * setvar() - set a variable to some value + * setvar() - set a variable to some value * - * If the arithmetic expansion does something like: - * $(( i = 1)) - * Then the math code will make a call like so: - * setvar("i", "1", 0); - * The storage for the first two parameters are not allocated, so your - * shell implementation will most likely need to strdup() them to save. + * If the arithmetic expansion does something like: + * $(( i = 1)) + * then the math code will make a call like so: + * setvar("i", "1", 0); + * The storage for the first two parameters are not allocated, so your + * shell implementation will most likely need to strdup() them to save. * - * endofname() - return the end of a variable name from input + * endofname() - return the end of a variable name from input * - * The arithmetic code does not know about variable naming conventions. - * So when it is given an experession, it knows something is not numeric, - * but it is up to the shell to dictate what is a valid identifiers. - * So when it encounters something like: - * $(( some_var + 123 )) - * It will make a call like so: - * end = endofname("some_var + 123"); - * So the shell needs to scan the input string and return a pointer to the - * first non-identifier string. In this case, it should return the input - * pointer with an offset pointing to the first space. The typical - * implementation will return the offset of first char that does not match - * the regex (in C locale): ^[a-zA-Z_][a-zA-Z_0-9]* + * The arithmetic code does not know about variable naming conventions. + * So when it is given an experession, it knows something is not numeric, + * but it is up to the shell to dictate what is a valid identifiers. + * So when it encounters something like: + * $(( some_var + 123 )) + * It will make a call like so: + * end = endofname("some_var + 123"); + * So the shell needs to scan the input string and return a pointer to the + * first non-identifier string. In this case, it should return the input + * pointer with an offset pointing to the first space. The typical + * implementation will return the offset of first char that does not match + * the regex (in C locale): ^[a-zA-Z_][a-zA-Z_0-9]* */ /* To make your life easier when dealing with optional 64bit math support, @@ -96,13 +94,14 @@ typedef const char* FAST_FUNC (*arith_var_lookup_t)(const char *name); typedef void FAST_FUNC (*arith_var_set_t)(const char *name, const char *val); //typedef const char* FAST_FUNC (*arith_var_endofname_t)(const char *name); -typedef struct arith_eval_hooks { +typedef struct arith_state_t { arith_var_lookup_t lookupvar; arith_var_set_t setvar; // arith_var_endofname_t endofname; -} arith_eval_hooks_t; + int errcode; +} arith_state_t; -arith_t arith(const char *expr, int *perrcode, arith_eval_hooks_t*); +arith_t arith(arith_state_t *state, const char *expr); POP_SAVED_FUNCTION_VISIBILITY -- cgit v1.2.3-55-g6feb From 0eac8ff1648f94a79a0e21731ec993dd73d946db Mon Sep 17 00:00:00 2001 From: Denys Vlasenko Date: Mon, 13 Sep 2010 12:49:52 +0200 Subject: shell/math.c: stop using bss variable function old new delta evaluate_string - 678 +678 expand_one_var 1543 1563 +20 builtin_type 114 116 +2 expand_and_evaluate_arith 89 87 -2 prev_chk_var_recursive 4 - -4 ash_arith 122 118 -4 arith_lookup_val 142 132 -10 arith 674 12 -662 ------------------------------------------------------------------------------ (add/remove: 1/1 grow/shrink: 2/4 up/down: 700/-682) Total: 18 bytes Signed-off-by: Denys Vlasenko --- shell/math.c | 54 ++++++++++++++++++++++++++++++++++-------------------- shell/math.h | 5 +++-- 2 files changed, 37 insertions(+), 22 deletions(-) (limited to 'shell') diff --git a/shell/math.c b/shell/math.c index 555559a26..839715776 100644 --- a/shell/math.c +++ b/shell/math.c @@ -232,6 +232,7 @@ is_right_associative(operator prec) || prec == PREC(TOK_CONDITIONAL)); } + typedef struct { arith_t val; arith_t contidional_second_val; @@ -240,43 +241,49 @@ typedef struct { else is variable name */ } v_n_t; -typedef struct chk_var_recursive_looped_t { +typedef struct remembered_name { + struct remembered_name *next; const char *var; - struct chk_var_recursive_looped_t *next; -} chk_var_recursive_looped_t; +} remembered_name; + -static chk_var_recursive_looped_t *prev_chk_var_recursive; +static arith_t FAST_FUNC +evaluate_string(arith_state_t *math_state, const char *expr); static int arith_lookup_val(arith_state_t *math_state, v_n_t *t) { if (t->var) { const char *p = lookupvar(t->var); - if (p) { - chk_var_recursive_looped_t *cur; - chk_var_recursive_looped_t cur_save; + remembered_name *cur; + remembered_name cur_save; - /* recursively try p as expression */ - - for (cur = prev_chk_var_recursive; cur; cur = cur->next) { + /* did we already see this name? + * testcase: a=b; b=a; echo $((a)) + */ + for (cur = math_state->list_of_recursed_names; cur; cur = cur->next) { if (strcmp(cur->var, t->var) == 0) { - /* expression recursion loop detected */ + /* Yes. Expression recursion loop detected */ return -5; } } - /* save current var name */ - cur = prev_chk_var_recursive; + + /* push current var name */ + cur = math_state->list_of_recursed_names; cur_save.var = t->var; cur_save.next = cur; - prev_chk_var_recursive = &cur_save; + math_state->list_of_recursed_names = &cur_save; + + /* recursively evaluate p as expression */ + t->val = evaluate_string(math_state, p); + + /* pop current var name */ + math_state->list_of_recursed_names = cur; - t->val = arith(math_state, p); - /* restore previous ptr after recursion */ - prev_chk_var_recursive = cur; return math_state->errcode; } - /* allow undefined var as 0 */ + /* treat undefined var as 0 */ t->val = 0; } return 0; @@ -487,8 +494,8 @@ endofname(const char *name) return name; } -arith_t -arith(arith_state_t *math_state, const char *expr) +static arith_t FAST_FUNC +evaluate_string(arith_state_t *math_state, const char *expr) { operator lasttok; int errcode; @@ -677,6 +684,13 @@ arith(arith_state_t *math_state, const char *expr) return numstack->val; } +arith_t FAST_FUNC +arith(arith_state_t *math_state, const char *expr) +{ + math_state->list_of_recursed_names = NULL; + return evaluate_string(math_state, expr); +} + /* * Copyright (c) 1989, 1991, 1993, 1994 * The Regents of the University of California. All rights reserved. diff --git a/shell/math.h b/shell/math.h index 9f3da7f59..e34b65d5d 100644 --- a/shell/math.h +++ b/shell/math.h @@ -95,13 +95,14 @@ typedef void FAST_FUNC (*arith_var_set_t)(const char *name, const char *v //typedef const char* FAST_FUNC (*arith_var_endofname_t)(const char *name); typedef struct arith_state_t { + int errcode; arith_var_lookup_t lookupvar; arith_var_set_t setvar; // arith_var_endofname_t endofname; - int errcode; + void *list_of_recursed_names; } arith_state_t; -arith_t arith(arith_state_t *state, const char *expr); +arith_t FAST_FUNC arith(arith_state_t *state, const char *expr); POP_SAVED_FUNCTION_VISIBILITY -- cgit v1.2.3-55-g6feb From 063847d6bd23e184c409f37645ba90fa4d039ada Mon Sep 17 00:00:00 2001 From: Denys Vlasenko Date: Wed, 15 Sep 2010 13:33:02 +0200 Subject: shell/math: return string error indicator, not integer function old new delta expand_and_evaluate_arith 87 106 +19 expand_one_var 1563 1570 +7 arith 12 18 +6 evaluate_string 678 680 +2 arith_apply 1269 1271 +2 builtin_umask 133 132 -1 ash_arith 118 75 -43 expand_vars_to_list 1094 1038 -56 ------------------------------------------------------------------------------ (add/remove: 0/0 grow/shrink: 5/3 up/down: 36/-100) Total: -64 bytes Signed-off-by: Denys Vlasenko --- shell/ash.c | 11 +---- shell/ash_test/ash-arith/arith.right | 56 +++++++++++------------ shell/hush.c | 40 +++++++---------- shell/hush_test/hush-arith/arith.right | 54 +++++++++++------------ shell/math.c | 81 +++++++++++++++++----------------- shell/math.h | 2 +- 6 files changed, 113 insertions(+), 131 deletions(-) (limited to 'shell') diff --git a/shell/ash.c b/shell/ash.c index c27ab7de2..ec887e088 100644 --- a/shell/ash.c +++ b/shell/ash.c @@ -5451,15 +5451,8 @@ ash_arith(const char *s) INT_OFF; result = arith(&math_state, s); - if (math_state.errcode < 0) { - if (math_state.errcode == -3) - ash_msg_and_raise_error("exponent less than 0"); - if (math_state.errcode == -2) - ash_msg_and_raise_error("divide by zero"); - if (math_state.errcode == -5) - ash_msg_and_raise_error("expression recursion loop detected"); - raise_error_syntax(s); - } + if (math_state.errmsg) + ash_msg_and_raise_error(math_state.errmsg); INT_ON; return result; diff --git a/shell/ash_test/ash-arith/arith.right b/shell/ash_test/ash-arith/arith.right index 3ea7ce680..7257cc566 100644 --- a/shell/ash_test/ash-arith/arith.right +++ b/shell/ash_test/ash-arith/arith.right @@ -55,28 +55,28 @@ Format: 'expected actual' 30 30 20 20 30 30 -./arith.tests: line 117: syntax error: 1 ? 20 : x+=2 +./arith.tests: line 117: arithmetic syntax error 6 6 6,5,3 6,5,3 263 263 255 255 40 40 -./arith.tests: line 163: syntax error: 7 = 43 +./arith.tests: line 163: arithmetic syntax error ./arith.tests: line 165: divide by zero -./arith.tests: let: line 166: syntax error: jv += $iv -./arith.tests: line 167: syntax error: jv += $iv -./arith.tests: let: line 168: syntax error: rv = 7 + (43 * 6 +./arith.tests: let: line 166: arithmetic syntax error +./arith.tests: line 167: arithmetic syntax error +./arith.tests: let: line 168: arithmetic syntax error abc def ghi -./arith.tests: line 191: syntax error: ( 4 + A ) + 4 +./arith.tests: line 191: arithmetic syntax error 16 16 -./arith.tests: line 196: syntax error: 4 ? : 3 + 5 -./arith.tests: line 197: syntax error: 1 ? 20 -./arith.tests: line 198: syntax error: 4 ? 20 : +./arith.tests: line 196: arithmetic syntax error +./arith.tests: line 197: arithmetic syntax error +./arith.tests: line 198: arithmetic syntax error 9 9 -./arith.tests: line 205: syntax error: 0 && B=42 -./arith.tests: line 208: syntax error: 1 || B=88 +./arith.tests: line 205: arithmetic syntax error +./arith.tests: line 208: arithmetic syntax error 9 9 9 9 9 9 @@ -97,18 +97,18 @@ ghi 3 3 4 4 4 4 -./arith.tests: line 257: syntax error: 7-- -./arith.tests: line 259: syntax error: --x=7 -./arith.tests: line 260: syntax error: ++x=7 -./arith.tests: line 262: syntax error: x++=7 -./arith.tests: line 263: syntax error: x--=7 +./arith.tests: line 257: arithmetic syntax error +./arith.tests: line 259: arithmetic syntax error +./arith.tests: line 260: arithmetic syntax error +./arith.tests: line 262: arithmetic syntax error +./arith.tests: line 263: arithmetic syntax error 4 4 7 7 -7 -7 -./arith1.sub: line 2: syntax error: 4-- -./arith1.sub: line 3: syntax error: 4++ -./arith1.sub: line 4: syntax error: 4 -- -./arith1.sub: line 5: syntax error: 4 ++ +./arith1.sub: line 2: arithmetic syntax error +./arith1.sub: line 3: arithmetic syntax error +./arith1.sub: line 4: arithmetic syntax error +./arith1.sub: line 5: arithmetic syntax error 6 6 3 3 7 7 @@ -119,19 +119,19 @@ ghi 2 2 -2 -2 1 1 -./arith1.sub: line 37: syntax error: +++7 -./arith2.sub: line 2: syntax error: --7 -./arith2.sub: line 3: syntax error: ++7 -./arith2.sub: line 4: syntax error: -- 7 -./arith2.sub: line 5: syntax error: ++ 7 +./arith1.sub: line 37: arithmetic syntax error +./arith2.sub: line 2: arithmetic syntax error +./arith2.sub: line 3: arithmetic syntax error +./arith2.sub: line 4: arithmetic syntax error +./arith2.sub: line 5: arithmetic syntax error 5 5 1 1 4 4 0 0 -./arith2.sub: line 42: syntax error: -- - 7 -./arith2.sub: line 47: syntax error: ++ + 7 +./arith2.sub: line 42: arithmetic syntax error +./arith2.sub: line 47: arithmetic syntax error 8 12 -./arith.tests: line 290: syntax error: a b +./arith.tests: line 290: arithmetic syntax error 42 42 42 diff --git a/shell/hush.c b/shell/hush.c index 4ca5403de..ad30ac1ea 100644 --- a/shell/hush.c +++ b/shell/hush.c @@ -4461,7 +4461,7 @@ static char *encode_then_expand_string(const char *str, int process_bkslash, int } #if ENABLE_SH_MATH_SUPPORT -static arith_t expand_and_evaluate_arith(const char *arg, int *errcode_p) +static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p) { arith_state_t math_state; arith_t res; @@ -4472,8 +4472,11 @@ static arith_t expand_and_evaluate_arith(const char *arg, int *errcode_p) //math_state.endofname = endofname; exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1); res = arith(&math_state, exp_str ? exp_str : arg); - *errcode_p = math_state.errcode; free(exp_str); + if (errmsg_p) + *errmsg_p = math_state.errmsg; + if (math_state.errmsg) + die_if_script(math_state.errmsg); return res; } #endif @@ -4714,22 +4717,26 @@ static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, cha * var:NM */ arith_t beg, len; - int errcode = 0; + const char *errmsg; - beg = expand_and_evaluate_arith(exp_word, &errcode); + beg = expand_and_evaluate_arith(exp_word, &errmsg); + if (errmsg) + goto arith_err; debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg); *p++ = SPECIAL_VAR_SYMBOL; exp_word = p; p = strchr(p, SPECIAL_VAR_SYMBOL); *p = '\0'; - len = expand_and_evaluate_arith(exp_word, &errcode); + len = expand_and_evaluate_arith(exp_word, &errmsg); + if (errmsg) + goto arith_err; debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len); - - if (errcode >= 0 && len >= 0) { /* bash compat: len < 0 is illegal */ + if (len >= 0) { /* bash compat: len < 0 is illegal */ if (beg < 0) /* bash compat */ beg = 0; debug_printf_varexp("from val:'%s'\n", val); if (len == 0 || !val || beg >= strlen(val)) { + arith_err: val = NULL; } else { /* Paranoia. What if user entered 9999999999999 @@ -4926,28 +4933,11 @@ static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg) #if ENABLE_SH_MATH_SUPPORT case '+': { /* +cmd */ arith_t res; - int errcode; arg++; /* skip '+' */ *p = '\0'; /* replace trailing */ debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch); - res = expand_and_evaluate_arith(arg, &errcode); - - if (errcode < 0) { - const char *msg = "error in arithmetic"; - switch (errcode) { - case -3: - msg = "exponent less than 0"; - break; - case -2: - msg = "divide by 0"; - break; - case -5: - msg = "expression recursion loop detected"; - break; - } - die_if_script(msg); - } + res = expand_and_evaluate_arith(arg, NULL); debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res); sprintf(arith_buf, arith_t_fmt, res); val = arith_buf; diff --git a/shell/hush_test/hush-arith/arith.right b/shell/hush_test/hush-arith/arith.right index 718c26ad0..fd4ea8e01 100644 --- a/shell/hush_test/hush-arith/arith.right +++ b/shell/hush_test/hush-arith/arith.right @@ -61,7 +61,7 @@ check that the unevaluated part of the ternary operator does not do evaluation o 20 20 30 30 check precedence of assignment vs. conditional operator -hush: error in arithmetic +hush: arithmetic syntax error check precedence of assignment vs. conditional operator associativity of assignment-operator operator 6 6 @@ -70,22 +70,22 @@ octal, hex 263 263 255 255 40 40 -hush: error in arithmetic -hush: divide by 0 +hush: arithmetic syntax error +hush: divide by zero hush: can't execute 'let': No such file or directory -hush: error in arithmetic +hush: arithmetic syntax error hush: can't execute 'let': No such file or directory abc def ghi -hush: error in arithmetic +hush: arithmetic syntax error 16 16 -hush: error in arithmetic -hush: error in arithmetic -hush: error in arithmetic +hush: arithmetic syntax error +hush: arithmetic syntax error +hush: arithmetic syntax error 9 9 -hush: error in arithmetic -hush: error in arithmetic +hush: arithmetic syntax error +hush: arithmetic syntax error 9 9 9 9 9 9 @@ -106,18 +106,18 @@ hush: error in arithmetic 3 3 4 4 4 4 -hush: error in arithmetic -hush: error in arithmetic -hush: error in arithmetic -hush: error in arithmetic -hush: error in arithmetic +hush: arithmetic syntax error +hush: arithmetic syntax error +hush: arithmetic syntax error +hush: arithmetic syntax error +hush: arithmetic syntax error 4 4 7 7 -7 -7 -hush: error in arithmetic -hush: error in arithmetic -hush: error in arithmetic -hush: error in arithmetic +hush: arithmetic syntax error +hush: arithmetic syntax error +hush: arithmetic syntax error +hush: arithmetic syntax error 6 6 3 3 7 7 @@ -128,19 +128,19 @@ hush: error in arithmetic 2 2 -2 -2 1 1 -hush: error in arithmetic -hush: error in arithmetic -hush: error in arithmetic -hush: error in arithmetic -hush: error in arithmetic +hush: arithmetic syntax error +hush: arithmetic syntax error +hush: arithmetic syntax error +hush: arithmetic syntax error +hush: arithmetic syntax error 5 5 1 1 4 4 0 0 -hush: error in arithmetic -hush: error in arithmetic +hush: arithmetic syntax error +hush: arithmetic syntax error 8 12 -hush: error in arithmetic +hush: arithmetic syntax error 42 42 42 diff --git a/shell/math.c b/shell/math.c index 839715776..871c06c3e 100644 --- a/shell/math.c +++ b/shell/math.c @@ -26,26 +26,26 @@ * Licensed under GPLv2 or later, see file LICENSE in this source tree. */ /* Copyright (c) 2001 Aaron Lehmann - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - "Software"), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ /* This is my infix parser/evaluator. It is optimized for size, intended * as a replacement for yacc-based parsers. However, it may well be faster @@ -60,9 +60,6 @@ * this is based (this code differs in that it applies operators immediately * to the stack instead of adding them to a queue to end up with an * expression). - * - * To use the routine, call it with an expression string and error return - * pointer */ /* @@ -250,7 +247,7 @@ typedef struct remembered_name { static arith_t FAST_FUNC evaluate_string(arith_state_t *math_state, const char *expr); -static int +static const char* arith_lookup_val(arith_state_t *math_state, v_n_t *t) { if (t->var) { @@ -264,8 +261,8 @@ arith_lookup_val(arith_state_t *math_state, v_n_t *t) */ for (cur = math_state->list_of_recursed_names; cur; cur = cur->next) { if (strcmp(cur->var, t->var) == 0) { - /* Yes. Expression recursion loop detected */ - return -5; + /* Yes */ + return "expression recursion loop detected"; } } @@ -281,7 +278,7 @@ arith_lookup_val(arith_state_t *math_state, v_n_t *t) /* pop current var name */ math_state->list_of_recursed_names = cur; - return math_state->errcode; + return math_state->errmsg; } /* treat undefined var as 0 */ t->val = 0; @@ -292,14 +289,14 @@ arith_lookup_val(arith_state_t *math_state, v_n_t *t) /* "Applying" a token means performing it on the top elements on the integer * stack. For an unary operator it will only change the top element, but a * binary operator will pop two arguments and push the result */ -static NOINLINE int +static NOINLINE const char* arith_apply(arith_state_t *math_state, operator op, v_n_t *numstack, v_n_t **numstackptr) { #define NUMPTR (*numstackptr) v_n_t *numptr_m1; arith_t numptr_val, rez; - int err; + const char *err; /* There is no operator that can work without arguments */ if (NUMPTR == numstack) @@ -399,13 +396,13 @@ arith_apply(arith_state_t *math_state, operator op, v_n_t *numstack, v_n_t **num } else if (op == TOK_EXPONENT) { arith_t c; if (numptr_val < 0) - return -3; /* exponent less than 0 */ + return "exponent less than 0"; c = 1; while (--numptr_val >= 0) c *= rez; rez = c; - } else if (numptr_val==0) /* zero divisor check */ - return -2; + } else if (numptr_val == 0) + return "divide by zero"; else if (op == TOK_DIV || op == TOK_DIV_ASSIGN) rez /= numptr_val; else if (op == TOK_REM || op == TOK_REM_ASSIGN) @@ -430,9 +427,9 @@ arith_apply(arith_state_t *math_state, operator op, v_n_t *numstack, v_n_t **num numptr_m1->val = rez; /* erase var name, it is just a number now */ numptr_m1->var = NULL; - return 0; + return NULL; err: - return -1; + return "arithmetic syntax error"; #undef NUMPTR } @@ -498,7 +495,7 @@ static arith_t FAST_FUNC evaluate_string(arith_state_t *math_state, const char *expr) { operator lasttok; - int errcode; + const char *errmsg; const char *start_expr = expr = skip_whitespace(expr); unsigned expr_len = strlen(expr) + 2; /* Stack of integers */ @@ -512,7 +509,7 @@ evaluate_string(arith_state_t *math_state, const char *expr) operator *stackptr = stack; *stackptr++ = lasttok = TOK_LPAREN; /* start off with a left paren */ - errcode = 0; + errmsg = NULL; while (1) { const char *p; @@ -548,7 +545,7 @@ evaluate_string(arith_state_t *math_state, const char *expr) } if (numstack->var) { /* expression is $((var)) only, lookup now */ - errcode = arith_lookup_val(math_state, numstack); + errmsg = arith_lookup_val(math_state, numstack); } goto ret; } @@ -663,8 +660,8 @@ evaluate_string(arith_state_t *math_state, const char *expr) break; } } - errcode = arith_apply(math_state, prev_op, numstack, &numstackptr); - if (errcode) + errmsg = arith_apply(math_state, prev_op, numstack, &numstackptr); + if (errmsg) goto ret; } if (op == TOK_RPAREN) { @@ -678,15 +675,17 @@ evaluate_string(arith_state_t *math_state, const char *expr) } /* while (1) */ err: - numstack->val = errcode = -1; + numstack->val = -1; + errmsg = "arithmetic syntax error"; ret: - math_state->errcode = errcode; + math_state->errmsg = errmsg; return numstack->val; } arith_t FAST_FUNC arith(arith_state_t *math_state, const char *expr) { + math_state->errmsg = NULL; math_state->list_of_recursed_names = NULL; return evaluate_string(math_state, expr); } diff --git a/shell/math.h b/shell/math.h index e34b65d5d..2dcab130d 100644 --- a/shell/math.h +++ b/shell/math.h @@ -95,7 +95,7 @@ typedef void FAST_FUNC (*arith_var_set_t)(const char *name, const char *v //typedef const char* FAST_FUNC (*arith_var_endofname_t)(const char *name); typedef struct arith_state_t { - int errcode; + const char *errmsg; arith_var_lookup_t lookupvar; arith_var_set_t setvar; // arith_var_endofname_t endofname; -- cgit v1.2.3-55-g6feb From bed7c81ea24e9e9ba2a897e233de2abefe611e8b Mon Sep 17 00:00:00 2001 From: Denys Vlasenko Date: Thu, 16 Sep 2010 11:50:46 +0200 Subject: shell/math: deconvolute and explain ?: handling. Give better error message function old new delta arith_apply 1271 1283 +12 Signed-off-by: Denys Vlasenko --- shell/ash.c | 2 +- shell/ash_test/ash-arith/arith.right | 2 +- shell/hush.c | 4 +- shell/hush_test/hush-arith/arith.right | 2 +- shell/math.c | 243 ++++++++++++++++++--------------- shell/math.h | 20 +-- 6 files changed, 144 insertions(+), 129 deletions(-) (limited to 'shell') diff --git a/shell/ash.c b/shell/ash.c index ec887e088..9089adc63 100644 --- a/shell/ash.c +++ b/shell/ash.c @@ -5516,7 +5516,7 @@ cvtnum(arith_t num) int len; expdest = makestrspace(32, expdest); - len = fmtstr(expdest, 32, arith_t_fmt, num); + len = fmtstr(expdest, 32, ARITH_FMT, num); STADJUST(len, expdest); return len; } diff --git a/shell/ash_test/ash-arith/arith.right b/shell/ash_test/ash-arith/arith.right index 7257cc566..9b9ca8e2f 100644 --- a/shell/ash_test/ash-arith/arith.right +++ b/shell/ash_test/ash-arith/arith.right @@ -72,7 +72,7 @@ ghi ./arith.tests: line 191: arithmetic syntax error 16 16 ./arith.tests: line 196: arithmetic syntax error -./arith.tests: line 197: arithmetic syntax error +./arith.tests: line 197: malformed ?: operator ./arith.tests: line 198: arithmetic syntax error 9 9 ./arith.tests: line 205: arithmetic syntax error diff --git a/shell/hush.c b/shell/hush.c index ad30ac1ea..a888332bc 100644 --- a/shell/hush.c +++ b/shell/hush.c @@ -4938,8 +4938,8 @@ static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg) *p = '\0'; /* replace trailing */ debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch); res = expand_and_evaluate_arith(arg, NULL); - debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res); - sprintf(arith_buf, arith_t_fmt, res); + debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res); + sprintf(arith_buf, ARITH_FMT, res); val = arith_buf; break; } diff --git a/shell/hush_test/hush-arith/arith.right b/shell/hush_test/hush-arith/arith.right index fd4ea8e01..8a201fb3b 100644 --- a/shell/hush_test/hush-arith/arith.right +++ b/shell/hush_test/hush-arith/arith.right @@ -81,7 +81,7 @@ ghi hush: arithmetic syntax error 16 16 hush: arithmetic syntax error -hush: arithmetic syntax error +hush: malformed ?: operator hush: arithmetic syntax error 9 9 hush: arithmetic syntax error diff --git a/shell/math.c b/shell/math.c index 871c06c3e..9d3b912a7 100644 --- a/shell/math.c +++ b/shell/math.c @@ -1,5 +1,5 @@ /* - * arithmetic code ripped out of ash shell for code sharing + * Arithmetic code ripped out of ash shell for code sharing. * * This code is derived from software contributed to Berkeley by * Kenneth Almquist. @@ -154,7 +154,7 @@ typedef unsigned char operator; #define fix_assignment_prec(prec) do { if (prec == 3) prec = 2; } while (0) -/* ternary conditional operator is right associative too */ +/* Ternary conditional operator is right associative too */ #define TOK_CONDITIONAL tok_decl(4,0) #define TOK_CONDITIONAL_SEP tok_decl(4,1) @@ -186,10 +186,10 @@ typedef unsigned char operator; #define TOK_DIV tok_decl(14,1) #define TOK_REM tok_decl(14,2) -/* exponent is right associative */ +/* Exponent is right associative */ #define TOK_EXPONENT tok_decl(15,1) -/* unary operators */ +/* Unary operators */ #define UNARYPREC 16 #define TOK_BNOT tok_decl(UNARYPREC,0) #define TOK_NOT tok_decl(UNARYPREC,1) @@ -213,30 +213,37 @@ typedef unsigned char operator; #define TOK_RPAREN tok_decl(SPEC_PREC, 1) static int -tok_have_assign(operator op) +is_assign_op(operator op) { operator prec = PREC(op); - fix_assignment_prec(prec); - return (prec == PREC(TOK_ASSIGN) || - prec == PREC_PRE || prec == PREC_POST); + return prec == PREC(TOK_ASSIGN) + || prec == PREC_PRE + || prec == PREC_POST; } static int is_right_associative(operator prec) { - return (prec == PREC(TOK_ASSIGN) || prec == PREC(TOK_EXPONENT) - || prec == PREC(TOK_CONDITIONAL)); + return prec == PREC(TOK_ASSIGN) + || prec == PREC(TOK_EXPONENT) + || prec == PREC(TOK_CONDITIONAL); } typedef struct { arith_t val; - arith_t contidional_second_val; - char contidional_second_val_initialized; - char *var; /* if NULL then is regular number, - else is variable name */ -} v_n_t; + /* We acquire second_val only when "expr1 : expr2" part + * of ternary ?: op is evaluated. + * We treat ?: as two binary ops: (expr ? (expr1 : expr2)). + * ':' produces a new value which has two parts, val and second_val; + * then '?' selects one of them based on its left side. + */ + arith_t second_val; + char second_val_present; + /* If NULL then it's just a number, else it's a named variable */ + char *var; +} var_or_num_t; typedef struct remembered_name { struct remembered_name *next; @@ -248,7 +255,7 @@ static arith_t FAST_FUNC evaluate_string(arith_state_t *math_state, const char *expr); static const char* -arith_lookup_val(arith_state_t *math_state, v_n_t *t) +arith_lookup_val(arith_state_t *math_state, var_or_num_t *t) { if (t->var) { const char *p = lookupvar(t->var); @@ -290,27 +297,28 @@ arith_lookup_val(arith_state_t *math_state, v_n_t *t) * stack. For an unary operator it will only change the top element, but a * binary operator will pop two arguments and push the result */ static NOINLINE const char* -arith_apply(arith_state_t *math_state, operator op, v_n_t *numstack, v_n_t **numstackptr) +arith_apply(arith_state_t *math_state, operator op, var_or_num_t *numstack, var_or_num_t **numstackptr) { #define NUMPTR (*numstackptr) - v_n_t *numptr_m1; - arith_t numptr_val, rez; + var_or_num_t *top_of_stack; + arith_t rez; const char *err; /* There is no operator that can work without arguments */ if (NUMPTR == numstack) goto err; - numptr_m1 = NUMPTR - 1; - /* Check operand is var with noninteger value */ - err = arith_lookup_val(math_state, numptr_m1); + top_of_stack = NUMPTR - 1; + + /* Resolve name to value, if needed */ + err = arith_lookup_val(math_state, top_of_stack); if (err) return err; - rez = numptr_m1->val; + rez = top_of_stack->val; if (op == TOK_UMINUS) - rez *= -1; + rez = -rez; else if (op == TOK_NOT) rez = !rez; else if (op == TOK_BNOT) @@ -321,112 +329,119 @@ arith_apply(arith_state_t *math_state, operator op, v_n_t *numstack, v_n_t **num rez--; else if (op != TOK_UPLUS) { /* Binary operators */ + arith_t right_side_val; + char bad_second_val; - /* check and binary operators need two arguments */ - if (numptr_m1 == numstack) goto err; - - /* ... and they pop one */ - --NUMPTR; - numptr_val = rez; - if (op == TOK_CONDITIONAL) { - if (!numptr_m1->contidional_second_val_initialized) { - /* protect $((expr1 ? expr2)) without ": expr" */ - goto err; - } - rez = numptr_m1->contidional_second_val; - } else if (numptr_m1->contidional_second_val_initialized) { - /* protect $((expr1 : expr2)) without "expr ? " */ + /* Binary operators need two arguments */ + if (top_of_stack == numstack) goto err; + /* ...and they pop one */ + NUMPTR = top_of_stack; /* this decrements NUMPTR */ + + bad_second_val = top_of_stack->second_val_present; + if (op == TOK_CONDITIONAL) { /* ? operation */ + /* Make next if (...) protect against + * $((expr1 ? expr2)) - that is, missing ": expr" */ + bad_second_val = !bad_second_val; + } + if (bad_second_val) { + /* Protect against $((expr expr1 : expr2)) */ + return "malformed ?: operator"; } - numptr_m1 = NUMPTR - 1; + + top_of_stack--; /* now points to left side */ + if (op != TOK_ASSIGN) { - /* check operand is var with noninteger value for not '=' */ - err = arith_lookup_val(math_state, numptr_m1); + /* Resolve left side value (unless the op is '=') */ + err = arith_lookup_val(math_state, top_of_stack); if (err) return err; } - if (op == TOK_CONDITIONAL) { - numptr_m1->contidional_second_val = rez; + + right_side_val = rez; + rez = top_of_stack->val; + if (op == TOK_CONDITIONAL) /* ? operation */ + rez = (rez ? right_side_val : top_of_stack[1].second_val); + else if (op == TOK_CONDITIONAL_SEP) { /* : operation */ + if (top_of_stack == numstack) { + /* Protect against $((expr : expr)) */ + return "malformed ?: operator"; + } + top_of_stack->second_val_present = op; + top_of_stack->second_val = right_side_val; } - rez = numptr_m1->val; - if (op == TOK_BOR || op == TOK_OR_ASSIGN) - rez |= numptr_val; + else if (op == TOK_BOR || op == TOK_OR_ASSIGN) + rez |= right_side_val; else if (op == TOK_OR) - rez = numptr_val || rez; + rez = right_side_val || rez; else if (op == TOK_BAND || op == TOK_AND_ASSIGN) - rez &= numptr_val; + rez &= right_side_val; else if (op == TOK_BXOR || op == TOK_XOR_ASSIGN) - rez ^= numptr_val; + rez ^= right_side_val; else if (op == TOK_AND) - rez = rez && numptr_val; + rez = rez && right_side_val; else if (op == TOK_EQ) - rez = (rez == numptr_val); + rez = (rez == right_side_val); else if (op == TOK_NE) - rez = (rez != numptr_val); + rez = (rez != right_side_val); else if (op == TOK_GE) - rez = (rez >= numptr_val); + rez = (rez >= right_side_val); else if (op == TOK_RSHIFT || op == TOK_RSHIFT_ASSIGN) - rez >>= numptr_val; + rez >>= right_side_val; else if (op == TOK_LSHIFT || op == TOK_LSHIFT_ASSIGN) - rez <<= numptr_val; + rez <<= right_side_val; else if (op == TOK_GT) - rez = (rez > numptr_val); + rez = (rez > right_side_val); else if (op == TOK_LT) - rez = (rez < numptr_val); + rez = (rez < right_side_val); else if (op == TOK_LE) - rez = (rez <= numptr_val); + rez = (rez <= right_side_val); else if (op == TOK_MUL || op == TOK_MUL_ASSIGN) - rez *= numptr_val; + rez *= right_side_val; else if (op == TOK_ADD || op == TOK_PLUS_ASSIGN) - rez += numptr_val; + rez += right_side_val; else if (op == TOK_SUB || op == TOK_MINUS_ASSIGN) - rez -= numptr_val; + rez -= right_side_val; else if (op == TOK_ASSIGN || op == TOK_COMMA) - rez = numptr_val; - else if (op == TOK_CONDITIONAL_SEP) { - if (numptr_m1 == numstack) { - /* protect $((expr : expr)) without "expr ? " */ - goto err; - } - numptr_m1->contidional_second_val_initialized = op; - numptr_m1->contidional_second_val = numptr_val; - } else if (op == TOK_CONDITIONAL) { - rez = rez ? - numptr_val : numptr_m1->contidional_second_val; - } else if (op == TOK_EXPONENT) { + rez = right_side_val; + else if (op == TOK_EXPONENT) { arith_t c; - if (numptr_val < 0) + if (right_side_val < 0) return "exponent less than 0"; c = 1; - while (--numptr_val >= 0) + while (--right_side_val >= 0) c *= rez; rez = c; - } else if (numptr_val == 0) + } + else if (right_side_val == 0) return "divide by zero"; else if (op == TOK_DIV || op == TOK_DIV_ASSIGN) - rez /= numptr_val; + rez /= right_side_val; else if (op == TOK_REM || op == TOK_REM_ASSIGN) - rez %= numptr_val; + rez %= right_side_val; } - if (tok_have_assign(op)) { + + if (is_assign_op(op)) { char buf[sizeof(arith_t)*3 + 2]; - if (numptr_m1->var == NULL) { + if (top_of_stack->var == NULL) { /* Hmm, 1=2 ? */ +//TODO: actually, bash allows ++7 but for some reason it evals to 7, not 8 goto err; } - /* save to shell variable */ - sprintf(buf, arith_t_fmt, rez); - setvar(numptr_m1->var, buf); - /* after saving, make previous value for v++ or v-- */ + /* Save to shell variable */ + sprintf(buf, ARITH_FMT, rez); + setvar(top_of_stack->var, buf); + /* After saving, make previous value for v++ or v-- */ if (op == TOK_POST_INC) rez--; else if (op == TOK_POST_DEC) rez++; } - numptr_m1->val = rez; - /* erase var name, it is just a number now */ - numptr_m1->var = NULL; + + top_of_stack->val = rez; + /* Erase var name, it is just a number now */ + top_of_stack->var = NULL; return NULL; err: return "arithmetic syntax error"; @@ -499,16 +514,17 @@ evaluate_string(arith_state_t *math_state, const char *expr) const char *start_expr = expr = skip_whitespace(expr); unsigned expr_len = strlen(expr) + 2; /* Stack of integers */ - /* The proof that there can be no more than strlen(startbuf)/2+1 integers - * in any given correct or incorrect expression is left as an exercise to - * the reader. */ - v_n_t *const numstack = alloca((expr_len / 2) * sizeof(numstack[0])); - v_n_t *numstackptr = numstack; + /* The proof that there can be no more than strlen(startbuf)/2+1 + * integers in any given correct or incorrect expression + * is left as an exercise to the reader. */ + var_or_num_t *const numstack = alloca((expr_len / 2) * sizeof(numstack[0])); + var_or_num_t *numstackptr = numstack; /* Stack of operator tokens */ operator *const stack = alloca(expr_len * sizeof(stack[0])); operator *stackptr = stack; - *stackptr++ = lasttok = TOK_LPAREN; /* start off with a left paren */ + /* Start with a left paren */ + *stackptr++ = lasttok = TOK_LPAREN; errmsg = NULL; while (1) { @@ -521,7 +537,7 @@ evaluate_string(arith_state_t *math_state, const char *expr) arithval = *expr; if (arithval == '\0') { if (expr == start_expr) { - /* Null expression. */ + /* Null expression */ numstack->val = 0; goto ret; } @@ -558,7 +574,7 @@ evaluate_string(arith_state_t *math_state, const char *expr) safe_strncpy(numstackptr->var, expr, var_name_size); expr = p; num: - numstackptr->contidional_second_val_initialized = 0; + numstackptr->second_val_present = 0; numstackptr++; lasttok = TOK_NUM; continue; @@ -577,21 +593,32 @@ evaluate_string(arith_state_t *math_state, const char *expr) /* Should be an operator */ p = op_tokens; while (1) { - const char *e = expr; +// TODO: bash allows 7+++v, treats it as 7 + ++v +// we treat it as 7++ + v and reject /* Compare expr to current op_tokens[] element */ - while (*p && *e == *p) - p++, e++; - if (*p == '\0') { /* match: operator is found */ - expr = e; - break; + const char *e = expr; + while (1) { + if (*p == '\0') { + /* Match: operator is found */ + expr = e; + goto tok_found; + } + if (*p != *e) + break; + p++; + e++; } - /* Go to next element of op_tokens[] */ + /* No match, go to next element of op_tokens[] */ while (*p) p++; p += 2; /* skip NUL and TOK_foo bytes */ - if (*p == '\0') /* no next element, operator not found */ + if (*p == '\0') { + /* No next element, operator not found */ + //math_state->syntax_error_at = expr; goto err; + } } + tok_found: op = p[1]; /* fetch TOK_foo value */ /* NB: expr now points past the operator */ @@ -662,21 +689,21 @@ evaluate_string(arith_state_t *math_state, const char *expr) } errmsg = arith_apply(math_state, prev_op, numstack, &numstackptr); if (errmsg) - goto ret; + goto err_with_custom_msg; } - if (op == TOK_RPAREN) { + if (op == TOK_RPAREN) goto err; - } } - /* Push this operator to the stack and remember it. */ + /* Push this operator to the stack and remember it */ *stackptr++ = lasttok = op; next: ; } /* while (1) */ err: - numstack->val = -1; errmsg = "arithmetic syntax error"; + err_with_custom_msg: + numstack->val = -1; ret: math_state->errmsg = errmsg; return numstack->val; diff --git a/shell/math.h b/shell/math.h index 2dcab130d..2d305eb12 100644 --- a/shell/math.h +++ b/shell/math.h @@ -9,19 +9,13 @@ /* The math library has just one function: * - * arith_t arith(arith_state_t *states, const char *expr); + * arith_t arith(arith_state_t *state, const char *expr); * * The expr argument is the math string to parse. All normal expansions must * be done already. i.e. no dollar symbols should be present. * * The state argument is a pointer to a struct of hooks for your shell (see below), - * and a semi-detailed error code. Currently, those values are (for - * compatibility, you should assume all negative values are errors): - * 0 - no errors (yay!) - * -1 - unspecified problem - * -2 - divide by zero - * -3 - exponent less than 0 - * -5 - expression recursion loop detected + * and an error message string (NULL if no error). * * The function returns the answer to the expression. So if you called it * with the expression: @@ -64,12 +58,6 @@ * the regex (in C locale): ^[a-zA-Z_][a-zA-Z_0-9]* */ -/* To make your life easier when dealing with optional 64bit math support, - * rather than assume that the type is "signed long" and you can always - * use "%ld" to scan/print the value, use the arith_t helper defines. See - * below for the exact things that are available. - */ - #ifndef SHELL_MATH_H #define SHELL_MATH_H 1 @@ -77,11 +65,11 @@ PUSH_AND_SET_FUNCTION_VISIBILITY_TO_HIDDEN #if ENABLE_SH_MATH_SUPPORT_64 typedef long long arith_t; -#define arith_t_fmt "%lld" +#define ARITH_FMT "%lld" #define strto_arith_t strtoull #else typedef long arith_t; -#define arith_t_fmt "%ld" +#define ARITH_FMT "%ld" #define strto_arith_t strtoul #endif -- cgit v1.2.3-55-g6feb From 52e460b7440ed5b85e4125a4eccf1e665d92c0ff Mon Sep 17 00:00:00 2001 From: Denys Vlasenko Date: Thu, 16 Sep 2010 16:12:00 +0200 Subject: hush: move shell_ver from globals to main's stack. function old new delta hush_main 995 1011 +16 pseudo_exec_argv 253 251 -2 execvp_or_die 50 48 -2 maybe_set_to_sigexit 50 47 -3 hush_exit 78 75 -3 builtin_wait 274 271 -3 check_and_run_traps 205 200 -5 init_sigmasks 214 190 -24 builtin_trap 465 441 -24 reset_traps_to_defaults 238 211 -27 ------------------------------------------------------------------------------ (add/remove: 0/0 grow/shrink: 1/9 up/down: 16/-93) Total: -77 bytes Signed-off-by: Denys Vlasenko --- shell/hush.c | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) (limited to 'shell') diff --git a/shell/hush.c b/shell/hush.c index a888332bc..6e36078c2 100644 --- a/shell/hush.c +++ b/shell/hush.c @@ -707,8 +707,7 @@ struct globals { #endif const char *ifs; const char *cwd; - struct variable *top_var; /* = &G.shell_ver (set in main()) */ - struct variable shell_ver; + struct variable *top_var; char **expanded_assignments; #if ENABLE_HUSH_FUNCTIONS struct function *top_func; @@ -7337,6 +7336,7 @@ int hush_main(int argc, char **argv) unsigned builtin_argc; char **e; struct variable *cur_var; + struct variable shell_ver; INIT_G(); if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */ @@ -7345,12 +7345,13 @@ int hush_main(int argc, char **argv) G.argv0_for_re_execing = argv[0]; #endif /* Deal with HUSH_VERSION */ - G.shell_ver.flg_export = 1; - G.shell_ver.flg_read_only = 1; + memset(&shell_ver, 0, sizeof(shell_ver)); + shell_ver.flg_export = 1; + shell_ver.flg_read_only = 1; /* Code which handles ${var...} needs writable values for all variables, * therefore we xstrdup: */ - G.shell_ver.varstr = xstrdup(hush_version_str), - G.top_var = &G.shell_ver; + shell_ver.varstr = xstrdup(hush_version_str), + G.top_var = &shell_ver; /* Create shell local variables from the values * currently living in the environment */ debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION"); @@ -7369,8 +7370,8 @@ int hush_main(int argc, char **argv) e++; } /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */ - debug_printf_env("putenv '%s'\n", G.shell_ver.varstr); - putenv(G.shell_ver.varstr); + debug_printf_env("putenv '%s'\n", shell_ver.varstr); + putenv(shell_ver.varstr); /* Export PWD */ set_pwd_var(/*exp:*/ 1); -- cgit v1.2.3-55-g6feb From 395b97aeac4ac25dca32bd8480441ce64c17f7d9 Mon Sep 17 00:00:00 2001 From: Denys Vlasenko Date: Fri, 17 Sep 2010 18:02:17 +0200 Subject: shell/math: better comment. no code changes Signed-off-by: Denys Vlasenko --- shell/math.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'shell') diff --git a/shell/math.c b/shell/math.c index 9d3b912a7..760645d0f 100644 --- a/shell/math.c +++ b/shell/math.c @@ -652,10 +652,10 @@ evaluate_string(arith_state_t *math_state, const char *expr) * integer stack. * But for binary operators, "apply" everything on the operator * stack until we find an operator with a lesser priority than the - * one we have just extracted. + * one we have just extracted. If op is right-associative, + * then stop "applying" on the equal priority too. * Left paren is given the lowest priority so it will never be * "applied" in this way. - * if associativity is right and priority eq, applied also skip */ prec = PREC(op); if ((prec > 0 && prec < UNARYPREC) || prec == SPEC_PREC) { -- cgit v1.2.3-55-g6feb From 0e13b4019c3d05933ba8d37357023bfcd82e8106 Mon Sep 17 00:00:00 2001 From: Denys Vlasenko Date: Tue, 21 Sep 2010 12:35:39 +0200 Subject: hush: use smaller EXP_FLAG_foo constants function old new delta expand_string_to_string 126 124 -2 parse_stream 2376 2370 -6 ------------------------------------------------------------------------------ (add/remove: 0/0 grow/shrink: 0/2 up/down: 0/-8) Total: -8 bytes Signed-off-by: Denys Vlasenko --- shell/hush.c | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) (limited to 'shell') diff --git a/shell/hush.c b/shell/hush.c index 6e36078c2..4c597e1ed 100644 --- a/shell/hush.c +++ b/shell/hush.c @@ -391,18 +391,10 @@ enum { RES_SNTX }; -enum { - EXP_FLAG_GLOB = 0x200, - EXP_FLAG_ESC_GLOB_CHARS = 0x100, - EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */ -}; - typedef struct o_string { char *data; int length; /* position where data is appended */ int maxlen; - /* Protect newly added chars against globbing - * (by prepending \ to *, ?, [, \) */ int o_expflags; /* At least some part of the string was inside '' or "", * possibly empty one: word"", wo''rd etc. */ @@ -411,10 +403,18 @@ typedef struct o_string { smallint o_assignment; /* 0:maybe, 1:yes, 2:no */ } o_string; enum { - MAYBE_ASSIGNMENT = 0, + EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */ + EXP_FLAG_GLOB = 0x2, + /* Protect newly added chars against globbing + * by prepending \ to *, ?, [, \ */ + EXP_FLAG_ESC_GLOB_CHARS = 0x1, +}; +enum { + MAYBE_ASSIGNMENT = 0, DEFINITELY_ASSIGNMENT = 1, - NOT_ASSIGNMENT = 2, - WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */ + NOT_ASSIGNMENT = 2, + /* Not an assigment, but next word may be: "if v=xyz cmd;" */ + WORD_IS_KEYWORD = 3, }; /* Used for initialization: o_string foo = NULL_O_STRING; */ #define NULL_O_STRING { NULL } -- cgit v1.2.3-55-g6feb From b563f62bbb1c9a6d931924f8fd7c3e52bb3d5875 Mon Sep 17 00:00:00 2001 From: Denys Vlasenko Date: Sat, 25 Sep 2010 17:15:13 +0200 Subject: ash: fix signal and "set -e" interaction Signed-off-by: Denys Vlasenko --- shell/ash.c | 19 +++++++++++++------ shell/ash_test/ash-signals/signal8.right | 3 +++ shell/ash_test/ash-signals/signal8.tests | 18 ++++++++++++++++++ shell/ash_test/ash-signals/signal9.right | 3 +++ shell/ash_test/ash-signals/signal9.tests | 21 +++++++++++++++++++++ 5 files changed, 58 insertions(+), 6 deletions(-) create mode 100644 shell/ash_test/ash-signals/signal8.right create mode 100755 shell/ash_test/ash-signals/signal8.tests create mode 100644 shell/ash_test/ash-signals/signal9.right create mode 100755 shell/ash_test/ash-signals/signal9.tests (limited to 'shell') diff --git a/shell/ash.c b/shell/ash.c index 9089adc63..ea835527e 100644 --- a/shell/ash.c +++ b/shell/ash.c @@ -8214,7 +8214,7 @@ static int evalstring(char *s, int mask); /* Called to execute a trap. * Single callsite - at the end of evaltree(). - * If we return non-zero, exaltree raises EXEXIT exception. + * If we return non-zero, evaltree raises EXEXIT exception. * * Perhaps we should avoid entering new trap handlers * while we are executing a trap handler. [is it a TODO?] @@ -8404,11 +8404,15 @@ evaltree(union node *n, int flags) out: exception_handler = savehandler; + out1: + /* Order of checks below is important: + * signal handlers trigger before exit caused by "set -e". + */ + if (pending_sig && dotrap()) + goto exexit; if (checkexit & exitstatus) evalskip |= SKIPEVAL; - else if (pending_sig && dotrap()) - goto exexit; if (flags & EV_EXIT) { exexit: @@ -8740,7 +8744,7 @@ poplocalvars(void) while ((lvp = localvars) != NULL) { localvars = lvp->next; vp = lvp->vp; - TRACE(("poplocalvar %s\n", vp ? vp->text : "-")); + TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-")); if (vp == NULL) { /* $- saved */ memcpy(optlist, lvp->text, sizeof(optlist)); free((char*)lvp->text); @@ -13009,10 +13013,12 @@ int ash_main(int argc UNUSED_PARAM, char **argv) if (e == EXERROR) exitstatus = 2; s = state; - if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) + if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) { exitshell(); - if (e == EXINT) + } + if (e == EXINT) { outcslow('\n', stderr); + } popstackmark(&smark); FORCE_INT_ON; /* enable interrupts */ @@ -13105,6 +13111,7 @@ int ash_main(int argc UNUSED_PARAM, char **argv) _mcleanup(); } #endif + TRACE(("End of main reached\n")); exitshell(); /* NOTREACHED */ } diff --git a/shell/ash_test/ash-signals/signal8.right b/shell/ash_test/ash-signals/signal8.right new file mode 100644 index 000000000..39572f30e --- /dev/null +++ b/shell/ash_test/ash-signals/signal8.right @@ -0,0 +1,3 @@ +Removing traps +End of exit_func +Done: 0 diff --git a/shell/ash_test/ash-signals/signal8.tests b/shell/ash_test/ash-signals/signal8.tests new file mode 100755 index 000000000..731af7477 --- /dev/null +++ b/shell/ash_test/ash-signals/signal8.tests @@ -0,0 +1,18 @@ +"$THIS_SH" -c ' +exit_func() { + echo "Removing traps" + trap - EXIT TERM INT + echo "End of exit_func" +} +set -e +trap exit_func EXIT TERM INT +sleep 2 +exit 77 +' & + +sleep 1 +# BUG: ash kills -PGRP, but in non-interactive shell we do not create pgrps! +# In this case, bash kills by PID, not PGRP. +kill -TERM %1 +wait +echo Done: $? diff --git a/shell/ash_test/ash-signals/signal9.right b/shell/ash_test/ash-signals/signal9.right new file mode 100644 index 000000000..39572f30e --- /dev/null +++ b/shell/ash_test/ash-signals/signal9.right @@ -0,0 +1,3 @@ +Removing traps +End of exit_func +Done: 0 diff --git a/shell/ash_test/ash-signals/signal9.tests b/shell/ash_test/ash-signals/signal9.tests new file mode 100755 index 000000000..18e71012b --- /dev/null +++ b/shell/ash_test/ash-signals/signal9.tests @@ -0,0 +1,21 @@ +# Note: the inner script is a test which checks for a different bug +# (ordering between INT handler and exit on "set -e"), +# but so far I did not figure out how to simulate it non-interactively. + +"$THIS_SH" -c ' +exit_func() { + echo "Removing traps" + trap - EXIT TERM INT + echo "End of exit_func" +} +set -e +trap exit_func EXIT TERM INT +sleep 2 +exit 77 +' & + +child=$! +sleep 1 +kill -TERM $child +wait +echo Done: $? -- cgit v1.2.3-55-g6feb From 238081f750f442c1dd851ba70243bd0819f3ca04 Mon Sep 17 00:00:00 2001 From: Denys Vlasenko Date: Sun, 3 Oct 2010 14:26:26 +0200 Subject: hush: preparatory patch, no code changes Signed-off-by: Denys Vlasenko --- shell/hush.c | 51 ++++++++++++++++++++++++++------------------------- 1 file changed, 26 insertions(+), 25 deletions(-) (limited to 'shell') diff --git a/shell/hush.c b/shell/hush.c index 4c597e1ed..3b9362e10 100644 --- a/shell/hush.c +++ b/shell/hush.c @@ -2000,26 +2000,9 @@ static void o_addstr_with_NUL(o_string *o, const char *str) o_addblock(o, str, strlen(str) + 1); } -static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len) -{ - while (len) { - len--; - o_addchr(o, *str); - if (*str++ == '\\') { - /* \z -> \\\z; \ -> \\ */ - o_addchr(o, '\\'); - if (len) { - len--; - o_addchr(o, '\\'); - o_addchr(o, *str++); - } - } - } -} - -#undef HUSH_BRACE_EXP +#undef HUSH_BRACE_EXPANSION /* - * HUSH_BRACE_EXP code needs corresponding quoting on variable expansion side. + * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side. * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v. * Apparently, on unquoted $v bash still does globbing * ("v='*.txt'; echo $v" prints all .txt files), @@ -2029,7 +2012,7 @@ static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len * We have only second one. */ -#ifdef HUSH_BRACE_EXP +#ifdef HUSH_BRACE_EXPANSION # define MAYBE_BRACES "{}" #else # define MAYBE_BRACES "" @@ -2197,7 +2180,7 @@ static int o_get_last_ptr(o_string *o, int n) return ((int)(uintptr_t)list[n-1]) + string_start; } -#ifdef HUSH_BRACE_EXP +#ifdef HUSH_BRACE_EXPANSION /* There in a GNU extension, GLOB_BRACE, but it is not usable: * first, it processes even {a} (no commas), second, * I didn't manage to make it return strings when they don't match @@ -2393,7 +2376,7 @@ static int perform_glob(o_string *o, int n) return n; } -#else /* !HUSH_BRACE_EXP */ +#else /* !HUSH_BRACE_EXPANSION */ /* Helper */ static int glob_needed(const char *s) @@ -2470,7 +2453,7 @@ static int perform_glob(o_string *o, int n) return n; } -#endif /* !HUSH_BRACE_EXP */ +#endif /* !HUSH_BRACE_EXPANSION */ /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered. * Otherwise, just finish current list[] and start new */ @@ -4387,6 +4370,24 @@ static int process_command_subs(o_string *dest, const char *s); * followed by strings themselves. * Caller can deallocate entire list by single free(list). */ +/* A horde of its helpers come first: */ + +static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len) +{ + while (--len >= 0) { + o_addchr(o, *str); + if (*str++ == '\\') { + /* \z -> \\\z; \ -> \\ */ + o_addchr(o, '\\'); + if (len) { + len--; + o_addchr(o, '\\'); + o_addchr(o, *str++); + } + } + } +} + /* Store given string, finalizing the word and starting new one whenever * we encounter IFS char(s). This is used for expanding variable values. * End-of-string does NOT finalize word: think about 'echo -$VAR-' */ @@ -4395,9 +4396,9 @@ static int expand_on_ifs(o_string *output, int n, const char *str) while (1) { int word_len = strcspn(str, G.ifs); if (word_len) { - if (!(output->o_expflags & EXP_FLAG_GLOB)) + if (!(output->o_expflags & EXP_FLAG_GLOB)) { o_addblock(output, str, word_len); - else { + } else { /* Protect backslashes against globbing up :) * Example: "v='\*'; echo b$v" prints "b\*" * (and does not try to glob on "*") -- cgit v1.2.3-55-g6feb From 9e800223f13edeb02412936c810e7ee79f35c27c Mon Sep 17 00:00:00 2001 From: Denys Vlasenko Date: Sun, 3 Oct 2010 14:28:04 +0200 Subject: hush: implement brace expansion When enabled: function old new delta glob_brace - 402 +402 next_brace_sub - 70 +70 expand_on_ifs 185 231 +46 bbconfig_config_bz2 4923 4929 +6 o_save_ptr 282 140 -142 ------------------------------------------------------------------------------ (add/remove: 2/0 grow/shrink: 2/1 up/down: 524/-142) Total: 382 bytes Signed-off-by: Denys Vlasenko --- shell/hush.c | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) (limited to 'shell') diff --git a/shell/hush.c b/shell/hush.c index 3b9362e10..5b73f0c53 100644 --- a/shell/hush.c +++ b/shell/hush.c @@ -129,6 +129,13 @@ //config: help //config: Enable bash-compatible extensions. //config: +//config:config HUSH_BRACE_EXPANSION +//config: bool "Brace expansion" +//config: default y +//config: depends on HUSH_BASH_COMPAT +//config: help +//config: Enable {abc,def} extension. +//config: //config:config HUSH_HELP //config: bool "help builtin" //config: default y @@ -2000,7 +2007,6 @@ static void o_addstr_with_NUL(o_string *o, const char *str) o_addblock(o, str, strlen(str) + 1); } -#undef HUSH_BRACE_EXPANSION /* * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side. * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v. @@ -2012,7 +2018,7 @@ static void o_addstr_with_NUL(o_string *o, const char *str) * We have only second one. */ -#ifdef HUSH_BRACE_EXPANSION +#if ENABLE_HUSH_BRACE_EXPANSION # define MAYBE_BRACES "{}" #else # define MAYBE_BRACES "" @@ -2180,7 +2186,7 @@ static int o_get_last_ptr(o_string *o, int n) return ((int)(uintptr_t)list[n-1]) + string_start; } -#ifdef HUSH_BRACE_EXPANSION +#if ENABLE_HUSH_BRACE_EXPANSION /* There in a GNU extension, GLOB_BRACE, but it is not usable: * first, it processes even {a} (no commas), second, * I didn't manage to make it return strings when they don't match @@ -4375,8 +4381,17 @@ static int process_command_subs(o_string *dest, const char *s); static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len) { while (--len >= 0) { - o_addchr(o, *str); - if (*str++ == '\\') { + char c = *str++; +#if ENABLE_HUSH_BRACE_EXPANSION + if (c == '{' || c == '}') { + /* { -> \{, } -> \} */ + o_addchr(o, '\\'); + o_addchr(o, c); + continue; + } +#endif + o_addchr(o, c); + if (c == '\\') { /* \z -> \\\z; \ -> \\ */ o_addchr(o, '\\'); if (len) { -- cgit v1.2.3-55-g6feb From 2bcba5cc53a171fba2d9d0b5185f45d8026a2657 Mon Sep 17 00:00:00 2001 From: Denys Vlasenko Date: Sun, 3 Oct 2010 17:07:57 +0200 Subject: hush: add brace expansion testcase Signed-off-by: Denys Vlasenko --- shell/hush_test/hush-glob/bash_brace1.right | 4 ++++ shell/hush_test/hush-glob/bash_brace1.tests | 10 ++++++++++ 2 files changed, 14 insertions(+) create mode 100644 shell/hush_test/hush-glob/bash_brace1.right create mode 100755 shell/hush_test/hush-glob/bash_brace1.tests (limited to 'shell') diff --git a/shell/hush_test/hush-glob/bash_brace1.right b/shell/hush_test/hush-glob/bash_brace1.right new file mode 100644 index 000000000..63365c9e4 --- /dev/null +++ b/shell/hush_test/hush-glob/bash_brace1.right @@ -0,0 +1,4 @@ +bash_brace1.tests +*{b,b}race1.t* +bash_brace1.tests bash_brace1.tests +Done: 0 diff --git a/shell/hush_test/hush-glob/bash_brace1.tests b/shell/hush_test/hush-glob/bash_brace1.tests new file mode 100755 index 000000000..eb2f0e974 --- /dev/null +++ b/shell/hush_test/hush-glob/bash_brace1.tests @@ -0,0 +1,10 @@ +# unquoted $v should be globbed: +v='*brace1.t*'; echo $v + +# ...but not brace expanded: +v='*{b,b}race1.t*'; echo $v + +# whereas direct brces are expanded: +echo *{b,b}race1.t* + +echo Done: $? -- cgit v1.2.3-55-g6feb From 957f79f4714fbb0ee7d653d98609054f2a8d7545 Mon Sep 17 00:00:00 2001 From: Denys Vlasenko Date: Sun, 3 Oct 2010 17:15:50 +0200 Subject: hush: small code shrink function old new delta expand_on_ifs 231 222 -9 Signed-off-by: Denys Vlasenko --- shell/hush.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) (limited to 'shell') diff --git a/shell/hush.c b/shell/hush.c index 5b73f0c53..67a6d87f5 100644 --- a/shell/hush.c +++ b/shell/hush.c @@ -4382,12 +4382,16 @@ static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len { while (--len >= 0) { char c = *str++; + #if ENABLE_HUSH_BRACE_EXPANSION if (c == '{' || c == '}') { /* { -> \{, } -> \} */ o_addchr(o, '\\'); - o_addchr(o, c); - continue; + /* And now we want to add { or } and continue: + * o_addchr(o, c); + * continue; + * luckily, just falling throught achieves this. + */ } #endif o_addchr(o, c); -- cgit v1.2.3-55-g6feb From bbecd74d5a9413412b59dafc2f200a181f960b20 Mon Sep 17 00:00:00 2001 From: Denys Vlasenko Date: Sun, 3 Oct 2010 17:22:52 +0200 Subject: hush: remove brace expansion from TODO list in comments. No code changes. Signed-off-by: Denys Vlasenko --- shell/hush.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) (limited to 'shell') diff --git a/shell/hush.c b/shell/hush.c index 67a6d87f5..1f907e1ba 100644 --- a/shell/hush.c +++ b/shell/hush.c @@ -8,6 +8,8 @@ * Copyright (C) 2000,2001 Larry Doolittle * Copyright (C) 2008,2009 Denys Vlasenko * + * Licensed under GPLv2 or later, see file LICENSE in this source tree. + * * Credits: * The parser routines proper are all original material, first * written Dec 2000 and Jan 2001 by Larry Doolittle. The @@ -50,7 +52,6 @@ * * Bash compat TODO: * redirection of stdout+stderr: &> and >& - * brace expansion: one/{two,three,four} * reserved words: function select * advanced test: [[ ]] * process substitution: <(list) and >(list) @@ -63,7 +64,9 @@ * The EXPR is evaluated according to ARITHMETIC EVALUATION. * This is exactly equivalent to let "EXPR". * $[EXPR]: synonym for $((EXPR)) - * export builtin should be special, its arguments are assignments + * + * Won't do: + * In bash, export builtin is special, its arguments are assignments * and therefore expansion of them should be "one-word" expansion: * $ export i=`echo 'a b'` # export has one arg: "i=a b" * compare with: @@ -77,8 +80,6 @@ * aaa bbb * $ "export" i=`echo 'aaa bbb'`; echo "$i" * aaa - * - * Licensed under GPLv2 or later, see file LICENSE in this source tree. */ #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */ #include /* for malloc_trim */ -- cgit v1.2.3-55-g6feb From e2069fb325f598c81a37222c8e44436439757029 Mon Sep 17 00:00:00 2001 From: Denys Vlasenko Date: Mon, 4 Oct 2010 00:01:47 +0200 Subject: hush: remove "doesn't support brace expansion" from config help text Signed-off-by: Denys Vlasenko --- shell/hush.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'shell') diff --git a/shell/hush.c b/shell/hush.c index 1f907e1ba..75083dc2e 100644 --- a/shell/hush.c +++ b/shell/hush.c @@ -120,8 +120,8 @@ //config: //config: It will compile and work on no-mmu systems. //config: -//config: It does not handle select, aliases, brace expansion, -//config: tilde expansion, &>file and >&file redirection of stdout+stderr. +//config: It does not handle select, aliases, tilde expansion, +//config: &>file and >&file redirection of stdout+stderr. //config: //config:config HUSH_BASH_COMPAT //config: bool "bash-compatible extensions" -- cgit v1.2.3-55-g6feb From cacb2cd281392135871364c3beb1f8143396ccc0 Mon Sep 17 00:00:00 2001 From: Denys Vlasenko Date: Tue, 5 Oct 2010 00:13:02 +0200 Subject: *: whitespace fixes Signed-off-by: Denys Vlasenko --- editors/patch.c | 2 +- editors/patch_toybox.c | 2 +- shell/ash.c | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) (limited to 'shell') diff --git a/editors/patch.c b/editors/patch.c index 0bde2cab3..764f0f183 100644 --- a/editors/patch.c +++ b/editors/patch.c @@ -554,7 +554,7 @@ int patch_main(int argc UNUSED_PARAM, char **argv) int oldsum, newsum, del = 0; char *name; - oldsum = TT.oldline + TT.oldlen; + oldsum = TT.oldline + TT.oldlen; newsum = TT.newline + TT.newlen; name = reverse ? oldname : newname; diff --git a/editors/patch_toybox.c b/editors/patch_toybox.c index 7f3234e66..04bd98eea 100644 --- a/editors/patch_toybox.c +++ b/editors/patch_toybox.c @@ -522,7 +522,7 @@ int patch_main(int argc UNUSED_PARAM, char **argv) int oldsum, newsum, del = 0; char *s, *name; - oldsum = TT.oldline + TT.oldlen; + oldsum = TT.oldline + TT.oldlen; newsum = TT.newline + TT.newlen; name = reverse ? oldname : newname; diff --git a/shell/ash.c b/shell/ash.c index ea835527e..fbf3efce2 100644 --- a/shell/ash.c +++ b/shell/ash.c @@ -12840,7 +12840,7 @@ init(void) /* bash re-enables SIGHUP which is SIG_IGNed on entry. * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$" */ - signal(SIGHUP, SIG_DFL); + signal(SIGHUP, SIG_DFL); /* from var.c: */ { -- cgit v1.2.3-55-g6feb