1 // SPDX-License-Identifier: GPL-2.0+
4 * Tait Electronics Limited, Christchurch, New Zealand
8 * This file provides a shell like 'test' function to return
9 * true/false from an integer or string compare of two memory
10 * locations or a location and a scalar/literal.
11 * A few parts were lifted from bash 'test' command
29 char *op
; /* operator string */
30 int opcode
; /* internal representation of opcode */
33 typedef struct op_tbl_s op_tbl_t
;
35 static const op_tbl_t op_table
[] = {
51 static long evalexp(char *s
, int w
)
57 /* if the parameter starts with a * then assume is a pointer to the value we want */
59 addr
= simple_strtoul(&s
[1], NULL
, 16);
60 buf
= map_physmem(addr
, w
, MAP_WRBACK
);
62 puts("Failed to map physical memory\n");
67 l
= (long)(*(u8
*)buf
);
70 l
= (long)(*(u16
*)buf
);
73 l
= (long)(*(u32
*)buf
);
76 unmap_physmem(buf
, w
);
79 l
= simple_strtoul(s
, NULL
, 16);
82 /* avoid overflow on mask calculus */
83 return (w
>= sizeof(long)) ? l
: (l
& ((1UL << (w
* 8)) - 1));
86 static char * evalstr(char *s
)
88 /* if the parameter starts with a * then assume a string pointer else its a literal */
90 return (char *)simple_strtoul(&s
[1], NULL
, 16);
91 } else if (s
[0] == '$') {
103 return env_get((const char *)&s
[2]);
109 static int stringcomp(char *s
, char *t
, int op
)
119 case EQ
: return (p
== 0);
120 case NE
: return (p
!= 0);
121 case LT
: return (p
< 0);
122 case GT
: return (p
> 0);
123 case LE
: return (p
<= 0);
124 case GE
: return (p
>= 0);
129 static int arithcomp (char *s
, char *t
, int op
, int w
)
137 case EQ
: return (l
== r
);
138 case NE
: return (l
!= r
);
139 case LT
: return (l
< r
);
140 case GT
: return (l
> r
);
141 case LE
: return (l
<= r
);
142 case GE
: return (l
>= r
);
147 static int binary_test(char *op
, char *arg1
, char *arg2
, int w
)
150 const op_tbl_t
*optp
;
154 for (optp
= (op_tbl_t
*)&op_table
, i
= 0;
155 i
< ARRAY_SIZE(op_table
);
158 if ((strncmp (op
, optp
->op
, len
) == 0) && (len
== strlen (optp
->op
))) {
160 return (stringcomp(arg1
, arg2
, optp
->opcode
));
162 return (arithcomp (arg1
, arg2
, optp
->opcode
, w
));
167 printf("Unknown operator '%s'\n", op
);
168 return 0; /* op code not found */
171 /* command line interface to the shell test */
172 static int do_itest(cmd_tbl_t
*cmdtp
, int flag
, int argc
, char * const argv
[])
176 /* Validate arguments */
178 return CMD_RET_USAGE
;
180 /* Check for a data width specification.
181 * Defaults to long (4) if no specification.
182 * Uses -2 as 'width' for .s (string) so as not to upset existing code
184 switch (w
= cmd_get_data_size(argv
[0], 4)) {
188 value
= binary_test (argv
[2], argv
[1], argv
[3], w
);
191 value
= binary_test (argv
[2], argv
[1], argv
[3], 0);
195 puts("Invalid data width specifier\n");
204 itest
, 4, 0, do_itest
,
205 "return true/false on integer compare",
206 "[.b, .w, .l, .s] [*]value1 <op> [*]value2"