3
0

expr.c 11 KB

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