1 int open(const char *, int mode);
2 void close(int fd);
3 #define O_RDONLY 0
4 #define O_WRONLY 1
5 #define O_RDWR 2
6 #define STDIN 0
7
8 typedef enum {
9 S_IRWXU
10 // etc
11 } mode_t;
12
13 int creat (const char *, mode_t mode);
14
15 void
16 test_1 (const char *path)
17 {
18 int fd = open (path, O_RDWR); /* { dg-message "\\(1\\) opened here" } */
19 close (fd); /* { dg-message "\\(2\\) first 'close' here" "event1" } */
20 close (fd); /* { dg-warning "double 'close' of file descriptor 'fd' \\\[CWE-1341\\\]" "warning" } */
21 /* { dg-message "\\(3\\) second 'close' here; first 'close' was at \\(2\\)" "event2" { target *-*-* } .-1 } */
22 }
23
24 void
25 test_2 (const char *path)
26 {
27 int fd = open (path, O_RDWR); /* { dg-message "\\(1\\) opened here" } */
28 if (fd < 0) /* { dg-message "\\(2\\) assuming 'fd' is a valid file descriptor \\(>= 0\\)" "event1" } */
29 /* { dg-message "\\(3\\) following 'false' branch \\(when 'fd >= 0'\\)..." "event2" { target *-*-* } .-1 } */
30 return;
31 close (fd); /* { dg-message "\\(4\\) ...to here" "event1" } */
32 /* { dg-message "\\(5\\) first 'close' here" "event2" { target *-*-* } .-1 } */
33 close (fd); /* { dg-warning "double 'close' of file descriptor 'fd' \\\[CWE-1341\\\]" "warning" } */
34 /* {dg-message "\\(6\\) second 'close' here; first was at \\(5\\)" "" { target *-*-* } .-1 } */
35 }
36
37 void
38 test_3 ()
39 {
40 /* FD 0 is stdin at the entry to "main" and thus read-only, but we have no
41 guarantees here that it hasn't been closed and then reopened for
42 writing, so we can't issue a warning */
43
44 int fd = STDIN;
45 close(fd); /* { dg-message "\\(1\\) first 'close' here" } */
46 close(fd); /* { dg-warning "double 'close' of file descriptor 'fd' \\\[CWE-1341\\\]" "warning" } */
47 /* { dg-message "\\(2\\) second 'close' here; first 'close' was at \\(1\\)" "event2" { target *-*-* } .-1 } */
48 }
49
50 void
51 test_4 ()
52 {
53 int fd = -1;
54 close(fd);
55 close(fd);
56 }
57
58 void
59 test_5 (const char *path, mode_t mode)
60 {
61 int fd = creat (path, mode);
62 close(fd);
63 close(fd); /* { dg-warning "double 'close' of file descriptor 'fd' \\\[CWE-1341\\\]" "warning" } */
64 }