expr.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Mini expr implementation for busybox
  4. *
  5. * based on GNU expr Mike Parker.
  6. * Copyright (C) 86, 1991-1997, 1999 Free Software Foundation, Inc.
  7. *
  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.
  12. * - 64 math support
  13. *
  14. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  15. */
  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.
  20. *
  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).
  24. */
  25. //config:config EXPR
  26. //config: bool "expr"
  27. //config: default y
  28. //config: help
  29. //config: expr is used to calculate numbers and print the result
  30. //config: to standard output.
  31. //config:
  32. //config:config EXPR_MATH_SUPPORT_64
  33. //config: bool "Extend Posix numbers support to 64 bit"
  34. //config: default y
  35. //config: depends on EXPR
  36. //config: help
  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.
  40. //applet:IF_EXPR(APPLET(expr, BB_DIR_USR_BIN, BB_SUID_DROP))
  41. //kbuild:lib-$(CONFIG_EXPR) += expr.o
  42. //usage:#define expr_trivial_usage
  43. //usage: "EXPRESSION"
  44. //usage:#define expr_full_usage "\n\n"
  45. //usage: "Print the value of EXPRESSION to stdout\n"
  46. //usage: "\n"
  47. //usage: "EXPRESSION may be:\n"
  48. //usage: " ARG1 | ARG2 ARG1 if it is neither null nor 0, otherwise ARG2\n"
  49. //usage: " ARG1 & ARG2 ARG1 if neither argument is null or 0, otherwise 0\n"
  50. //usage: " ARG1 < ARG2 1 if ARG1 is less than ARG2, else 0. Similarly:\n"
  51. //usage: " ARG1 <= ARG2\n"
  52. //usage: " ARG1 = ARG2\n"
  53. //usage: " ARG1 != ARG2\n"
  54. //usage: " ARG1 >= ARG2\n"
  55. //usage: " ARG1 > ARG2\n"
  56. //usage: " ARG1 + ARG2 Sum of ARG1 and ARG2. Similarly:\n"
  57. //usage: " ARG1 - ARG2\n"
  58. //usage: " ARG1 * ARG2\n"
  59. //usage: " ARG1 / ARG2\n"
  60. //usage: " ARG1 % ARG2\n"
  61. //usage: " STRING : REGEXP Anchored pattern match of REGEXP in STRING\n"
  62. //usage: " match STRING REGEXP Same as STRING : REGEXP\n"
  63. //usage: " substr STRING POS LENGTH Substring of STRING, POS counted from 1\n"
  64. //usage: " index STRING CHARS Index in STRING where any CHARS is found, or 0\n"
  65. //usage: " length STRING Length of STRING\n"
  66. //usage: " quote TOKEN Interpret TOKEN as a string, even if\n"
  67. //usage: " it is a keyword like 'match' or an\n"
  68. //usage: " operator like '/'\n"
  69. //usage: " (EXPRESSION) Value of EXPRESSION\n"
  70. //usage: "\n"
  71. //usage: "Beware that many operators need to be escaped or quoted for shells.\n"
  72. //usage: "Comparisons are arithmetic if both ARGs are numbers, else\n"
  73. //usage: "lexicographical. Pattern matches return the string matched between\n"
  74. //usage: "\\( and \\) or null; if \\( and \\) are not used, they return the number\n"
  75. //usage: "of characters matched or 0."
  76. #include "libbb.h"
  77. #include "common_bufsiz.h"
  78. #include "xregex.h"
  79. #if ENABLE_EXPR_MATH_SUPPORT_64
  80. typedef int64_t arith_t;
  81. #define PF_REZ "ll"
  82. #define PF_REZ_TYPE (long long)
  83. #define STRTOL(s, e, b) strtoll(s, e, b)
  84. #else
  85. typedef long arith_t;
  86. #define PF_REZ "l"
  87. #define PF_REZ_TYPE (long)
  88. #define STRTOL(s, e, b) strtol(s, e, b)
  89. #endif
  90. /* TODO: use bb_strtol[l]? It's easier to check for errors... */
  91. /* The kinds of value we can have. */
  92. enum {
  93. INTEGER,
  94. STRING
  95. };
  96. /* A value is.... */
  97. struct valinfo {
  98. smallint type; /* Which kind. */
  99. union { /* The value itself. */
  100. arith_t i;
  101. char *s;
  102. } u;
  103. };
  104. typedef struct valinfo VALUE;
  105. /* The arguments given to the program, minus the program name. */
  106. struct globals {
  107. char **args;
  108. } FIX_ALIASING;
  109. #define G (*(struct globals*)bb_common_bufsiz1)
  110. #define INIT_G() do { setup_common_bufsiz(); } while (0)
  111. /* forward declarations */
  112. static VALUE *eval(void);
  113. /* Return a VALUE for I. */
  114. static VALUE *int_value(arith_t i)
  115. {
  116. VALUE *v;
  117. v = xzalloc(sizeof(VALUE));
  118. if (INTEGER) /* otherwise xzalloc did it already */
  119. v->type = INTEGER;
  120. v->u.i = i;
  121. return v;
  122. }
  123. /* Return a VALUE for S. */
  124. static VALUE *str_value(const char *s)
  125. {
  126. VALUE *v;
  127. v = xzalloc(sizeof(VALUE));
  128. if (STRING) /* otherwise xzalloc did it already */
  129. v->type = STRING;
  130. v->u.s = xstrdup(s);
  131. return v;
  132. }
  133. /* Free VALUE V, including structure components. */
  134. static void freev(VALUE *v)
  135. {
  136. if (v->type == STRING)
  137. free(v->u.s);
  138. free(v);
  139. }
  140. /* Return nonzero if V is a null-string or zero-number. */
  141. static int null(VALUE *v)
  142. {
  143. if (v->type == INTEGER)
  144. return v->u.i == 0;
  145. /* STRING: */
  146. return v->u.s[0] == '\0' || LONE_CHAR(v->u.s, '0');
  147. }
  148. /* Coerce V to a STRING value (can't fail). */
  149. static void tostring(VALUE *v)
  150. {
  151. if (v->type == INTEGER) {
  152. v->u.s = xasprintf("%" PF_REZ "d", PF_REZ_TYPE v->u.i);
  153. v->type = STRING;
  154. }
  155. }
  156. /* Coerce V to an INTEGER value. Return 1 on success, 0 on failure. */
  157. static bool toarith(VALUE *v)
  158. {
  159. if (v->type == STRING) {
  160. arith_t i;
  161. char *e;
  162. /* Don't interpret the empty string as an integer. */
  163. /* Currently does not worry about overflow or int/long differences. */
  164. i = STRTOL(v->u.s, &e, 10);
  165. if ((v->u.s == e) || *e)
  166. return 0;
  167. free(v->u.s);
  168. v->u.i = i;
  169. v->type = INTEGER;
  170. }
  171. return 1;
  172. }
  173. /* Return str[0]+str[1] if the next token matches STR exactly.
  174. STR must not be NULL. */
  175. static int nextarg(const char *str)
  176. {
  177. if (*G.args == NULL || strcmp(*G.args, str) != 0)
  178. return 0;
  179. return (unsigned char)str[0] + (unsigned char)str[1];
  180. }
  181. /* The comparison operator handling functions. */
  182. static int cmp_common(VALUE *l, VALUE *r, int op)
  183. {
  184. arith_t ll, rr;
  185. ll = l->u.i;
  186. rr = r->u.i;
  187. if (l->type == STRING || r->type == STRING) {
  188. tostring(l);
  189. tostring(r);
  190. ll = strcmp(l->u.s, r->u.s);
  191. rr = 0;
  192. }
  193. /* calculating ll - rr and checking the result is prone to overflows.
  194. * We'll do it differently: */
  195. if (op == '<')
  196. return ll < rr;
  197. if (op == ('<' + '='))
  198. return ll <= rr;
  199. if (op == '=' || (op == '=' + '='))
  200. return ll == rr;
  201. if (op == '!' + '=')
  202. return ll != rr;
  203. if (op == '>')
  204. return ll > rr;
  205. /* >= */
  206. return ll >= rr;
  207. }
  208. /* The arithmetic operator handling functions. */
  209. static arith_t arithmetic_common(VALUE *l, VALUE *r, int op)
  210. {
  211. arith_t li, ri;
  212. if (!toarith(l) || !toarith(r))
  213. bb_error_msg_and_die("non-numeric argument");
  214. li = l->u.i;
  215. ri = r->u.i;
  216. if (op == '+')
  217. return li + ri;
  218. if (op == '-')
  219. return li - ri;
  220. if (op == '*')
  221. return li * ri;
  222. if (ri == 0)
  223. bb_error_msg_and_die("division by zero");
  224. if (op == '/')
  225. return li / ri;
  226. return li % ri;
  227. }
  228. /* Do the : operator.
  229. SV is the VALUE for the lhs (the string),
  230. PV is the VALUE for the rhs (the pattern). */
  231. static VALUE *docolon(VALUE *sv, VALUE *pv)
  232. {
  233. enum { NMATCH = 2 };
  234. VALUE *v;
  235. regex_t re_buffer;
  236. regmatch_t re_regs[NMATCH];
  237. tostring(sv);
  238. tostring(pv);
  239. if (pv->u.s[0] == '^') {
  240. bb_error_msg(
  241. "warning: '%s': using '^' as the first character\n"
  242. "of a basic regular expression is not portable; it is ignored", pv->u.s);
  243. }
  244. memset(&re_buffer, 0, sizeof(re_buffer));
  245. memset(re_regs, 0, sizeof(re_regs));
  246. xregcomp(&re_buffer, pv->u.s, 0);
  247. /* expr uses an anchored pattern match, so check that there was a
  248. * match and that the match starts at offset 0. */
  249. if (regexec(&re_buffer, sv->u.s, NMATCH, re_regs, 0) != REG_NOMATCH
  250. && re_regs[0].rm_so == 0
  251. ) {
  252. /* Were \(...\) used? */
  253. if (re_buffer.re_nsub > 0 && re_regs[1].rm_so >= 0) {
  254. sv->u.s[re_regs[1].rm_eo] = '\0';
  255. v = str_value(sv->u.s + re_regs[1].rm_so);
  256. } else {
  257. v = int_value(re_regs[0].rm_eo);
  258. }
  259. } else {
  260. /* Match failed -- return the right kind of null. */
  261. if (re_buffer.re_nsub > 0)
  262. v = str_value("");
  263. else
  264. v = int_value(0);
  265. }
  266. regfree(&re_buffer);
  267. return v;
  268. }
  269. /* Handle bare operands and ( expr ) syntax. */
  270. static VALUE *eval7(void)
  271. {
  272. VALUE *v;
  273. if (!*G.args)
  274. bb_error_msg_and_die("syntax error");
  275. if (nextarg("(")) {
  276. G.args++;
  277. v = eval();
  278. if (!nextarg(")"))
  279. bb_error_msg_and_die("syntax error");
  280. G.args++;
  281. return v;
  282. }
  283. if (nextarg(")"))
  284. bb_error_msg_and_die("syntax error");
  285. return str_value(*G.args++);
  286. }
  287. /* Handle match, substr, index, length, and quote keywords. */
  288. static VALUE *eval6(void)
  289. {
  290. static const char keywords[] ALIGN1 =
  291. "quote\0""length\0""match\0""index\0""substr\0";
  292. VALUE *r, *i1, *i2;
  293. VALUE *l = l; /* silence gcc */
  294. VALUE *v = v; /* silence gcc */
  295. int key = *G.args ? index_in_strings(keywords, *G.args) + 1 : 0;
  296. if (key == 0) /* not a keyword */
  297. return eval7();
  298. G.args++; /* We have a valid token, so get the next argument. */
  299. if (key == 1) { /* quote */
  300. if (!*G.args)
  301. bb_error_msg_and_die("syntax error");
  302. return str_value(*G.args++);
  303. }
  304. if (key == 2) { /* length */
  305. r = eval6();
  306. tostring(r);
  307. v = int_value(strlen(r->u.s));
  308. freev(r);
  309. } else
  310. l = eval6();
  311. if (key == 3) { /* match */
  312. r = eval6();
  313. v = docolon(l, r);
  314. freev(l);
  315. freev(r);
  316. }
  317. if (key == 4) { /* index */
  318. r = eval6();
  319. tostring(l);
  320. tostring(r);
  321. v = int_value(strcspn(l->u.s, r->u.s) + 1);
  322. if (v->u.i == (arith_t) strlen(l->u.s) + 1)
  323. v->u.i = 0;
  324. freev(l);
  325. freev(r);
  326. }
  327. if (key == 5) { /* substr */
  328. i1 = eval6();
  329. i2 = eval6();
  330. tostring(l);
  331. if (!toarith(i1) || !toarith(i2)
  332. || i1->u.i > (arith_t) strlen(l->u.s)
  333. || i1->u.i <= 0 || i2->u.i <= 0)
  334. v = str_value("");
  335. else {
  336. v = xmalloc(sizeof(VALUE));
  337. v->type = STRING;
  338. v->u.s = xstrndup(l->u.s + i1->u.i - 1, i2->u.i);
  339. }
  340. freev(l);
  341. freev(i1);
  342. freev(i2);
  343. }
  344. return v;
  345. }
  346. /* Handle : operator (pattern matching).
  347. Calls docolon to do the real work. */
  348. static VALUE *eval5(void)
  349. {
  350. VALUE *l, *r, *v;
  351. l = eval6();
  352. while (nextarg(":")) {
  353. G.args++;
  354. r = eval6();
  355. v = docolon(l, r);
  356. freev(l);
  357. freev(r);
  358. l = v;
  359. }
  360. return l;
  361. }
  362. /* Handle *, /, % operators. */
  363. static VALUE *eval4(void)
  364. {
  365. VALUE *l, *r;
  366. int op;
  367. arith_t val;
  368. l = eval5();
  369. while (1) {
  370. op = nextarg("*");
  371. if (!op) { op = nextarg("/");
  372. if (!op) { op = nextarg("%");
  373. if (!op) return l;
  374. }}
  375. G.args++;
  376. r = eval5();
  377. val = arithmetic_common(l, r, op);
  378. freev(l);
  379. freev(r);
  380. l = int_value(val);
  381. }
  382. }
  383. /* Handle +, - operators. */
  384. static VALUE *eval3(void)
  385. {
  386. VALUE *l, *r;
  387. int op;
  388. arith_t val;
  389. l = eval4();
  390. while (1) {
  391. op = nextarg("+");
  392. if (!op) {
  393. op = nextarg("-");
  394. if (!op) return l;
  395. }
  396. G.args++;
  397. r = eval4();
  398. val = arithmetic_common(l, r, op);
  399. freev(l);
  400. freev(r);
  401. l = int_value(val);
  402. }
  403. }
  404. /* Handle comparisons. */
  405. static VALUE *eval2(void)
  406. {
  407. VALUE *l, *r;
  408. int op;
  409. arith_t val;
  410. l = eval3();
  411. while (1) {
  412. op = nextarg("<");
  413. if (!op) { op = nextarg("<=");
  414. if (!op) { op = nextarg("=");
  415. if (!op) { op = nextarg("==");
  416. if (!op) { op = nextarg("!=");
  417. if (!op) { op = nextarg(">=");
  418. if (!op) { op = nextarg(">");
  419. if (!op) return l;
  420. }}}}}}
  421. G.args++;
  422. r = eval3();
  423. toarith(l);
  424. toarith(r);
  425. val = cmp_common(l, r, op);
  426. freev(l);
  427. freev(r);
  428. l = int_value(val);
  429. }
  430. }
  431. /* Handle &. */
  432. static VALUE *eval1(void)
  433. {
  434. VALUE *l, *r;
  435. l = eval2();
  436. while (nextarg("&")) {
  437. G.args++;
  438. r = eval2();
  439. if (null(l) || null(r)) {
  440. freev(l);
  441. freev(r);
  442. l = int_value(0);
  443. } else
  444. freev(r);
  445. }
  446. return l;
  447. }
  448. /* Handle |. */
  449. static VALUE *eval(void)
  450. {
  451. VALUE *l, *r;
  452. l = eval1();
  453. while (nextarg("|")) {
  454. G.args++;
  455. r = eval1();
  456. if (null(l)) {
  457. freev(l);
  458. l = r;
  459. } else
  460. freev(r);
  461. }
  462. return l;
  463. }
  464. int expr_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  465. int expr_main(int argc UNUSED_PARAM, char **argv)
  466. {
  467. VALUE *v;
  468. INIT_G();
  469. xfunc_error_retval = 2; /* coreutils compat */
  470. G.args = argv + 1;
  471. if (*G.args == NULL) {
  472. bb_error_msg_and_die("too few arguments");
  473. }
  474. v = eval();
  475. if (*G.args)
  476. bb_error_msg_and_die("syntax error");
  477. if (v->type == INTEGER)
  478. printf("%" PF_REZ "d\n", PF_REZ_TYPE v->u.i);
  479. else
  480. puts(v->u.s);
  481. fflush_stdout_and_exit(null(v));
  482. }