1 // SPDX-License-Identifier: GPL-2.0+
3 * Copyright 2008 Freescale Semiconductor, Inc.
8 * This file provides a shell like 'expr' function to return.
19 #include <linux/errno.h>
20 #include <linux/sizes.h>
23 #define MAX_STR_LEN 128
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)
38 static int get_arg(char *s, int w, struct expr_arg *argp)
43 * If the parameter starts with a '*' then assume it is a pointer to
53 addr = hextoul(&s[1], NULL);
56 p = map_sysmem(addr, sizeof(uchar));
57 val = (ulong)*(uchar *)p;
62 p = map_sysmem(addr, sizeof(ushort));
63 val = (ulong)*(ushort *)p;
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;
74 printf("Out of memory\n");
83 p = map_sysmem(addr, sizeof(u32));
89 p = map_sysmem(addr, sizeof(ulong));
96 if (w == CMD_DATA_SIZE_STR)
98 arg.ival = hextoul(s, NULL);
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)
124 if (!memcmp(s1, s2, l2))
132 * substitute() - Substitute part of one string with another
134 * This updates @string so that the first occurrence of @old is replaced with
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);
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");
164 /* move tail if needed */
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;
185 int setexpr_regex_sub(char *data, uint data_size, char *nbuf, uint nbuf_size,
186 const char *r, const char *s, bool global)
190 int res, len, nlen, loop;
192 if (slre_compile(&slre, r) == 0) {
193 printf("Error compiling regex: %s\n", slre.err_str);
198 for (loop = 0;; loop++) {
199 struct cap caps[slre.num_caps + 2];
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);
219 debug("%s: No match\n", data);
221 debug("## MATCH ## %s\n", data);
233 if (nlen + 1 >= nbuf_size) {
234 printf("## error: pattern buffer overflow: have %d, need %d\n",
235 nbuf_size, nlen + 1);
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) {
262 if (caps[i].len == 0)
267 debug("## BACKREF %d: replace \"%.*s\" by \"%.*s\" in \"%s\"\n",
270 caps[i].len, caps[i].ptr,
274 char *p = memstr(np, nlen, backref, 2);
279 np = substitute(np, &nlen,
280 nbuf_size - (np - nbuf),
282 caps[i].ptr, caps[i].len);
288 debug("## SUBST(2) ## %s\n", nbuf);
290 datap = substitute(datap, &len, data_size - (datap - data),
291 old, olen, nbuf, nlen);
296 debug("## REMAINDER: %s\n", datap);
298 debug("## RESULT: %s\n", data);
303 debug("## FINAL (now env_set()) : %s\n", data);
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)
320 char data[SLRE_BUFSZ];
321 char nbuf[SLRE_PATSZ];
329 if (slre_compile(&slre, r) == 0) {
330 printf("Error compiling regex: %s\n", slre.err_str);
335 value = env_get(name);
337 printf("## Error: variable \"%s\" not defined\n", name);
343 debug("REGEX on %s=%s\n", name, t);
344 debug("REGEX=\"%s\", SUBST=\"%s\", GLOBAL=%d\n", r, s ? s : "<NULL>",
348 if (len + 1 > SLRE_BUFSZ) {
349 printf("## error: subst buffer overflow: have %d, need %d\n",
350 SLRE_BUFSZ, len + 1);
356 ret = setexpr_regex_sub(data, SLRE_BUFSZ, nbuf, SLRE_PATSZ, r, s,
361 debug("%s=%s\n", name, data);
363 return env_set(name, data);
367 static int do_setexpr(struct cmd_tbl *cmdtp, int flag, int argc,
370 struct expr_arg aval, bval;
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]
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];
399 return CMD_RET_USAGE;
401 result = printf_setexpr(str, sizeof(str), argc - 3, &argv[3]);
405 return env_set(argv[1], str);
408 if (argc == 4 || argc > 6)
409 return CMD_RET_USAGE;
411 /* plain assignment: "setexpr name value" */
413 if (w == CMD_DATA_SIZE_STR) {
414 ret = env_set(argv[1], aval.sval);
417 ret = env_set_hex(argv[1], aval.ival);
423 /* 5 or 6 args (6 args only with [g]sub) */
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);
436 /* standard operators: "setexpr name val1 op val2" */
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)
446 return CMD_RET_FAILURE;
449 if (w == CMD_DATA_SIZE_STR) {
453 switch (argv[3][0]) {
455 len = strlen(aval.sval) + strlen(bval.sval) + 1;
458 printf("Out of memory\n");
459 ret = CMD_RET_FAILURE;
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);
466 printf("Could not set var\n");
471 printf("invalid op\n");
478 switch (argv[3][0]) {
504 printf("invalid op\n");
508 env_set_hex(argv[1], value);
511 if (w == CMD_DATA_SIZE_STR) {
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
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."
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"