Skip to content

Commit

Permalink
utils: string: Add strbytes2mem_check() check strbytes2mem() params
Browse files Browse the repository at this point in the history
    ulpatch/build$ ./src/tests/ulpatch_test -f strbytes -v --lv dbg

Signed-off-by: Rong Tao <[email protected]>
  • Loading branch information
Rtoax committed Jan 9, 2025
1 parent b3dd557 commit 16a4008
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 2 deletions.
26 changes: 24 additions & 2 deletions src/tests/utils/string.c
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ TEST(Utils_str, strbytes2mem, 0)
uint8_t mem[128];
size_t n;
char seperator;
int expect_errno;
} values[] = {
{
.s = "0xff",
Expand Down Expand Up @@ -174,22 +175,43 @@ TEST(Utils_str, strbytes2mem, 0)
.n = 4,
.seperator = '+',
},
{
.s = "0xff,0x1,0x3,0x2",
.mem = {0xff,0x1,0x3,0x2},
.n = 0,
.seperator = ';', /* Bad string, return NULL */
.expect_errno = EINVAL,
},
};

ret = 0;

for (i = 0; i < ARRAY_SIZE(values); i++) {
nbytes = 0;

void *mem = strbytes2mem(values[i].s, &nbytes, buf, sizeof(buf),
values[i].seperator);

printf("%s : %ld (expect %ld)\n", values[i].s, nbytes, values[i].n);
#if defined(DEBUG)
fdisasm_arch(stdout, ">> ", 0, (unsigned char *)mem, nbytes);
#endif
if (memcmp(mem, values[i].mem, MAX(nbytes, values[i].n)))
if (nbytes != values[i].n) {
ret++;
continue;
}

/**
* errno equal to zero or EINVAL, and _MUST_ equal to
* expect_errno
*/
if (values[i].expect_errno != errno)
ret++;

if (!mem && errno != EINVAL)
ret++;

if (nbytes != values[i].n)
if (mem && memcmp(mem, values[i].mem, MAX(nbytes, values[i].n)))
ret++;
}

Expand Down
38 changes: 38 additions & 0 deletions src/utils/string.c
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,31 @@ int fmembytes(FILE *fp, const void *data, int data_len)
return 0;
}

static int strbytes2mem_check(const char *bytes, char seperator)
{
const char *s = bytes;

while (s && *s != '\0') {
#if defined(DEBUG)
ulp_debug("s %s %c %c\n", s, *s, seperator);
#endif
switch (*s) {
case '0' ... '9':
case 'a' ... 'f':
case 'A' ... 'F':
case 'x':
break;
default:
if (*s == seperator)
break;
errno = EINVAL;
return -EINVAL;
}
s++;
}
return 0;
}

/**
* convert string to memory bytes, split with ','.
*
Expand All @@ -110,13 +135,26 @@ int fmembytes(FILE *fp, const void *data, int data_len)
void *strbytes2mem(const char *bytes, size_t *nbytes, void *buf, size_t buf_len,
char seperator)
{
int err;
size_t n = 0;
uint8_t *u = buf;
char sep = ',', str_sep[2];

errno = 0;

if (seperator)
sep = seperator;

/* "0xff" -> 0xff -> size of 1 */
if (!buf || buf_len < 1) {
errno = EINVAL;
return NULL;
}

err = strbytes2mem_check(bytes, sep);
if (err)
return NULL;

sprintf(str_sep, "%c", sep);

const char *s = bytes;
Expand Down

0 comments on commit 16a4008

Please sign in to comment.