Fix underflow in path_remove_trailing()

This commit is contained in:
Rodrigo Arias 2023-03-13 17:38:29 +01:00 committed by Rodrigo Arias Mallo
parent 8da0342760
commit 6deef0308a
3 changed files with 37 additions and 1 deletions

View File

@ -96,7 +96,7 @@ void
path_remove_trailing(char *path)
{
int n = strlen(path);
for (int i = n - 1; path[i] == '/'; i--) {
for (int i = n - 1; i >= 0 && path[i] == '/'; i--) {
path[i] = '\0';
}
}

View File

@ -14,3 +14,4 @@ unit_test(stream.c)
unit_test(thread.c)
unit_test(value.c)
unit_test(version.c)
unit_test(path.c)

35
test/unit/path.c Normal file
View File

@ -0,0 +1,35 @@
/* Copyright (c) 2023 Barcelona Supercomputing Center (BSC)
* SPDX-License-Identifier: GPL-3.0-or-later */
#include "emu/path.h"
#include "common.h"
#include <string.h>
static void
test_underflow_trailing(void)
{
char in[] = { 'A', '/', '/', '/', '/', '\0', 'B' };
char out[] = { 'A', '/', '\0','\0','\0','\0', 'B' };
char *p = in + 2; /* ^here */
path_remove_trailing(p);
if (memcmp(in, out, sizeof(in)) != 0) {
for (size_t i = 0; i < sizeof(in); i++) {
err("i=%3d, in[i]=%02x out[i]=%02x\n", i,
(unsigned char) in[i],
(unsigned char) out[i]);
}
die("path mismatch");
}
err("OK\n");
}
int
main(void)
{
test_underflow_trailing();
return 0;
}