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