Skip to content

Commit 3f77526

Browse files
psa_constant_names: adding support for signed types
psa_constant_names now works correctly with signed values, such as psa_status_t may have.
1 parent 1b87984 commit 3f77526

File tree

1 file changed

+41
-8
lines changed

1 file changed

+41
-8
lines changed

programs/psa/psa_constant_names.c

Lines changed: 41 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
#include <errno.h>
2+
#include <stdint.h>
13
#include <stdio.h>
24
#include <stdlib.h>
35
#include <string.h>
@@ -151,6 +153,40 @@ static void usage(const char *program_name)
151153

152154
typedef enum {
153155
TYPE_STATUS,
156+
} signed_value_type;
157+
158+
int process_signed(signed_value_type type, long min, long max, char **argp)
159+
{
160+
for (; *argp != NULL; argp++) {
161+
char buffer[200];
162+
char *end;
163+
long value = strtol(*argp, &end, 0);
164+
if (*end) {
165+
printf("Non-numeric value: %s\n", *argp);
166+
return EXIT_FAILURE;
167+
}
168+
if (value < min || (errno == ERANGE && value < 0)) {
169+
printf("Value too small: %s\n", *argp);
170+
return EXIT_FAILURE;
171+
}
172+
if (value > max || (errno == ERANGE && value > 0)) {
173+
printf("Value too large: %s\n", *argp);
174+
return EXIT_FAILURE;
175+
}
176+
177+
switch (type) {
178+
case TYPE_STATUS:
179+
psa_snprint_status(buffer, sizeof(buffer),
180+
(psa_status_t) value);
181+
break;
182+
}
183+
puts(buffer);
184+
}
185+
186+
return EXIT_SUCCESS;
187+
}
188+
189+
typedef enum {
154190
TYPE_ALGORITHM,
155191
TYPE_ECC_CURVE,
156192
TYPE_KEY_TYPE,
@@ -167,16 +203,12 @@ int process_unsigned(unsigned_value_type type, unsigned long max, char **argp)
167203
printf("Non-numeric value: %s\n", *argp);
168204
return EXIT_FAILURE;
169205
}
170-
if (value > max) {
206+
if (value > max || errno == ERANGE) {
171207
printf("Value out of range: %s\n", *argp);
172208
return EXIT_FAILURE;
173209
}
174210

175211
switch (type) {
176-
case TYPE_STATUS:
177-
psa_snprint_status(buffer, sizeof(buffer),
178-
(psa_status_t) value);
179-
break;
180212
case TYPE_ALGORITHM:
181213
psa_snprint_algorithm(buffer, sizeof(buffer),
182214
(psa_algorithm_t) value);
@@ -211,9 +243,10 @@ int main(int argc, char *argv[])
211243
}
212244

213245
if (!strcmp(argv[1], "error") || !strcmp(argv[1], "status")) {
214-
/* Wrong! psa_status_t is signed. */
215-
return process_unsigned(TYPE_ALGORITHM, 0xffffffff,
216-
argv + 2);
246+
/* There's no way to obtain the actual range of a signed type,
247+
* so hard-code it here: psa_status_t is int32_t. */
248+
return process_signed(TYPE_STATUS, INT32_MIN, INT32_MAX,
249+
argv + 2);
217250
} else if (!strcmp(argv[1], "alg") || !strcmp(argv[1], "algorithm")) {
218251
return process_unsigned(TYPE_ALGORITHM, (psa_algorithm_t) (-1),
219252
argv + 2);

0 commit comments

Comments
 (0)