This is the mail archive of the glibc-bugs@sourceware.org mailing list for the glibc project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

[Bug stdio/21398] New: freopen does not check dup3 return value, and does not return error if dup3 fails (seen when open returns fd 0, and freopen on stdin)


https://sourceware.org/bugzilla/show_bug.cgi?id=21398

            Bug ID: 21398
           Summary: freopen does not check dup3 return value, and does not
                    return error if dup3 fails (seen when open returns fd
                    0, and freopen on stdin)
           Product: glibc
           Version: 2.25
            Status: UNCONFIRMED
          Severity: normal
          Priority: P2
         Component: stdio
          Assignee: unassigned at sourceware dot org
          Reporter: olson at cumulusnetworks dot com
  Target Milestone: ---

When fd 0 is closed, and the fopen in freopen gets fd 0, and dup3 is available,
the dup3(0,0,0) correctly fails with EINVAL, the return status is ignored, and
fd 0 is closed.  Subsequent attempts to use stdin fail.

This was observed in debian jessie with glibc 2.19, but by code inspection on
glibc top of trunk in git, the bug is still present.

Here is a simple test program to show the problem:

#include <stdio.h>
#include <unistd.h>

int main(int cnt, char **args)
{
    FILE *newf;
    char buf[128], *ret;
    if(cnt != 2) {
        fprintf(stderr, "Usage: %s filename_to_freopen\n", *args);
        return 1;
    }
    (void)close(0);
    newf = freopen(args[1], "r", stdin);
    fprintf(stdout, "freopen(%s, r, stdin) returns %p\n", args[1], newf);
    fflush(stdout);
    fprintf(stdout, "ferror(%p) returns %d\n", args[1], ferror(newf));
    ret = fgets(buf, sizeof buf, stdin);
    fprintf(stdout, "fgets(%p) returns %p\n", newf, ret);
    fprintf(stdout, "2nd ferror(%p) returns %d\n", args[1], ferror(newf));
    return 0;
}

With gcc 4.9, it compiles -Wall with no warnings (on a 64bit x86_64 system, but
by inspection, the 32 bit freopen.c has the same bug):

Running it on an existing file (the source for the above program):
./fbug freopen_bug.c 
freopen(freopen_bug.c, r, stdin) returns 0x7f0fdada14e0
ferror(0x7ffdaa94ad1a) returns 0
fgets(0x7f0fdada14e0) returns (nil)
2nd ferror(0x7ffdaa94ad1a) returns 1

And strace shows the issue:


16:10:40 close(0)                       = 0
16:10:40 open("freopen_bug.c", O_RDONLY) = 0
16:10:40 dup3(0, 0, 0)                  = -1 EINVAL (Invalid argument)
16:10:40 close(0)                       = 0

(no other system calls in between)

-- 
You are receiving this mail because:
You are on the CC list for the bug.

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]