[LTP] [PATCH v3 1/2] open: fix cleanup condition and use snprintf
Jinseok Kim
always.starving0@gmail.com
Thu Feb 19 15:15:17 CET 2026
The test uses sprintf() to build temporary file names, which may
overflow the fixed-size buffer. Replace it with snprintf() to avoid
potential buffer overflows.
The cleanup logic also checked '!first' to decide whether to close
file descriptors. Since file descriptor 0 is valid, this condition
can incorrectly skip cleanup and leak file descriptors.
To fix this:
- Initialize first = -1 to correctly detect uninitialized state
- Initialize fds array with -1 after malloc to avoid closing invalid fds
Signed-off-by: Jinseok Kim <always.starving0@gmail.com>
---
testcases/kernel/syscalls/open/open04.c | 10 ++++++----
1 file changed, 6 insertions(+), 4 deletions(-)
diff --git a/testcases/kernel/syscalls/open/open04.c b/testcases/kernel/syscalls/open/open04.c
index 3dc3486d3..152bec2d4 100644
--- a/testcases/kernel/syscalls/open/open04.c
+++ b/testcases/kernel/syscalls/open/open04.c
@@ -15,7 +15,8 @@
#define FNAME "open04"
-static int fds_limit, first, i;
+static int fds_limit, i;
+static int first = -1;
static int *fds;
static char fname[20];
@@ -27,10 +28,11 @@ static void setup(void)
first = SAFE_OPEN(FNAME, O_RDWR | O_CREAT, 0777);
fds = SAFE_MALLOC(sizeof(int) * (fds_limit - first));
+ memset(fds, -1, sizeof(int) * (fds_limit - first));
fds[0] = first;
for (i = first + 1; i < fds_limit; i++) {
- sprintf(fname, FNAME ".%d", i);
+ snprintf(fname, sizeof(fname), FNAME ".%d", i);
fd = open(fname, O_RDWR | O_CREAT, 0777);
if (fd == -1) {
if (errno != EMFILE)
@@ -44,13 +46,13 @@ static void setup(void)
static void run(void)
{
- sprintf(fname, FNAME ".%d", fds_limit);
+ snprintf(fname, sizeof(fname), FNAME ".%d", fds_limit);
TST_EXP_FAIL2(open(fname, O_RDWR | O_CREAT, 0777), EMFILE);
}
static void cleanup(void)
{
- if (!first || !fds)
+ if (first < 0 || !fds)
return;
for (i = first; i < fds_limit; i++)
--
2.43.0
More information about the ltp
mailing list