From 37cb5686de05f8989dc1080ebc70b319fbc65cdd Mon Sep 17 00:00:00 2001 From: Simon Ruderich Date: Thu, 13 Jun 2013 21:19:15 +0200 Subject: [PATCH] Handle invalid arguments to close()/fclose() better. --- src/coloredstderr.c | 10 ++++++++-- tests/example.c | 8 ++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/coloredstderr.c b/src/coloredstderr.c index db6cb27..b7e71e1 100644 --- a/src/coloredstderr.c +++ b/src/coloredstderr.c @@ -396,14 +396,20 @@ static int (*real_close)(int); int close(int fd) { DLSYM_FUNCTION(real_close, "close"); - close_fd(fd); + if (fd >= 0) { + close_fd(fd); + } return real_close(fd); } static int (*real_fclose)(FILE *); int fclose(FILE *fp) { + int fd; + DLSYM_FUNCTION(real_fclose, "fclose"); - close_fd(fileno(fp)); + if (fp != NULL && (fd = fileno(fp)) >= 0) { + close_fd(fd); + } return real_fclose(fp); } diff --git a/tests/example.c b/tests/example.c index 0fee973..b1d42e3 100644 --- a/tests/example.c +++ b/tests/example.c @@ -56,5 +56,13 @@ int main(int argc, char **argv unused) { putc_unlocked('x', stderr); putc_unlocked('\n', stdout); + /* Test invalid stuff. */ + close(-42); + close(-4711); + /* Can't test this, results in a segfault with the "normal" fclose(). */ + /*fclose(NULL);*/ + dup(-12); + dup2(12, -42); + return EXIT_SUCCESS; } -- 2.43.2