1 /* vi: set sw=4 ts=4: */
3 * Mini expr implementation for busybox
5 * based on GNU expr Mike Parker.
6 * Copyright (C) 86, 1991-1997, 1999 Free Software Foundation, Inc.
8 * Busybox modifications
9 * Copyright (c) 2000 Edward Betts <edward@debian.org>.
10 * Copyright (C) 2003-2005 Vladimir Oleynik <dzo@simtreas.ru>
11 * - reduced 464 bytes.
14 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
16 /* This program evaluates expressions. Each token (operator, operand,
17 * parenthesis) of the expression must be a separate argument. The
18 * parser used is a reasonably general one, though any incarnation of
19 * it is language-specific. It is especially nice for expressions.
21 * No parse tree is needed; a new node is evaluated immediately.
22 * One function can handle multiple operators all of equal precedence,
23 * provided they all associate ((x op x) op x).
26 //config: bool "expr (6.1 kb)"
29 //config: expr is used to calculate numbers and print the result
30 //config: to standard output.
32 //config:config EXPR_MATH_SUPPORT_64
33 //config: bool "Extend Posix numbers support to 64 bit"
35 //config: depends on EXPR
37 //config: Enable 64-bit math support in the expr applet. This will make
38 //config: the applet slightly larger, but will allow computation with very
39 //config: large numbers.
41 //applet:IF_EXPR(APPLET(expr, BB_DIR_USR_BIN, BB_SUID_DROP))
43 //kbuild:lib-$(CONFIG_EXPR) += expr.o
45 //usage:#define expr_trivial_usage
47 //usage:#define expr_full_usage "\n\n"
48 //usage: "Print the value of EXPRESSION to stdout\n"
50 //usage: "EXPRESSION may be:\n"
51 //usage: " ARG1 | ARG2 ARG1 if it is neither null nor 0, otherwise ARG2\n"
52 //usage: " ARG1 & ARG2 ARG1 if neither argument is null or 0, otherwise 0\n"
53 //usage: " ARG1 < ARG2 1 if ARG1 is less than ARG2, else 0. Similarly:\n"
54 //usage: " ARG1 <= ARG2\n"
55 //usage: " ARG1 = ARG2\n"
56 //usage: " ARG1 != ARG2\n"
57 //usage: " ARG1 >= ARG2\n"
58 //usage: " ARG1 > ARG2\n"
59 //usage: " ARG1 + ARG2 Sum of ARG1 and ARG2. Similarly:\n"
60 //usage: " ARG1 - ARG2\n"
61 //usage: " ARG1 * ARG2\n"
62 //usage: " ARG1 / ARG2\n"
63 //usage: " ARG1 % ARG2\n"
64 //usage: " STRING : REGEXP Anchored pattern match of REGEXP in STRING\n"
65 //usage: " match STRING REGEXP Same as STRING : REGEXP\n"
66 //usage: " substr STRING POS LENGTH Substring of STRING, POS counted from 1\n"
67 //usage: " index STRING CHARS Index in STRING where any CHARS is found, or 0\n"
68 //usage: " length STRING Length of STRING\n"
69 //usage: " quote TOKEN Interpret TOKEN as a string, even if\n"
70 //usage: " it is a keyword like 'match' or an\n"
71 //usage: " operator like '/'\n"
72 //usage: " (EXPRESSION) Value of EXPRESSION\n"
74 //usage: "Beware that many operators need to be escaped or quoted for shells.\n"
75 //usage: "Comparisons are arithmetic if both ARGs are numbers, else\n"
76 //usage: "lexicographical. Pattern matches return the string matched between\n"
77 //usage: "\\( and \\) or null; if \\( and \\) are not used, they return the number\n"
78 //usage: "of characters matched or 0."
81 #include "common_bufsiz.h"
84 #if ENABLE_EXPR_MATH_SUPPORT_64
85 typedef int64_t arith_t;
88 #define PF_REZ_TYPE (long long)
89 #define STRTOL(s, e, b) strtoll(s, e, b)
94 #define PF_REZ_TYPE (long)
95 #define STRTOL(s, e, b) strtol(s, e, b)
98 /* TODO: use bb_strtol[l]? It's easier to check for errors... */
100 /* The kinds of value we can have. */
108 smallint type; /* Which kind. */
109 union { /* The value itself. */
114 typedef struct valinfo VALUE;
116 /* The arguments given to the program, minus the program name. */
120 #define G (*(struct globals*)bb_common_bufsiz1)
121 #define INIT_G() do { setup_common_bufsiz(); } while (0)
123 /* forward declarations */
124 static VALUE *eval(void);
127 /* Return a VALUE for I. */
129 static VALUE *int_value(arith_t i)
133 v = xzalloc(sizeof(VALUE));
134 if (INTEGER) /* otherwise xzalloc did it already */
140 /* Return a VALUE for S. */
142 static VALUE *str_value(const char *s)
146 v = xzalloc(sizeof(VALUE));
147 if (STRING) /* otherwise xzalloc did it already */
153 /* Free VALUE V, including structure components. */
155 static void freev(VALUE *v)
157 if (v->type == STRING)
162 /* Return nonzero if V is a null-string or zero-number. */
164 static int null(VALUE *v)
166 if (v->type == INTEGER)
169 return v->u.s[0] == '\0' || LONE_CHAR(v->u.s, '0');
172 /* Coerce V to a STRING value (can't fail). */
174 static void tostring(VALUE *v)
176 if (v->type == INTEGER) {
177 v->u.s = xasprintf("%" PF_REZ "d", PF_REZ_TYPE v->u.i);
182 /* Coerce V to an INTEGER value. Return 1 on success, 0 on failure. */
184 static bool toarith(VALUE *v)
186 if (v->type == STRING) {
190 /* Don't interpret the empty string as an integer. */
191 /* Currently does not worry about overflow or int/long differences. */
192 i = STRTOL(v->u.s, &e, 10);
193 if ((v->u.s == e) || *e)
202 /* Return str[0]+str[1] if the next token matches STR exactly.
203 STR must not be NULL. */
205 static int nextarg(const char *str)
207 if (*G.args == NULL || strcmp(*G.args, str) != 0)
209 return (unsigned char)str[0] + (unsigned char)str[1];
212 /* The comparison operator handling functions. */
214 static int cmp_common(VALUE *l, VALUE *r, int op)
220 if (l->type == STRING || r->type == STRING) {
223 ll = strcmp(l->u.s, r->u.s);
226 /* calculating ll - rr and checking the result is prone to overflows.
227 * We'll do it differently: */
230 if (op == ('<' + '='))
232 if (op == '=' || (op == '=' + '='))
242 /* The arithmetic operator handling functions. */
244 static arith_t arithmetic_common(VALUE *l, VALUE *r, int op)
248 if (!toarith(l) || !toarith(r))
249 bb_error_msg_and_die("non-numeric argument");
259 bb_error_msg_and_die("division by zero");
265 /* Do the : operator.
266 SV is the VALUE for the lhs (the string),
267 PV is the VALUE for the rhs (the pattern). */
269 static VALUE *docolon(VALUE *sv, VALUE *pv)
274 regmatch_t re_regs[NMATCH];
279 if (pv->u.s[0] == '^') {
281 "warning: '%s': using '^' as the first character\n"
282 "of a basic regular expression is not portable; it is ignored", pv->u.s);
285 memset(&re_buffer, 0, sizeof(re_buffer));
286 memset(re_regs, 0, sizeof(re_regs));
287 xregcomp(&re_buffer, pv->u.s, 0);
289 /* expr uses an anchored pattern match, so check that there was a
290 * match and that the match starts at offset 0. */
291 if (regexec(&re_buffer, sv->u.s, NMATCH, re_regs, 0) != REG_NOMATCH
292 && re_regs[0].rm_so == 0
294 /* Were \(...\) used? */
295 if (re_buffer.re_nsub > 0 && re_regs[1].rm_so >= 0) {
296 sv->u.s[re_regs[1].rm_eo] = '\0';
297 v = str_value(sv->u.s + re_regs[1].rm_so);
299 v = int_value(re_regs[0].rm_eo);
302 /* Match failed -- return the right kind of null. */
303 if (re_buffer.re_nsub > 0)
312 /* Handle bare operands and ( expr ) syntax. */
314 static VALUE *eval7(void)
319 bb_error_msg_and_die("syntax error");
325 bb_error_msg_and_die("syntax error");
331 bb_error_msg_and_die("syntax error");
333 return str_value(*G.args++);
336 /* Handle match, substr, index, length, and quote keywords. */
338 static VALUE *eval6(void)
340 static const char keywords[] ALIGN1 =
341 "quote\0""length\0""match\0""index\0""substr\0";
344 VALUE *l = l; /* silence gcc */
345 VALUE *v = v; /* silence gcc */
346 int key = *G.args ? index_in_strings(keywords, *G.args) + 1 : 0;
348 if (key == 0) /* not a keyword */
350 G.args++; /* We have a valid token, so get the next argument. */
351 if (key == 1) { /* quote */
353 bb_error_msg_and_die("syntax error");
354 return str_value(*G.args++);
356 if (key == 2) { /* length */
359 v = int_value(strlen(r->u.s));
364 if (key == 3) { /* match */
370 if (key == 4) { /* index */
374 v = int_value(strcspn(l->u.s, r->u.s) + 1);
375 if (v->u.i == (arith_t) strlen(l->u.s) + 1)
380 if (key == 5) { /* substr */
384 if (!toarith(i1) || !toarith(i2)
385 || i1->u.i > (arith_t) strlen(l->u.s)
386 || i1->u.i <= 0 || i2->u.i <= 0)
389 v = xmalloc(sizeof(VALUE));
391 v->u.s = xstrndup(l->u.s + i1->u.i - 1, i2->u.i);
400 /* Handle : operator (pattern matching).
401 Calls docolon to do the real work. */
403 static VALUE *eval5(void)
408 while (nextarg(":")) {
419 /* Handle *, /, % operators. */
421 static VALUE *eval4(void)
430 if (!op) { op = nextarg("/");
431 if (!op) { op = nextarg("%");
436 val = arithmetic_common(l, r, op);
443 /* Handle +, - operators. */
445 static VALUE *eval3(void)
460 val = arithmetic_common(l, r, op);
467 /* Handle comparisons. */
469 static VALUE *eval2(void)
478 if (!op) { op = nextarg("<=");
479 if (!op) { op = nextarg("=");
480 if (!op) { op = nextarg("==");
481 if (!op) { op = nextarg("!=");
482 if (!op) { op = nextarg(">=");
483 if (!op) { op = nextarg(">");
490 val = cmp_common(l, r, op);
499 static VALUE *eval1(void)
504 while (nextarg("&")) {
507 if (null(l) || null(r)) {
519 static VALUE *eval(void)
524 while (nextarg("|")) {
536 int expr_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
537 int expr_main(int argc UNUSED_PARAM, char **argv)
543 xfunc_error_retval = 2; /* coreutils compat */
545 if (*G.args == NULL) {
546 bb_error_msg_and_die("too few arguments");
550 bb_error_msg_and_die("syntax error");
551 if (v->type == INTEGER)
552 printf("%" PF_REZ "d\n", PF_REZ_TYPE v->u.i);
555 fflush_stdout_and_exit(null(v));