simple-stream-checks.c revision 32133cfb333510ba94aff040067713c0b32d58c5
1// RUN: %clang_cc1 -analyze -analyzer-checker=core,alpha.unix.SimpleStream -verify %s
2
3typedef struct __sFILE {
4  unsigned char *_p;
5} FILE;
6FILE *fopen(const char * restrict, const char * restrict) __asm("_" "fopen" );
7int fputc(int, FILE *);
8int fputs(const char * restrict, FILE * restrict) __asm("_" "fputs" );
9int fclose(FILE *);
10void exit(int);
11
12void checkDoubleFClose(int *Data) {
13  FILE *F = fopen("myfile.txt", "w");
14  if (F != 0) {
15    fputs ("fopen example", F);
16    if (!Data)
17      fclose(F);
18    else
19      fputc(*Data, F);
20    fclose(F); // expected-warning {{Closing a previously closed file stream}}
21  }
22}
23
24int checkLeak(int *Data) {
25  FILE *F = fopen("myfile.txt", "w");
26  if (F != 0) {
27    fputs ("fopen example", F);
28  }
29
30  if (Data) // expected-warning {{Opened file is never closed; potential resource leak}}
31    return *Data;
32  else
33    return 0;
34}
35
36void checkLeakFollowedByAssert(int *Data) {
37  FILE *F = fopen("myfile.txt", "w");
38  if (F != 0) {
39    fputs ("fopen example", F);
40    if (!Data)
41      exit(0);
42    fclose(F);
43  }
44}
45
46void CloseOnlyOnValidFileHandle() {
47  FILE *F = fopen("myfile.txt", "w");
48  if (F)
49    fclose(F);
50  int x = 0; // no warning
51}
52