setexpr.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. // SPDX-License-Identifier: GPL-2.0+
  2. /*
  3. * Copyright 2008 Freescale Semiconductor, Inc.
  4. * Copyright 2013 Wolfgang Denk <wd@denx.de>
  5. */
  6. /*
  7. * This file provides a shell like 'expr' function to return.
  8. */
  9. #include <common.h>
  10. #include <config.h>
  11. #include <command.h>
  12. #include <ctype.h>
  13. #include <env.h>
  14. #include <log.h>
  15. #include <malloc.h>
  16. #include <mapmem.h>
  17. #include <linux/sizes.h>
  18. #include "printf.h"
  19. #define MAX_STR_LEN 128
  20. /**
  21. * struct expr_arg: Holds an argument to an expression
  22. *
  23. * @ival: Integer value (if width is not CMD_DATA_SIZE_STR)
  24. * @sval: String value (if width is CMD_DATA_SIZE_STR)
  25. */
  26. struct expr_arg {
  27. union {
  28. ulong ival;
  29. char *sval;
  30. };
  31. };
  32. static int get_arg(char *s, int w, struct expr_arg *argp)
  33. {
  34. struct expr_arg arg;
  35. /*
  36. * If the parameter starts with a '*' then assume it is a pointer to
  37. * the value we want.
  38. */
  39. if (s[0] == '*') {
  40. ulong *p;
  41. ulong addr;
  42. ulong val;
  43. int len;
  44. char *str;
  45. addr = hextoul(&s[1], NULL);
  46. switch (w) {
  47. case 1:
  48. p = map_sysmem(addr, sizeof(uchar));
  49. val = (ulong)*(uchar *)p;
  50. unmap_sysmem(p);
  51. arg.ival = val;
  52. break;
  53. case 2:
  54. p = map_sysmem(addr, sizeof(ushort));
  55. val = (ulong)*(ushort *)p;
  56. unmap_sysmem(p);
  57. arg.ival = val;
  58. break;
  59. case CMD_DATA_SIZE_STR:
  60. p = map_sysmem(addr, SZ_64K);
  61. /* Maximum string length of 64KB plus terminator */
  62. len = strnlen((char *)p, SZ_64K) + 1;
  63. str = malloc(len);
  64. if (!str) {
  65. printf("Out of memory\n");
  66. return -ENOMEM;
  67. }
  68. memcpy(str, p, len);
  69. str[len - 1] = '\0';
  70. unmap_sysmem(p);
  71. arg.sval = str;
  72. break;
  73. case 4:
  74. p = map_sysmem(addr, sizeof(u32));
  75. val = *(u32 *)p;
  76. unmap_sysmem(p);
  77. arg.ival = val;
  78. break;
  79. default:
  80. p = map_sysmem(addr, sizeof(ulong));
  81. val = *p;
  82. unmap_sysmem(p);
  83. arg.ival = val;
  84. break;
  85. }
  86. } else {
  87. if (w == CMD_DATA_SIZE_STR)
  88. return -EINVAL;
  89. arg.ival = hextoul(s, NULL);
  90. }
  91. *argp = arg;
  92. return 0;
  93. }
  94. #ifdef CONFIG_REGEX
  95. #include <slre.h>
  96. /*
  97. * memstr - Find the first substring in memory
  98. * @s1: The string to be searched
  99. * @s2: The string to search for
  100. *
  101. * Similar to and based on strstr(),
  102. * but strings do not need to be NUL terminated.
  103. */
  104. static char *memstr(const char *s1, int l1, const char *s2, int l2)
  105. {
  106. if (!l2)
  107. return (char *)s1;
  108. while (l1 >= l2) {
  109. l1--;
  110. if (!memcmp(s1, s2, l2))
  111. return (char *)s1;
  112. s1++;
  113. }
  114. return NULL;
  115. }
  116. /**
  117. * substitute() - Substitute part of one string with another
  118. *
  119. * This updates @string so that the first occurrence of @old is replaced with
  120. * @new
  121. *
  122. * @string: String buffer containing string to update at the start
  123. * @slen: Pointer to current string length, updated on success
  124. * @ssize: Size of string buffer
  125. * @old: Old string to find in the buffer (no terminator needed)
  126. * @olen: Length of @old excluding terminator
  127. * @new: New string to replace @old with
  128. * @nlen: Length of @new excluding terminator
  129. * @return pointer to immediately after the copied @new in @string, or NULL if
  130. * no replacement took place
  131. */
  132. static char *substitute(char *string, int *slen, int ssize,
  133. const char *old, int olen, const char *new, int nlen)
  134. {
  135. char *p = memstr(string, *slen, old, olen);
  136. if (p == NULL)
  137. return NULL;
  138. debug("## Match at pos %ld: match len %d, subst len %d\n",
  139. (long)(p - string), olen, nlen);
  140. /* make sure replacement matches */
  141. if (*slen + nlen - olen > ssize) {
  142. printf("## error: substitution buffer overflow\n");
  143. return NULL;
  144. }
  145. /* move tail if needed */
  146. if (olen != nlen) {
  147. int tail, len;
  148. len = (olen > nlen) ? olen : nlen;
  149. tail = ssize - (p + len - string);
  150. debug("## tail len %d\n", tail);
  151. memmove(p + nlen, p + olen, tail);
  152. }
  153. /* insert substitute */
  154. memcpy(p, new, nlen);
  155. *slen += nlen - olen;
  156. return p + nlen;
  157. }
  158. int setexpr_regex_sub(char *data, uint data_size, char *nbuf, uint nbuf_size,
  159. const char *r, const char *s, bool global)
  160. {
  161. struct slre slre;
  162. char *datap = data;
  163. int res, len, nlen, loop;
  164. if (slre_compile(&slre, r) == 0) {
  165. printf("Error compiling regex: %s\n", slre.err_str);
  166. return 1;
  167. }
  168. len = strlen(data);
  169. for (loop = 0;; loop++) {
  170. struct cap caps[slre.num_caps + 2];
  171. const char *old;
  172. char *np;
  173. int i, olen;
  174. (void) memset(caps, 0, sizeof(caps));
  175. res = slre_match(&slre, datap, len - (datap - data), caps);
  176. debug("Result: %d\n", res);
  177. for (i = 0; i <= slre.num_caps; i++) {
  178. if (caps[i].len > 0) {
  179. debug("Substring %d: [%.*s]\n", i,
  180. caps[i].len, caps[i].ptr);
  181. }
  182. }
  183. if (res == 0) {
  184. if (loop == 0) {
  185. printf("%s: No match\n", data);
  186. return 1;
  187. } else {
  188. break;
  189. }
  190. }
  191. debug("## MATCH ## %s\n", data);
  192. if (!s)
  193. return 1;
  194. old = caps[0].ptr;
  195. olen = caps[0].len;
  196. nlen = strlen(s);
  197. if (nlen + 1 >= nbuf_size) {
  198. printf("## error: pattern buffer overflow: have %d, need %d\n",
  199. nbuf_size, nlen + 1);
  200. return 1;
  201. }
  202. strcpy(nbuf, s);
  203. debug("## SUBST(1) ## %s\n", nbuf);
  204. /*
  205. * Handle back references
  206. *
  207. * Support for \0 ... \9, where \0 is the
  208. * whole matched pattern (similar to &).
  209. *
  210. * Implementation is a bit simpleminded as
  211. * backrefs are substituted sequentially, one
  212. * by one. This will lead to somewhat
  213. * unexpected results if the replacement
  214. * strings contain any \N strings then then
  215. * may get substitued, too. We accept this
  216. * restriction for the sake of simplicity.
  217. */
  218. for (i = 0; i < 10; ++i) {
  219. char backref[2] = {
  220. '\\',
  221. '0',
  222. };
  223. if (caps[i].len == 0)
  224. break;
  225. backref[1] += i;
  226. debug("## BACKREF %d: replace \"%.*s\" by \"%.*s\" in \"%s\"\n",
  227. i,
  228. 2, backref,
  229. caps[i].len, caps[i].ptr,
  230. nbuf);
  231. for (np = nbuf;;) {
  232. char *p = memstr(np, nlen, backref, 2);
  233. if (p == NULL)
  234. break;
  235. np = substitute(np, &nlen,
  236. nbuf_size - (np - nbuf),
  237. backref, 2,
  238. caps[i].ptr, caps[i].len);
  239. if (np == NULL)
  240. return 1;
  241. }
  242. }
  243. debug("## SUBST(2) ## %s\n", nbuf);
  244. datap = substitute(datap, &len, data_size - (datap - data),
  245. old, olen, nbuf, nlen);
  246. if (datap == NULL)
  247. return 1;
  248. debug("## REMAINDER: %s\n", datap);
  249. debug("## RESULT: %s\n", data);
  250. if (!global)
  251. break;
  252. }
  253. debug("## FINAL (now env_set()) : %s\n", data);
  254. return 0;
  255. }
  256. #define SLRE_BUFSZ 16384
  257. #define SLRE_PATSZ 4096
  258. /*
  259. * Perform regex operations on a environment variable
  260. *
  261. * Returns 0 if OK, 1 in case of errors.
  262. */
  263. static int regex_sub_var(const char *name, const char *r, const char *s,
  264. const char *t, int global)
  265. {
  266. struct slre slre;
  267. char data[SLRE_BUFSZ];
  268. char nbuf[SLRE_PATSZ];
  269. const char *value;
  270. int len;
  271. int ret;
  272. if (!name)
  273. return 1;
  274. if (slre_compile(&slre, r) == 0) {
  275. printf("Error compiling regex: %s\n", slre.err_str);
  276. return 1;
  277. }
  278. if (!t) {
  279. value = env_get(name);
  280. if (!value) {
  281. printf("## Error: variable \"%s\" not defined\n", name);
  282. return 1;
  283. }
  284. t = value;
  285. }
  286. debug("REGEX on %s=%s\n", name, t);
  287. debug("REGEX=\"%s\", SUBST=\"%s\", GLOBAL=%d\n", r, s ? s : "<NULL>",
  288. global);
  289. len = strlen(t);
  290. if (len + 1 > SLRE_BUFSZ) {
  291. printf("## error: subst buffer overflow: have %d, need %d\n",
  292. SLRE_BUFSZ, len + 1);
  293. return 1;
  294. }
  295. strcpy(data, t);
  296. ret = setexpr_regex_sub(data, SLRE_BUFSZ, nbuf, SLRE_PATSZ, r, s,
  297. global);
  298. if (ret)
  299. return 1;
  300. printf("%s=%s\n", name, data);
  301. return env_set(name, data);
  302. }
  303. #endif
  304. static int do_setexpr(struct cmd_tbl *cmdtp, int flag, int argc,
  305. char *const argv[])
  306. {
  307. struct expr_arg aval, bval;
  308. ulong value;
  309. int ret = 0;
  310. int w;
  311. /*
  312. * We take 3, 5, or 6 arguments, except fmt operation, which
  313. * takes 4 to 8 arguments (limited by _maxargs):
  314. * 3 : setexpr name value
  315. * 5 : setexpr name val1 op val2
  316. * setexpr name [g]sub r s
  317. * 6 : setexpr name [g]sub r s t
  318. * setexpr name fmt format [val1] [val2] [val3] [val4]
  319. */
  320. if (argc < 3)
  321. return CMD_RET_USAGE;
  322. w = cmd_get_data_size(argv[0], 4);
  323. if (get_arg(argv[2], w, &aval))
  324. return CMD_RET_FAILURE;
  325. /* format string assignment: "setexpr name fmt %d value" */
  326. if (strcmp(argv[2], "fmt") == 0 && IS_ENABLED(CONFIG_CMD_SETEXPR_FMT)) {
  327. char str[MAX_STR_LEN];
  328. int result;
  329. if (argc == 3)
  330. return CMD_RET_USAGE;
  331. result = printf_setexpr(str, sizeof(str), argc - 3, &argv[3]);
  332. if (result)
  333. return result;
  334. return env_set(argv[1], str);
  335. }
  336. if (argc == 4 || argc > 6)
  337. return CMD_RET_USAGE;
  338. /* plain assignment: "setexpr name value" */
  339. if (argc == 3) {
  340. if (w == CMD_DATA_SIZE_STR) {
  341. ret = env_set(argv[1], aval.sval);
  342. free(aval.sval);
  343. } else {
  344. ret = env_set_hex(argv[1], aval.ival);
  345. }
  346. return ret;
  347. }
  348. /* 5 or 6 args (6 args only with [g]sub) */
  349. #ifdef CONFIG_REGEX
  350. /*
  351. * rexep handling: "setexpr name [g]sub r s [t]"
  352. * with 5 args, "t" will be NULL
  353. */
  354. if (strcmp(argv[2], "gsub") == 0)
  355. return regex_sub_var(argv[1], argv[3], argv[4], argv[5], 1);
  356. if (strcmp(argv[2], "sub") == 0)
  357. return regex_sub_var(argv[1], argv[3], argv[4], argv[5], 0);
  358. #endif
  359. /* standard operators: "setexpr name val1 op val2" */
  360. if (argc != 5)
  361. return CMD_RET_USAGE;
  362. if (strlen(argv[3]) != 1)
  363. return CMD_RET_USAGE;
  364. if (get_arg(argv[4], w, &bval)) {
  365. if (w == CMD_DATA_SIZE_STR)
  366. free(aval.sval);
  367. return CMD_RET_FAILURE;
  368. }
  369. if (w == CMD_DATA_SIZE_STR) {
  370. int len;
  371. char *str;
  372. switch (argv[3][0]) {
  373. case '+':
  374. len = strlen(aval.sval) + strlen(bval.sval) + 1;
  375. str = malloc(len);
  376. if (!str) {
  377. printf("Out of memory\n");
  378. ret = CMD_RET_FAILURE;
  379. } else {
  380. /* These were copied out and checked earlier */
  381. strcpy(str, aval.sval);
  382. strcat(str, bval.sval);
  383. ret = env_set(argv[1], str);
  384. if (ret)
  385. printf("Could not set var\n");
  386. free(str);
  387. }
  388. break;
  389. default:
  390. printf("invalid op\n");
  391. ret = 1;
  392. }
  393. } else {
  394. ulong a = aval.ival;
  395. ulong b = bval.ival;
  396. switch (argv[3][0]) {
  397. case '|':
  398. value = a | b;
  399. break;
  400. case '&':
  401. value = a & b;
  402. break;
  403. case '+':
  404. value = a + b;
  405. break;
  406. case '^':
  407. value = a ^ b;
  408. break;
  409. case '-':
  410. value = a - b;
  411. break;
  412. case '*':
  413. value = a * b;
  414. break;
  415. case '/':
  416. value = a / b;
  417. break;
  418. case '%':
  419. value = a % b;
  420. break;
  421. default:
  422. printf("invalid op\n");
  423. return 1;
  424. }
  425. env_set_hex(argv[1], value);
  426. }
  427. if (w == CMD_DATA_SIZE_STR) {
  428. free(aval.sval);
  429. free(bval.sval);
  430. }
  431. return ret;
  432. }
  433. U_BOOT_CMD(
  434. setexpr, 8, 0, do_setexpr,
  435. "set environment variable as the result of eval expression",
  436. "[.b, .w, .l, .s] name [*]value1 <op> [*]value2\n"
  437. " - set environment variable 'name' to the result of the evaluated\n"
  438. " expression specified by <op>. <op> can be &, |, ^, +, -, *, /, %\n"
  439. " (for strings only + is supported)\n"
  440. " size argument is only meaningful if value1 and/or value2 are\n"
  441. " memory addresses (*)\n"
  442. "setexpr[.b, .w, .l] name [*]value\n"
  443. " - load a value into a variable"
  444. #ifdef CONFIG_CMD_SETEXPR_FMT
  445. "\n"
  446. "setexpr name fmt <format> [value1] [value2] [value3] [value4]\n"
  447. " - set environment variable 'name' to the result of the bash like\n"
  448. " format string evaluation of value."
  449. #endif
  450. #ifdef CONFIG_REGEX
  451. "\n"
  452. "setexpr name gsub r s [t]\n"
  453. " - For each substring matching the regular expression <r> in the\n"
  454. " string <t>, substitute the string <s>. The result is\n"
  455. " assigned to <name>. If <t> is not supplied, use the old\n"
  456. " value of <name>\n"
  457. "setexpr name sub r s [t]\n"
  458. " - Just like gsub(), but replace only the first matching substring"
  459. #endif
  460. );