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/sizes.h>
22 #define MAX_STR_LEN 128
25 * struct expr_arg: Holds an argument to an expression
27 * @ival: Integer value (if width is not CMD_DATA_SIZE_STR)
28 * @sval: String value (if width is CMD_DATA_SIZE_STR)
37 static int get_arg(char *s, int w, struct expr_arg *argp)
42 * If the parameter starts with a '*' then assume it is a pointer to
52 addr = hextoul(&s[1], NULL);
55 p = map_sysmem(addr, sizeof(uchar));
56 val = (ulong)*(uchar *)p;
61 p = map_sysmem(addr, sizeof(ushort));
62 val = (ulong)*(ushort *)p;
66 case CMD_DATA_SIZE_STR:
67 p = map_sysmem(addr, SZ_64K);
69 /* Maximum string length of 64KB plus terminator */
70 len = strnlen((char *)p, SZ_64K) + 1;
73 printf("Out of memory\n");
82 p = map_sysmem(addr, sizeof(u32));
88 p = map_sysmem(addr, sizeof(ulong));
95 if (w == CMD_DATA_SIZE_STR)
97 arg.ival = hextoul(s, NULL);
109 * memstr - Find the first substring in memory
110 * @s1: The string to be searched
111 * @s2: The string to search for
113 * Similar to and based on strstr(),
114 * but strings do not need to be NUL terminated.
116 static char *memstr(const char *s1, int l1, const char *s2, int l2)
123 if (!memcmp(s1, s2, l2))
131 * substitute() - Substitute part of one string with another
133 * This updates @string so that the first occurrence of @old is replaced with
136 * @string: String buffer containing string to update at the start
137 * @slen: Pointer to current string length, updated on success
138 * @ssize: Size of string buffer
139 * @old: Old string to find in the buffer (no terminator needed)
140 * @olen: Length of @old excluding terminator
141 * @new: New string to replace @old with
142 * @nlen: Length of @new excluding terminator
143 * Return: pointer to immediately after the copied @new in @string, or NULL if
144 * no replacement took place
146 static char *substitute(char *string, int *slen, int ssize,
147 const char *old, int olen, const char *new, int nlen)
149 char *p = memstr(string, *slen, old, olen);
154 debug("## Match at pos %ld: match len %d, subst len %d\n",
155 (long)(p - string), olen, nlen);
157 /* make sure replacement matches */
158 if (*slen + nlen - olen > ssize) {
159 printf("## error: substitution buffer overflow\n");
163 /* move tail if needed */
167 len = (olen > nlen) ? olen : nlen;
169 tail = ssize - (p + len - string);
171 debug("## tail len %d\n", tail);
173 memmove(p + nlen, p + olen, tail);
176 /* insert substitute */
177 memcpy(p, new, nlen);
179 *slen += nlen - olen;
184 int setexpr_regex_sub(char *data, uint data_size, char *nbuf, uint nbuf_size,
185 const char *r, const char *s, bool global)
189 int res, len, nlen, loop;
191 if (slre_compile(&slre, r) == 0) {
192 printf("Error compiling regex: %s\n", slre.err_str);
197 for (loop = 0;; loop++) {
198 struct cap caps[slre.num_caps + 2];
203 (void) memset(caps, 0, sizeof(caps));
205 res = slre_match(&slre, datap, len - (datap - data), caps);
207 debug("Result: %d\n", res);
209 for (i = 0; i <= slre.num_caps; i++) {
210 if (caps[i].len > 0) {
211 debug("Substring %d: [%.*s]\n", i,
212 caps[i].len, caps[i].ptr);
218 debug("%s: No match\n", data);
220 debug("## MATCH ## %s\n", data);
232 if (nlen + 1 >= nbuf_size) {
233 printf("## error: pattern buffer overflow: have %d, need %d\n",
234 nbuf_size, nlen + 1);
239 debug("## SUBST(1) ## %s\n", nbuf);
242 * Handle back references
244 * Support for \0 ... \9, where \0 is the
245 * whole matched pattern (similar to &).
247 * Implementation is a bit simpleminded as
248 * backrefs are substituted sequentially, one
249 * by one. This will lead to somewhat
250 * unexpected results if the replacement
251 * strings contain any \N strings then then
252 * may get substitued, too. We accept this
253 * restriction for the sake of simplicity.
255 for (i = 0; i < 10; ++i) {
261 if (caps[i].len == 0)
266 debug("## BACKREF %d: replace \"%.*s\" by \"%.*s\" in \"%s\"\n",
269 caps[i].len, caps[i].ptr,
273 char *p = memstr(np, nlen, backref, 2);
278 np = substitute(np, &nlen,
279 nbuf_size - (np - nbuf),
281 caps[i].ptr, caps[i].len);
287 debug("## SUBST(2) ## %s\n", nbuf);
289 datap = substitute(datap, &len, data_size - (datap - data),
290 old, olen, nbuf, nlen);
295 debug("## REMAINDER: %s\n", datap);
297 debug("## RESULT: %s\n", data);
302 debug("## FINAL (now env_set()) : %s\n", data);
307 #define SLRE_BUFSZ 16384
308 #define SLRE_PATSZ 4096
311 * Perform regex operations on a environment variable
313 * Returns 0 if OK, 1 in case of errors.
315 static int regex_sub_var(const char *name, const char *r, const char *s,
316 const char *t, int global)
319 char data[SLRE_BUFSZ];
320 char nbuf[SLRE_PATSZ];
328 if (slre_compile(&slre, r) == 0) {
329 printf("Error compiling regex: %s\n", slre.err_str);
334 value = env_get(name);
336 printf("## Error: variable \"%s\" not defined\n", name);
342 debug("REGEX on %s=%s\n", name, t);
343 debug("REGEX=\"%s\", SUBST=\"%s\", GLOBAL=%d\n", r, s ? s : "<NULL>",
347 if (len + 1 > SLRE_BUFSZ) {
348 printf("## error: subst buffer overflow: have %d, need %d\n",
349 SLRE_BUFSZ, len + 1);
355 ret = setexpr_regex_sub(data, SLRE_BUFSZ, nbuf, SLRE_PATSZ, r, s,
360 debug("%s=%s\n", name, data);
362 return env_set(name, data);
366 static int do_setexpr(struct cmd_tbl *cmdtp, int flag, int argc,
369 struct expr_arg aval, bval;
375 * We take 3, 5, or 6 arguments, except fmt operation, which
376 * takes 4 to 8 arguments (limited by _maxargs):
377 * 3 : setexpr name value
378 * 5 : setexpr name val1 op val2
379 * setexpr name [g]sub r s
380 * 6 : setexpr name [g]sub r s t
381 * setexpr name fmt format [val1] [val2] [val3] [val4]
385 return CMD_RET_USAGE;
387 w = cmd_get_data_size(argv[0], 4);
389 if (get_arg(argv[2], w, &aval))
390 return CMD_RET_FAILURE;
392 /* format string assignment: "setexpr name fmt %d value" */
393 if (strcmp(argv[2], "fmt") == 0 && IS_ENABLED(CONFIG_CMD_SETEXPR_FMT)) {
394 char str[MAX_STR_LEN];
398 return CMD_RET_USAGE;
400 result = printf_setexpr(str, sizeof(str), argc - 3, &argv[3]);
404 return env_set(argv[1], str);
407 if (argc == 4 || argc > 6)
408 return CMD_RET_USAGE;
410 /* plain assignment: "setexpr name value" */
412 if (w == CMD_DATA_SIZE_STR) {
413 ret = env_set(argv[1], aval.sval);
416 ret = env_set_hex(argv[1], aval.ival);
422 /* 5 or 6 args (6 args only with [g]sub) */
425 * rexep handling: "setexpr name [g]sub r s [t]"
426 * with 5 args, "t" will be NULL
428 if (strcmp(argv[2], "gsub") == 0)
429 return regex_sub_var(argv[1], argv[3], argv[4], argv[5], 1);
431 if (strcmp(argv[2], "sub") == 0)
432 return regex_sub_var(argv[1], argv[3], argv[4], argv[5], 0);
435 /* standard operators: "setexpr name val1 op val2" */
437 return CMD_RET_USAGE;
439 if (strlen(argv[3]) != 1)
440 return CMD_RET_USAGE;
442 if (get_arg(argv[4], w, &bval)) {
443 if (w == CMD_DATA_SIZE_STR)
445 return CMD_RET_FAILURE;
448 if (w == CMD_DATA_SIZE_STR) {
452 switch (argv[3][0]) {
454 len = strlen(aval.sval) + strlen(bval.sval) + 1;
457 printf("Out of memory\n");
458 ret = CMD_RET_FAILURE;
460 /* These were copied out and checked earlier */
461 strcpy(str, aval.sval);
462 strcat(str, bval.sval);
463 ret = env_set(argv[1], str);
465 printf("Could not set var\n");
470 printf("invalid op\n");
477 switch (argv[3][0]) {
503 printf("invalid op\n");
507 env_set_hex(argv[1], value);
510 if (w == CMD_DATA_SIZE_STR) {
519 setexpr, 8, 0, do_setexpr,
520 "set environment variable as the result of eval expression",
521 "[.b, .w, .l, .s] name [*]value1 <op> [*]value2\n"
522 " - set environment variable 'name' to the result of the evaluated\n"
523 " expression specified by <op>. <op> can be &, |, ^, +, -, *, /, %\n"
524 " (for strings only + is supported)\n"
525 " size argument is only meaningful if value1 and/or value2 are\n"
526 " memory addresses (*)\n"
527 "setexpr[.b, .w, .l] name [*]value\n"
528 " - load a value into a variable"
529 #ifdef CONFIG_CMD_SETEXPR_FMT
531 "setexpr name fmt <format> [value1] [value2] [value3] [value4]\n"
532 " - set environment variable 'name' to the result of the bash like\n"
533 " format string evaluation of value."
537 "setexpr name gsub r s [t]\n"
538 " - For each substring matching the regular expression <r> in the\n"
539 " string <t>, substitute the string <s>. The result is\n"
540 " assigned to <name>. If <t> is not supplied, use the old\n"
541 " value of <name>. If no substring matching <r> is found in <t>,\n"
542 " assign <t> to <name>.\n"
543 "setexpr name sub r s [t]\n"
544 " - Just like gsub(), but replace only the first matching substring"