Merge tag 'xilinx-for-v2025.01-rc3-v2' of https://source.denx.de/u-boot/custodians...
[u-boot.git] / cmd / setexpr.c
blobe111b8ba98ad7c276621aca949ccd31ba5dc12ed
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3 * Copyright 2008 Freescale Semiconductor, Inc.
4 * Copyright 2013 Wolfgang Denk <wd@denx.de>
5 */
7 /*
8 * This file provides a shell like 'expr' function to return.
9 */
11 #include <config.h>
12 #include <command.h>
13 #include <ctype.h>
14 #include <env.h>
15 #include <log.h>
16 #include <malloc.h>
17 #include <mapmem.h>
18 #include <vsprintf.h>
19 #include <linux/errno.h>
20 #include <linux/sizes.h>
21 #include "printf.h"
23 #define MAX_STR_LEN 128
25 /**
26 * struct expr_arg: Holds an argument to an expression
28 * @ival: Integer value (if width is not CMD_DATA_SIZE_STR)
29 * @sval: String value (if width is CMD_DATA_SIZE_STR)
31 struct expr_arg {
32 union {
33 ulong ival;
34 char *sval;
38 static int get_arg(char *s, int w, struct expr_arg *argp)
40 struct expr_arg arg;
43 * If the parameter starts with a '*' then assume it is a pointer to
44 * the value we want.
46 if (s[0] == '*') {
47 ulong *p;
48 ulong addr;
49 ulong val;
50 int len;
51 char *str;
53 addr = hextoul(&s[1], NULL);
54 switch (w) {
55 case 1:
56 p = map_sysmem(addr, sizeof(uchar));
57 val = (ulong)*(uchar *)p;
58 unmap_sysmem(p);
59 arg.ival = val;
60 break;
61 case 2:
62 p = map_sysmem(addr, sizeof(ushort));
63 val = (ulong)*(ushort *)p;
64 unmap_sysmem(p);
65 arg.ival = val;
66 break;
67 case CMD_DATA_SIZE_STR:
68 p = map_sysmem(addr, SZ_64K);
70 /* Maximum string length of 64KB plus terminator */
71 len = strnlen((char *)p, SZ_64K) + 1;
72 str = malloc(len);
73 if (!str) {
74 printf("Out of memory\n");
75 return -ENOMEM;
77 memcpy(str, p, len);
78 str[len - 1] = '\0';
79 unmap_sysmem(p);
80 arg.sval = str;
81 break;
82 case 4:
83 p = map_sysmem(addr, sizeof(u32));
84 val = *(u32 *)p;
85 unmap_sysmem(p);
86 arg.ival = val;
87 break;
88 default:
89 p = map_sysmem(addr, sizeof(ulong));
90 val = *p;
91 unmap_sysmem(p);
92 arg.ival = val;
93 break;
95 } else {
96 if (w == CMD_DATA_SIZE_STR)
97 return -EINVAL;
98 arg.ival = hextoul(s, NULL);
100 *argp = arg;
102 return 0;
105 #ifdef CONFIG_REGEX
107 #include <slre.h>
110 * memstr - Find the first substring in memory
111 * @s1: The string to be searched
112 * @s2: The string to search for
114 * Similar to and based on strstr(),
115 * but strings do not need to be NUL terminated.
117 static char *memstr(const char *s1, int l1, const char *s2, int l2)
119 if (!l2)
120 return (char *)s1;
122 while (l1 >= l2) {
123 l1--;
124 if (!memcmp(s1, s2, l2))
125 return (char *)s1;
126 s1++;
128 return NULL;
132 * substitute() - Substitute part of one string with another
134 * This updates @string so that the first occurrence of @old is replaced with
135 * @new
137 * @string: String buffer containing string to update at the start
138 * @slen: Pointer to current string length, updated on success
139 * @ssize: Size of string buffer
140 * @old: Old string to find in the buffer (no terminator needed)
141 * @olen: Length of @old excluding terminator
142 * @new: New string to replace @old with
143 * @nlen: Length of @new excluding terminator
144 * Return: pointer to immediately after the copied @new in @string, or NULL if
145 * no replacement took place
147 static char *substitute(char *string, int *slen, int ssize,
148 const char *old, int olen, const char *new, int nlen)
150 char *p = memstr(string, *slen, old, olen);
152 if (p == NULL)
153 return NULL;
155 debug("## Match at pos %ld: match len %d, subst len %d\n",
156 (long)(p - string), olen, nlen);
158 /* make sure replacement matches */
159 if (*slen + nlen - olen > ssize) {
160 printf("## error: substitution buffer overflow\n");
161 return NULL;
164 /* move tail if needed */
165 if (olen != nlen) {
166 int tail, len;
168 len = (olen > nlen) ? olen : nlen;
170 tail = ssize - (p + len - string);
172 debug("## tail len %d\n", tail);
174 memmove(p + nlen, p + olen, tail);
177 /* insert substitute */
178 memcpy(p, new, nlen);
180 *slen += nlen - olen;
182 return p + nlen;
185 int setexpr_regex_sub(char *data, uint data_size, char *nbuf, uint nbuf_size,
186 const char *r, const char *s, bool global)
188 struct slre slre;
189 char *datap = data;
190 int res, len, nlen, loop;
192 if (slre_compile(&slre, r) == 0) {
193 printf("Error compiling regex: %s\n", slre.err_str);
194 return 1;
197 len = strlen(data);
198 for (loop = 0;; loop++) {
199 struct cap caps[slre.num_caps + 2];
200 const char *old;
201 char *np;
202 int i, olen;
204 (void) memset(caps, 0, sizeof(caps));
206 res = slre_match(&slre, datap, len - (datap - data), caps);
208 debug("Result: %d\n", res);
210 for (i = 0; i <= slre.num_caps; i++) {
211 if (caps[i].len > 0) {
212 debug("Substring %d: [%.*s]\n", i,
213 caps[i].len, caps[i].ptr);
217 if (res == 0) {
218 if (loop == 0) {
219 debug("%s: No match\n", data);
220 } else {
221 debug("## MATCH ## %s\n", data);
223 break;
226 if (!s)
227 return 1;
229 old = caps[0].ptr;
230 olen = caps[0].len;
231 nlen = strlen(s);
233 if (nlen + 1 >= nbuf_size) {
234 printf("## error: pattern buffer overflow: have %d, need %d\n",
235 nbuf_size, nlen + 1);
236 return 1;
238 strcpy(nbuf, s);
240 debug("## SUBST(1) ## %s\n", nbuf);
243 * Handle back references
245 * Support for \0 ... \9, where \0 is the
246 * whole matched pattern (similar to &).
248 * Implementation is a bit simpleminded as
249 * backrefs are substituted sequentially, one
250 * by one. This will lead to somewhat
251 * unexpected results if the replacement
252 * strings contain any \N strings then then
253 * may get substitued, too. We accept this
254 * restriction for the sake of simplicity.
256 for (i = 0; i < 10; ++i) {
257 char backref[2] = {
258 '\\',
259 '0',
262 if (caps[i].len == 0)
263 break;
265 backref[1] += i;
267 debug("## BACKREF %d: replace \"%.*s\" by \"%.*s\" in \"%s\"\n",
269 2, backref,
270 caps[i].len, caps[i].ptr,
271 nbuf);
273 for (np = nbuf;;) {
274 char *p = memstr(np, nlen, backref, 2);
276 if (p == NULL)
277 break;
279 np = substitute(np, &nlen,
280 nbuf_size - (np - nbuf),
281 backref, 2,
282 caps[i].ptr, caps[i].len);
284 if (np == NULL)
285 return 1;
288 debug("## SUBST(2) ## %s\n", nbuf);
290 datap = substitute(datap, &len, data_size - (datap - data),
291 old, olen, nbuf, nlen);
293 if (datap == NULL)
294 return 1;
296 debug("## REMAINDER: %s\n", datap);
298 debug("## RESULT: %s\n", data);
300 if (!global)
301 break;
303 debug("## FINAL (now env_set()) : %s\n", data);
305 return 0;
308 #define SLRE_BUFSZ 16384
309 #define SLRE_PATSZ 4096
312 * Perform regex operations on a environment variable
314 * Returns 0 if OK, 1 in case of errors.
316 static int regex_sub_var(const char *name, const char *r, const char *s,
317 const char *t, int global)
319 struct slre slre;
320 char data[SLRE_BUFSZ];
321 char nbuf[SLRE_PATSZ];
322 const char *value;
323 int len;
324 int ret;
326 if (!name)
327 return 1;
329 if (slre_compile(&slre, r) == 0) {
330 printf("Error compiling regex: %s\n", slre.err_str);
331 return 1;
334 if (!t) {
335 value = env_get(name);
336 if (!value) {
337 printf("## Error: variable \"%s\" not defined\n", name);
338 return 1;
340 t = value;
343 debug("REGEX on %s=%s\n", name, t);
344 debug("REGEX=\"%s\", SUBST=\"%s\", GLOBAL=%d\n", r, s ? s : "<NULL>",
345 global);
347 len = strlen(t);
348 if (len + 1 > SLRE_BUFSZ) {
349 printf("## error: subst buffer overflow: have %d, need %d\n",
350 SLRE_BUFSZ, len + 1);
351 return 1;
354 strcpy(data, t);
356 ret = setexpr_regex_sub(data, SLRE_BUFSZ, nbuf, SLRE_PATSZ, r, s,
357 global);
358 if (ret)
359 return 1;
361 debug("%s=%s\n", name, data);
363 return env_set(name, data);
365 #endif
367 static int do_setexpr(struct cmd_tbl *cmdtp, int flag, int argc,
368 char *const argv[])
370 struct expr_arg aval, bval;
371 ulong value;
372 int ret = 0;
373 int w;
376 * We take 3, 5, or 6 arguments, except fmt operation, which
377 * takes 4 to 8 arguments (limited by _maxargs):
378 * 3 : setexpr name value
379 * 5 : setexpr name val1 op val2
380 * setexpr name [g]sub r s
381 * 6 : setexpr name [g]sub r s t
382 * setexpr name fmt format [val1] [val2] [val3] [val4]
385 if (argc < 3)
386 return CMD_RET_USAGE;
388 w = cmd_get_data_size(argv[0], 4);
390 if (get_arg(argv[2], w, &aval))
391 return CMD_RET_FAILURE;
393 /* format string assignment: "setexpr name fmt %d value" */
394 if (strcmp(argv[2], "fmt") == 0 && IS_ENABLED(CONFIG_CMD_SETEXPR_FMT)) {
395 char str[MAX_STR_LEN];
396 int result;
398 if (argc == 3)
399 return CMD_RET_USAGE;
401 result = printf_setexpr(str, sizeof(str), argc - 3, &argv[3]);
402 if (result)
403 return result;
405 return env_set(argv[1], str);
408 if (argc == 4 || argc > 6)
409 return CMD_RET_USAGE;
411 /* plain assignment: "setexpr name value" */
412 if (argc == 3) {
413 if (w == CMD_DATA_SIZE_STR) {
414 ret = env_set(argv[1], aval.sval);
415 free(aval.sval);
416 } else {
417 ret = env_set_hex(argv[1], aval.ival);
420 return ret;
423 /* 5 or 6 args (6 args only with [g]sub) */
424 #ifdef CONFIG_REGEX
426 * rexep handling: "setexpr name [g]sub r s [t]"
427 * with 5 args, "t" will be NULL
429 if (strcmp(argv[2], "gsub") == 0)
430 return regex_sub_var(argv[1], argv[3], argv[4], argv[5], 1);
432 if (strcmp(argv[2], "sub") == 0)
433 return regex_sub_var(argv[1], argv[3], argv[4], argv[5], 0);
434 #endif
436 /* standard operators: "setexpr name val1 op val2" */
437 if (argc != 5)
438 return CMD_RET_USAGE;
440 if (strlen(argv[3]) != 1)
441 return CMD_RET_USAGE;
443 if (get_arg(argv[4], w, &bval)) {
444 if (w == CMD_DATA_SIZE_STR)
445 free(aval.sval);
446 return CMD_RET_FAILURE;
449 if (w == CMD_DATA_SIZE_STR) {
450 int len;
451 char *str;
453 switch (argv[3][0]) {
454 case '+':
455 len = strlen(aval.sval) + strlen(bval.sval) + 1;
456 str = malloc(len);
457 if (!str) {
458 printf("Out of memory\n");
459 ret = CMD_RET_FAILURE;
460 } else {
461 /* These were copied out and checked earlier */
462 strcpy(str, aval.sval);
463 strcat(str, bval.sval);
464 ret = env_set(argv[1], str);
465 if (ret)
466 printf("Could not set var\n");
467 free(str);
469 break;
470 default:
471 printf("invalid op\n");
472 ret = 1;
474 } else {
475 ulong a = aval.ival;
476 ulong b = bval.ival;
478 switch (argv[3][0]) {
479 case '|':
480 value = a | b;
481 break;
482 case '&':
483 value = a & b;
484 break;
485 case '+':
486 value = a + b;
487 break;
488 case '^':
489 value = a ^ b;
490 break;
491 case '-':
492 value = a - b;
493 break;
494 case '*':
495 value = a * b;
496 break;
497 case '/':
498 value = a / b;
499 break;
500 case '%':
501 value = a % b;
502 break;
503 default:
504 printf("invalid op\n");
505 return 1;
508 env_set_hex(argv[1], value);
511 if (w == CMD_DATA_SIZE_STR) {
512 free(aval.sval);
513 free(bval.sval);
516 return ret;
519 U_BOOT_CMD(
520 setexpr, 8, 0, do_setexpr,
521 "set environment variable as the result of eval expression",
522 "[.b, .w, .l, .s] name [*]value1 <op> [*]value2\n"
523 " - set environment variable 'name' to the result of the evaluated\n"
524 " expression specified by <op>. <op> can be &, |, ^, +, -, *, /, %\n"
525 " (for strings only + is supported)\n"
526 " size argument is only meaningful if value1 and/or value2 are\n"
527 " memory addresses (*)\n"
528 "setexpr[.b, .w, .l] name [*]value\n"
529 " - load a value into a variable"
530 #ifdef CONFIG_CMD_SETEXPR_FMT
531 "\n"
532 "setexpr name fmt <format> [value1] [value2] [value3] [value4]\n"
533 " - set environment variable 'name' to the result of the bash like\n"
534 " format string evaluation of value."
535 #endif
536 #ifdef CONFIG_REGEX
537 "\n"
538 "setexpr name gsub r s [t]\n"
539 " - For each substring matching the regular expression <r> in the\n"
540 " string <t>, substitute the string <s>. The result is\n"
541 " assigned to <name>. If <t> is not supplied, use the old\n"
542 " value of <name>. If no substring matching <r> is found in <t>,\n"
543 " assign <t> to <name>.\n"
544 "setexpr name sub r s [t]\n"
545 " - Just like gsub(), but replace only the first matching substring"
546 #endif