3
0

expr.c 12 KB

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