1 // RUN: %clang_analyze_cc1 -Wno-strict-prototypes -analyzer-store=region -verify %s \
2 // RUN: -analyzer-checker=core \
3 // RUN: -analyzer-checker=alpha.deadcode.UnreachableCode \
4 // RUN: -analyzer-checker=alpha.core.CastSize \
5 // RUN: -analyzer-checker=unix \
6 // RUN: -analyzer-checker=debug.ExprInspection
8 #include "Inputs/system-header-simulator.h"
10 void clang_analyzer_eval(int);
11 void clang_analyzer_dump(int);
12 void clang_analyzer_dumpExtent(void *);
14 // Without -fms-compatibility, wchar_t isn't a builtin type. MSVC defines
15 // _WCHAR_T_DEFINED if wchar_t is available. Microsoft recommends that you use
16 // the builtin type: "Using the typedef version can cause portability
17 // problems", but we're ok here because we're not actually running anything.
18 // Also of note is this cryptic warning: "The wchar_t type is not supported
19 // when you compile C code".
21 // See the docs for more:
22 // https://msdn.microsoft.com/en-us/library/dh8che7s.aspx
23 #if !defined(_WCHAR_T_DEFINED)
24 // "Microsoft implements wchar_t as a two-byte unsigned value"
25 typedef unsigned short wchar_t;
26 #define _WCHAR_T_DEFINED
27 #endif // !defined(_WCHAR_T_DEFINED)
29 typedef __typeof(sizeof(int)) size_t;
34 void *realloc(void *ptr
, size_t size
);
35 void *reallocf(void *ptr
, size_t size
);
36 void *calloc(size_t nmemb
, size_t size
);
37 char *strdup(const char *s
);
38 wchar_t *wcsdup(const wchar_t *s
);
39 char *strndup(const char *s
, size_t n
);
40 int memcmp(const void *s1
, const void *s2
, size_t n
);
43 char *_strdup(const char *strSource
);
44 wchar_t *_wcsdup(const wchar_t *strSource
);
45 void *_alloca(size_t size
);
49 char *fooRetPtr(void);
53 return; // expected-warning{{Potential leak of memory pointed to by 'p'}}
59 free(p
); // expected-warning{{Attempt to free released memory}}
62 void f2_realloc_0(void) {
65 realloc(p
,0); // expected-warning{{Attempt to free released memory}}
68 void f2_realloc_1(void) {
70 int *q
= realloc(p
,0); // no-warning
73 void reallocNotNullPtr(unsigned sizeIn
) {
75 char *p
= (char*)malloc(size
);
77 char *q
= (char*)realloc(p
, sizeIn
);
78 char x
= *q
; // expected-warning {{Potential leak of memory pointed to by 'q'}}
82 void allocaTest(void) {
83 int *p
= alloca(sizeof(int));
86 void winAllocaTest(void) {
87 int *p
= _alloca(sizeof(int));
90 void allocaBuiltinTest(void) {
91 int *p
= __builtin_alloca(sizeof(int));
94 int *realloctest1(void) {
97 return q
; // no warning - returning the allocated value
100 // p should be freed if realloc fails.
101 void reallocFails(void) {
102 char *p
= malloc(12);
103 char *r
= realloc(p
, 12+1);
111 void reallocSizeZero1(void) {
112 char *p
= malloc(12);
113 char *r
= realloc(p
, 0);
115 free(p
); // expected-warning {{Attempt to free released memory}}
121 void reallocSizeZero2(void) {
122 char *p
= malloc(12);
123 char *r
= realloc(p
, 0);
125 free(p
); // expected-warning {{Attempt to free released memory}}
129 free(p
); // expected-warning {{Attempt to free released memory}}
132 void reallocSizeZero3(void) {
133 char *p
= malloc(12);
134 char *r
= realloc(p
, 0);
138 void reallocSizeZero4(void) {
139 char *r
= realloc(0, 0);
143 void reallocSizeZero5(void) {
144 char *r
= realloc(0, 0);
147 void reallocPtrZero1(void) {
148 char *r
= realloc(0, 12);
149 } // expected-warning {{Potential leak of memory pointed to by 'r'}}
151 void reallocPtrZero2(void) {
152 char *r
= realloc(0, 12);
157 void reallocPtrZero3(void) {
158 char *r
= realloc(0, 12);
162 void reallocRadar6337483_1(void) {
163 char *buf
= malloc(100);
164 buf
= (char*)realloc(buf
, 0x1000000);
166 return;// expected-warning {{Potential leak of memory pointed to by}}
171 void reallocRadar6337483_2(void) {
172 char *buf
= malloc(100);
173 char *buf2
= (char*)realloc(buf
, 0x1000000);
179 } // expected-warning {{Potential leak of memory pointed to by}}
181 void reallocRadar6337483_3(void) {
182 char * buf
= malloc(100);
184 tmp
= (char*)realloc(buf
, 0x1000000);
193 void reallocRadar6337483_4(void) {
194 char *buf
= malloc(100);
195 char *buf2
= (char*)realloc(buf
, 0x1000000);
197 return; // expected-warning {{Potential leak of memory pointed to by}}
203 int *reallocfTest1(void) {
206 return q
; // no warning - returning the allocated value
209 void reallocfRadar6337483_4(void) {
210 char *buf
= malloc(100);
211 char *buf2
= (char*)reallocf(buf
, 0x1000000);
213 return; // no warning - reallocf frees even on failure
219 void reallocfRadar6337483_3(void) {
220 char * buf
= malloc(100);
222 tmp
= (char*)reallocf(buf
, 0x1000000);
224 free(buf
); // expected-warning {{Attempt to free released memory}}
231 void reallocfPtrZero1(void) {
232 char *r
= reallocf(0, 12);
233 } // expected-warning {{Potential leak of memory pointed to by}}
235 //------------------- Check usage of zero-allocated memory ---------------------
236 void CheckUseZeroAllocatedNoWarn1(void) {
238 free(p
); // no warning
241 void CheckUseZeroAllocatedNoWarn2(void) {
242 int *p
= alloca(0); // no warning
245 void CheckUseZeroWinAllocatedNoWarn2(void) {
246 int *p
= _alloca(0); // no warning
250 void CheckUseZeroAllocatedNoWarn3(void) {
252 int *q
= realloc(p
, 8); // no warning
256 void CheckUseZeroAllocatedNoWarn4(void) {
257 int *p
= realloc(0, 8);
258 *p
= 1; // no warning
262 void CheckUseZeroAllocated1(void) {
264 *p
= 1; // expected-warning {{Use of memory allocated with size zero}}
268 char CheckUseZeroAllocated2(void) {
270 return *p
; // expected-warning {{Use of memory allocated with size zero}}
273 char CheckUseZeroWinAllocated2(void) {
274 char *p
= _alloca(0);
275 return *p
; // expected-warning {{Use of memory allocated with size zero}}
278 void UseZeroAllocated(int *p
) {
280 *p
= 7; // expected-warning {{Use of memory allocated with size zero}}
282 void CheckUseZeroAllocated3(void) {
288 void CheckUseZeroAllocated4(void) {
290 f(*p
); // expected-warning {{Use of memory allocated with size zero}}
294 void CheckUseZeroAllocated5(void) {
295 int *p
= calloc(0, 2);
296 *p
= 1; // expected-warning {{Use of memory allocated with size zero}}
300 void CheckUseZeroAllocated6(void) {
301 int *p
= calloc(2, 0);
302 *p
= 1; // expected-warning {{Use of memory allocated with size zero}}
306 void CheckUseZeroAllocated7(void) {
307 int *p
= realloc(0, 0);
308 *p
= 1; // expected-warning {{Use of memory allocated with size zero}}
312 void CheckUseZeroAllocated8(void) {
314 int *q
= realloc(p
, 0);
315 *q
= 1; // expected-warning {{Use of memory allocated with size zero}}
319 void CheckUseZeroAllocated9(void) {
320 int *p
= realloc(0, 0);
321 int *q
= realloc(p
, 0);
322 *q
= 1; // expected-warning {{Use of memory allocated with size zero}}
326 void CheckUseZeroAllocatedPathNoWarn(_Bool b
) {
334 *p
= 1; // no warning
339 void CheckUseZeroAllocatedPathWarn(_Bool b
) {
347 *p
= 1; // expected-warning {{Use of memory allocated with size zero}}
352 void CheckUseZeroReallocatedPathNoWarn(_Bool b
) {
358 char *q
= realloc(p
, s
);
361 *q
= 1; // no warning
366 void CheckUseZeroReallocatedPathWarn(_Bool b
) {
372 char *q
= realloc(p
, s
);
375 *q
= 1; // expected-warning {{Use of memory allocated with size zero}}
380 // This case tests that storing malloc'ed memory to a static variable which is
381 // then returned is not leaked. In the absence of known contracts for functions
382 // or inter-procedural analysis, this is a conservative answer.
386 return p
; // no-warning
389 // This case tests that storing malloc'ed memory to a static global variable
390 // which is then returned is not leaked. In the absence of known contracts for
391 // functions or inter-procedural analysis, this is a conservative answer.
392 static int *p_f4
= 0;
395 return p_f4
; // no-warning
401 return q
; // no-warning
407 return; // no-warning
412 void f6_realloc(void) {
415 return; // no-warning
432 char *x
= (char*) malloc(4);
434 x
[0] = 'a'; // expected-warning{{Use of memory after it is freed}}
438 char *x
= (char*) malloc(4);
440 char *y
= strndup(x
, 4); // expected-warning{{Use of memory after it is freed}}
443 void f7_realloc(void) {
444 char *x
= (char*) malloc(4);
446 x
[0] = 'a'; // expected-warning{{Use of memory after it is freed}}
450 int *x
= malloc(11); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
454 int *buf
= malloc(2); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
455 buf
[1] = 'c'; // not crash
458 void cast_emtpy_struct(void) {
462 struct st
*s
= malloc(sizeof(struct st
)); // no-warning
466 void cast_struct_1(void) {
472 struct st
*s
= malloc(sizeof(struct st
)); // no-warning
476 void cast_struct_2(void) {
482 struct st
*s
= malloc(sizeof(struct st
)); // no-warning
486 void cast_struct_3(void) {
492 struct st
*s
= malloc(sizeof(struct st
)); // no-warning
496 void cast_struct_4(void) {
502 struct st
*s
= malloc(sizeof(struct st
)); // no-warning
506 void cast_struct_5(void) {
512 struct st
*s
= malloc(sizeof(struct st
) - sizeof(char)); // no-warning
516 void cast_struct_warn_1(void) {
522 struct st
*s
= malloc(sizeof(struct st
) + 2); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
526 void cast_struct_warn_2(void) {
532 struct st
*s
= malloc(2); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
536 void cast_struct_flex_array_1(void) {
542 struct st
*s
= malloc(sizeof(struct st
) + 3); // no-warning
546 void cast_struct_flex_array_2(void) {
552 struct st
*s
= malloc(sizeof(struct st
) + 3); // no-warning
556 void cast_struct_flex_array_3(void) {
562 struct st
*s
= malloc(sizeof(struct st
) + 3); // no-warning
566 void cast_struct_flex_array_4(void) {
575 struct st
*s
= malloc(sizeof(struct st
) + 3 * sizeof(struct foo
)); // no-warning
579 void cast_struct_flex_array_5(void) {
588 struct st
*s
= malloc(sizeof(struct st
) + 3 * sizeof(struct foo
)); // no-warning
592 void cast_struct_flex_array_6(void) {
601 struct st
*s
= malloc(sizeof(struct st
) + 3 * sizeof(struct foo
)); // no-warning
605 void cast_struct_flex_array_warn_1(void) {
614 struct st
*s
= malloc(3 * sizeof(struct st
) + 3 * sizeof(struct foo
)); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
618 void cast_struct_flex_array_warn_2(void) {
627 struct st
*s
= malloc(3 * sizeof(struct st
) + 3 * sizeof(struct foo
)); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
631 void cast_struct_flex_array_warn_3(void) {
640 struct st
*s
= malloc(3 * sizeof(struct st
) + 3 * sizeof(struct foo
)); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
644 void cast_struct_flex_array_warn_4(void) {
650 struct st
*s
= malloc(sizeof(struct st
) + 3); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
654 void cast_struct_flex_array_warn_5(void) {
660 struct st
*s
= malloc(sizeof(struct st
) + 3); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
664 void cast_struct_flex_array_warn_6(void) {
670 struct st
*s
= malloc(sizeof(struct st
) + 3); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
674 void mallocCastToVoid(void) {
676 const void *cp
= p
; // not crash
680 void mallocCastToFP(void) {
682 void (*fp
)(void) = p
; // not crash
686 // This tests that malloc() buffers are undefined by default
687 char mallocGarbage (void) {
688 char *buf
= malloc(2);
689 char result
= buf
[1]; // expected-warning{{undefined}}
694 // This tests that calloc() buffers need to be freed
695 void callocNoFree (void) {
696 char *buf
= calloc(2,2);
697 return; // expected-warning{{Potential leak of memory pointed to by 'buf'}}
700 // These test that calloc() buffers are zeroed by default
701 char callocZeroesGood (void) {
702 char *buf
= calloc(2,2);
703 char result
= buf
[3]; // no-warning
707 return result
; // no-warning
710 char callocZeroesBad (void) {
711 char *buf
= calloc(2,2);
712 char result
= buf
[3]; // no-warning
714 free(buf
); // expected-warning{{never executed}}
716 return result
; // expected-warning{{Potential leak of memory pointed to by 'buf'}}
719 void nullFree(void) {
721 free(p
); // no warning - a nop
724 void paramFree(int *p
) {
726 free(p
); // no warning
727 myfoo(p
); // expected-warning {{Use of memory after it is freed}}
730 int* mallocEscapeRet(void) {
732 return p
; // no warning
735 void mallocEscapeFoo(void) {
738 return; // no warning
741 void mallocEscapeFree(void) {
747 void mallocEscapeFreeFree(void) {
751 free(p
); // expected-warning{{Attempt to free released memory}}
754 void mallocEscapeFreeUse(void) {
758 myfoo(p
); // expected-warning{{Use of memory after it is freed}}
762 void myalloc2(int **p
);
764 void mallocEscapeFreeCustomAlloc(void) {
769 free(p
); // no warning
772 void mallocEscapeFreeCustomAlloc2(void) {
777 free(p
); // no warning
780 void mallocBindFreeUse(void) {
784 myfoo(x
); // expected-warning{{Use of memory after it is freed}}
787 void mallocEscapeMalloc(void) {
791 } // expected-warning{{Potential leak of memory pointed to by}}
793 void mallocMalloc(void) {
796 } // expected-warning {{Potential leak of memory pointed to by}}\
797 // expected-warning {{Potential leak of memory pointed to by}}
799 void mallocFreeMalloc(void) {
806 void mallocFreeUse_params(void) {
809 myfoo(p
); //expected-warning{{Use of memory after it is freed}}
812 void mallocFreeUse_params2(void) {
815 myfooint(*p
); //expected-warning{{Use of memory after it is freed}}
818 void mallocFailedOrNot(void) {
826 struct StructWithInt
{
830 int *mallocReturnFreed(void) {
833 return p
; // expected-warning {{Use of memory after it is freed}}
836 int useAfterFreeStruct(void) {
837 struct StructWithInt
*px
= malloc(sizeof(struct StructWithInt
));
840 return px
->g
; // expected-warning {{Use of memory after it is freed}}
843 void nonSymbolAsFirstArg(int *pp
, struct StructWithInt
*p
);
845 void mallocEscapeFooNonSymbolArg(void) {
846 struct StructWithInt
*p
= malloc(sizeof(struct StructWithInt
));
847 nonSymbolAsFirstArg(&p
->g
, p
);
848 return; // no warning
851 void mallocFailedOrNotLeak(void) {
854 return; // no warning
856 return; // expected-warning {{Potential leak of memory pointed to by}}
859 void mallocAssignment(void) {
860 char *p
= malloc(12);
862 } // expected-warning {{leak}}
864 int vallocTest(void) {
865 char *mem
= valloc(12);
866 return 0; // expected-warning {{Potential leak of memory pointed to by}}
869 void vallocEscapeFreeUse(void) {
873 myfoo(p
); // expected-warning{{Use of memory after it is freed}}
881 struct GlStTy GlS
= {0};
883 void GlobalFree(void) {
887 void GlobalMalloc(void) {
891 void GlobalStructMalloc(void) {
896 void GlobalStructMallocFree(void) {
904 void globalArrayTest(void) {
905 char *p
= (char*)malloc(12);
909 // Make sure that we properly handle a pointer stored into a local struct/array.
910 typedef struct _StructWithPtr
{
914 static StructWithPtr arrOfStructs
[10];
916 void testMalloc(void) {
920 arrOfStructs
[0] = St
; // no-warning
923 StructWithPtr
testMalloc2(void) {
927 return St
; // no-warning
930 int *testMalloc3(void) {
933 return y
; // no-warning
936 void testStructLeak(void) {
938 St
.memP
= malloc(12);
939 return; // expected-warning {{Potential leak of memory pointed to by 'St.memP'}}
942 void testElemRegion1(void) {
943 char *x
= (void*)malloc(2);
948 void testElemRegion2(int **pp
) {
954 void testElemRegion3(int **pp
) {
959 // Region escape testing.
961 unsigned takePtrToPtr(int **p
);
962 void PassTheAddrOfAllocatedData(int f
) {
964 // We don't know what happens after the call. Should stop tracking here.
965 if (takePtrToPtr(&p
))
967 free(p
); // no warning
973 unsigned takePtrToStruct(struct X
*s
);
974 int ** foo2(int *g
, int f
) {
976 struct X
*px
= malloc(sizeof(struct X
));
978 // We don't know what happens after this call. Should not track px nor p.
979 if (takePtrToStruct(px
))
985 struct X
* RegInvalidationDetect1(struct X
*s2
) {
986 struct X
*px
= malloc(sizeof(struct X
));
989 return px
; // expected-warning {{Potential leak of memory pointed to by}}
992 struct X
* RegInvalidationGiveUp1(void) {
994 struct X
*px
= malloc(sizeof(struct X
));
999 int **RegInvalidationDetect2(int **pp
) {
1000 int *p
= malloc(12);
1003 return 0;// expected-warning {{Potential leak of memory pointed to by}}
1006 extern void exit(int) __attribute__ ((__noreturn__
));
1007 void mallocExit(int *g
) {
1008 struct xx
*p
= malloc(12);
1015 extern void __assert_fail (__const
char *__assertion
, __const
char *__file
,
1016 unsigned int __line
, __const
char *__function
)
1017 __attribute__ ((__noreturn__
));
1018 #define assert(expr) \
1019 ((expr) ? (void)(0) : __assert_fail (#expr, __FILE__, __LINE__, __func__))
1020 void mallocAssert(int *g
) {
1021 struct xx
*p
= malloc(12);
1028 void doNotInvalidateWhenPassedToSystemCalls(char *s
) {
1029 char *p
= malloc(12);
1037 } // expected-warning {{leak}}
1039 // Treat source buffer contents as escaped.
1040 void escapeSourceContents(char *s
) {
1041 char *p
= malloc(12);
1042 memcpy(s
, &p
, 12); // no warning
1044 void *p1
= malloc(7);
1046 memcpy(&a
, &p1
, sizeof a
);
1047 // FIXME: No warning due to limitations imposed by current modelling of
1048 // 'memcpy' (regions metadata is not copied).
1051 int *allocated
= (int *)malloc(4);
1052 memcpy(&ptrs
[0], &allocated
, sizeof(int *));
1053 // FIXME: No warning due to limitations imposed by current modelling of
1054 // 'memcpy' (regions metadata is not copied).
1057 void invalidateDestinationContents(void) {
1059 int *p
= (int *)malloc(4);
1060 memcpy(&p
, &null
, sizeof(int *));
1062 int *ptrs1
[2]; // expected-warning {{Potential leak of memory pointed to by}}
1063 ptrs1
[0] = (int *)malloc(4);
1064 memcpy(ptrs1
, &null
, sizeof(int *));
1066 int *ptrs2
[2]; // expected-warning {{Potential memory leak}}
1067 ptrs2
[0] = (int *)malloc(4);
1068 memcpy(&ptrs2
[1], &null
, sizeof(int *));
1070 int *ptrs3
[2]; // expected-warning {{Potential memory leak}}
1071 ptrs3
[0] = (int *)malloc(4);
1072 memcpy(&ptrs3
[0], &null
, sizeof(int *));
1073 } // expected-warning {{Potential memory leak}}
1075 // Rely on the CString checker evaluation of the strcpy API to convey that the result of strcpy is equal to p.
1076 void symbolLostWithStrcpy(char *s
) {
1077 char *p
= malloc(12);
1083 // The same test as the one above, but with what is actually generated on a mac.
1084 static __inline
char *
1085 __inline_strcpy_chk (char *restrict __dest
, const char *restrict __src
)
1087 return __builtin___strcpy_chk (__dest
, __src
, __builtin_object_size (__dest
, 2 > 1));
1090 void symbolLostWithStrcpy_InlineStrcpyVersion(char *s
) {
1091 char *p
= malloc(12);
1092 p
= ((__builtin_object_size (p
, 0) != (size_t) -1) ? __builtin___strcpy_chk (p
, s
, __builtin_object_size (p
, 2 > 1)) : __inline_strcpy_chk (p
, s
));
1096 // Here we are returning a pointer one past the allocated value. An idiom which
1097 // can be used for implementing special malloc. The correct uses of this might
1098 // be rare enough so that we could keep this as a warning.
1099 static void *specialMalloc(int n
){
1109 // Potentially, the user could free the struct by performing pointer arithmetic on the return value.
1110 // This is a variation of the specialMalloc issue, though probably would be more rare in correct code.
1111 int *specialMallocWithStruct(void) {
1112 struct StructWithInt
*px
= malloc(sizeof(struct StructWithInt
));
1116 // Test various allocation/deallocation functions.
1117 void testStrdup(const char *s
, unsigned validIndex
) {
1118 char *s2
= strdup(s
);
1119 s2
[validIndex
+ 1] = 'b';
1120 } // expected-warning {{Potential leak of memory pointed to by}}
1122 void testWinStrdup(const char *s
, unsigned validIndex
) {
1123 char *s2
= _strdup(s
);
1124 s2
[validIndex
+ 1] = 'b';
1125 } // expected-warning {{Potential leak of memory pointed to by}}
1127 void testWcsdup(const wchar_t *s
, unsigned validIndex
) {
1128 wchar_t *s2
= wcsdup(s
);
1129 s2
[validIndex
+ 1] = 'b';
1130 } // expected-warning {{Potential leak of memory pointed to by}}
1132 void testWinWcsdup(const wchar_t *s
, unsigned validIndex
) {
1133 wchar_t *s2
= _wcsdup(s
);
1134 s2
[validIndex
+ 1] = 'b';
1135 } // expected-warning {{Potential leak of memory pointed to by}}
1137 int testStrndup(const char *s
, unsigned validIndex
, unsigned size
) {
1138 char *s2
= strndup(s
, size
);
1139 s2
[validIndex
+ 1] = 'b';
1140 if (s2
[validIndex
] != 'a')
1143 return 1;// expected-warning {{Potential leak of memory pointed to by}}
1146 void testStrdupContentIsDefined(const char *s
, unsigned validIndex
) {
1147 char *s2
= strdup(s
);
1148 char result
= s2
[1];// no warning
1152 void testWinStrdupContentIsDefined(const char *s
, unsigned validIndex
) {
1153 char *s2
= _strdup(s
);
1154 char result
= s2
[1];// no warning
1158 void testWcsdupContentIsDefined(const wchar_t *s
, unsigned validIndex
) {
1159 wchar_t *s2
= wcsdup(s
);
1160 wchar_t result
= s2
[1];// no warning
1164 void testWinWcsdupContentIsDefined(const wchar_t *s
, unsigned validIndex
) {
1165 wchar_t *s2
= _wcsdup(s
);
1166 wchar_t result
= s2
[1];// no warning
1170 // ----------------------------------------------------------------------------
1171 // Test the system library functions to which the pointer can escape.
1172 // This tests false positive suppression.
1174 // For now, we assume memory passed to pthread_specific escapes.
1175 // TODO: We could check that if a new pthread binding is set, the existing
1176 // binding must be freed; otherwise, a memory leak can occur.
1177 void testPthereadSpecificEscape(pthread_key_t key
) {
1178 void *buf
= malloc(12);
1179 pthread_setspecific(key
, buf
); // no warning
1182 // PR12101: Test funopen().
1183 static int releasePtr(void *_ctx
) {
1187 FILE *useFunOpen(void) {
1188 void *ctx
= malloc(sizeof(int));
1189 FILE *f
= funopen(ctx
, 0, 0, 0, releasePtr
); // no warning
1195 FILE *useFunOpenNoReleaseFunction(void) {
1196 void *ctx
= malloc(sizeof(int));
1197 FILE *f
= funopen(ctx
, 0, 0, 0, 0);
1201 return f
; // expected-warning{{leak}}
1204 static int readNothing(void *_ctx
, char *buf
, int size
) {
1207 FILE *useFunOpenReadNoRelease(void) {
1208 void *ctx
= malloc(sizeof(int));
1209 FILE *f
= funopen(ctx
, readNothing
, 0, 0, 0);
1213 return f
; // expected-warning{{leak}}
1216 // Test setbuf, setvbuf.
1217 int my_main_no_warning(void) {
1218 char *p
= malloc(100);
1219 setvbuf(stdout
, p
, 0, 100);
1222 int my_main_no_warning2(void) {
1223 char *p
= malloc(100);
1224 setbuf(__stdoutp
, p
);
1227 int my_main_warn(FILE *f
) {
1228 char *p
= malloc(100);
1229 setvbuf(f
, p
, 0, 100);
1230 return 0;// expected-warning {{leak}}
1233 // <rdar://problem/10978247>.
1234 // some people use stack allocated memory as an optimization to avoid
1235 // a heap allocation for small work sizes. This tests the analyzer's
1236 // understanding that the malloc'ed memory is not the same as stackBuffer.
1237 void radar10978247(int myValueSize
) {
1238 char stackBuffer
[128];
1241 if (myValueSize
<= sizeof(stackBuffer
))
1242 buffer
= stackBuffer
;
1244 buffer
= malloc(myValueSize
);
1246 // do stuff with the buffer
1247 if (buffer
!= stackBuffer
)
1251 void radar10978247_positive(int myValueSize
) {
1252 char stackBuffer
[128];
1255 if (myValueSize
<= sizeof(stackBuffer
))
1256 buffer
= stackBuffer
;
1258 buffer
= malloc(myValueSize
);
1260 // do stuff with the buffer
1261 if (buffer
== stackBuffer
)
1264 return; // expected-warning {{leak}}
1266 // <rdar://problem/11269741> Previously this triggered a false positive
1267 // because malloc() is known to return uninitialized memory and the binding
1268 // of 'o' to 'p->n' was not getting propertly handled. Now we report a leak.
1269 struct rdar11269741_a_t
{
1270 struct rdar11269741_b_t
{
1275 int rdar11269741(struct rdar11269741_b_t o
)
1277 struct rdar11269741_a_t
*p
= (struct rdar11269741_a_t
*) malloc(sizeof(*p
));
1279 return p
->n
.m
; // expected-warning {{leak}}
1282 // Pointer arithmetic, returning an ElementRegion.
1283 void *radar11329382(unsigned bl
) {
1284 void *ptr
= malloc (16);
1285 ptr
= ptr
+ (2 - bl
);
1286 return ptr
; // no warning
1289 void __assert_rtn(const char *, const char *, int, const char *) __attribute__((__noreturn__
));
1290 int strcmp(const char *, const char *);
1292 void radar11270219(void) {
1293 char *x
= a(), *y
= a();
1294 (__builtin_expect(!(x
&& y
), 0) ? __assert_rtn(__func__
, "/Users/zaks/tmp/ex.c", 24, "x && y") : (void)0);
1295 strcmp(x
, y
); // no warning
1298 void radar_11358224_test_double_assign_ints_positive_2(void)
1300 void *ptr
= malloc(16);
1302 } // expected-warning {{leak}}
1304 // Assume that functions which take a function pointer can free memory even if
1305 // they are defined in system headers and take the const pointer to the
1306 // allocated memory. (radar://11160612)
1307 int const_ptr_and_callback(int, const char*, int n
, void(*)(void*));
1308 void r11160612_1(void) {
1309 char *x
= malloc(12);
1310 const_ptr_and_callback(0, x
, 12, free
); // no - warning
1313 // Null is passed as callback.
1314 void r11160612_2(void) {
1315 char *x
= malloc(12);
1316 const_ptr_and_callback(0, x
, 12, 0);
1317 } // expected-warning {{leak}}
1319 // Callback is passed to a function defined in a system header.
1320 void r11160612_4(void) {
1321 char *x
= malloc(12);
1322 sqlite3_bind_text_my(0, x
, 12, free
); // no - warning
1325 // Passing callbacks in a struct.
1326 void r11160612_5(StWithCallback St
) {
1327 void *x
= malloc(12);
1328 dealocateMemWhenDoneByVal(x
, St
);
1330 void r11160612_6(StWithCallback St
) {
1331 void *x
= malloc(12);
1332 dealocateMemWhenDoneByRef(&St
, x
);
1335 int mySub(int, int);
1336 int myAdd(int, int);
1337 int fPtr(unsigned cond
, int x
) {
1338 return (cond
? mySub
: myAdd
)(x
, x
);
1341 // Test anti-aliasing.
1343 void dependsOnValueOfPtr(int *g
, unsigned f
) {
1355 return; // no warning
1359 int CMPRegionHeapToStack(void) {
1361 int *x1
= malloc(8);
1363 clang_analyzer_eval(x1
== x2
); // expected-warning{{FALSE}}
1368 int CMPRegionHeapToHeap2(void) {
1370 int *x1
= malloc(8);
1371 int *x2
= malloc(8);
1374 clang_analyzer_eval(x4
== x5
); // expected-warning{{FALSE}}
1380 int CMPRegionHeapToHeap(void) {
1382 int *x1
= malloc(8);
1386 return 5/x
; // expected-warning{{Division by zero}}
1388 return x
;// expected-warning{{This statement is never executed}}
1391 int HeapAssignment(void) {
1396 clang_analyzer_eval(*x
!= *y
); // expected-warning{{FALSE}}
1402 int *retPtrMightAlias(int *x
);
1403 int cmpHeapAllocationToUnknown(void) {
1405 int *yBefore
= retPtr();
1407 int *yAfter
= retPtrMightAlias(m
);
1408 clang_analyzer_eval(yBefore
== m
); // expected-warning{{FALSE}}
1409 clang_analyzer_eval(yAfter
== m
); // expected-warning{{FALSE}}
1414 void localArrayTest(void) {
1415 char *p
= (char*)malloc(12);
1418 } // expected-warning {{leak}}
1420 void localStructTest(void) {
1422 StructWithPtr
*pSt
= &St
;
1423 pSt
->memP
= malloc(12);
1424 } // expected-warning{{Potential leak of memory pointed to by}}
1426 #ifdef __INTPTR_TYPE__
1427 // Test double assignment through integers.
1428 typedef __INTPTR_TYPE__
intptr_t;
1429 typedef unsigned __INTPTR_TYPE__
uintptr_t;
1431 static intptr_t glob
;
1432 void test_double_assign_ints(void)
1434 void *ptr
= malloc (16); // no-warning
1435 glob
= (intptr_t)(uintptr_t)ptr
;
1438 void test_double_assign_ints_positive(void)
1440 void *ptr
= malloc(16);
1441 (void*)(intptr_t)(uintptr_t)ptr
; // expected-warning {{unused}}
1442 } // expected-warning {{leak}}
1445 void testCGContextNoLeak(void)
1447 void *ptr
= malloc(16);
1448 CGContextRef context
= CGBitmapContextCreate(ptr
);
1450 // Because you can get the data back out like this, even much later,
1451 // CGBitmapContextCreate is one of our "stop-tracking" exceptions.
1452 free(CGBitmapContextGetData(context
));
1455 void testCGContextLeak(void)
1457 void *ptr
= malloc(16);
1458 CGContextRef context
= CGBitmapContextCreate(ptr
);
1459 // However, this time we're just leaking the data, because the context
1460 // object doesn't escape and it hasn't been freed in this function.
1463 // Allow xpc context to escape. radar://11635258
1464 // TODO: Would be great if we checked that the finalize_connection_context actually releases it.
1465 static void finalize_connection_context(void *ctx
) {
1469 void foo (xpc_connection_t peer
) {
1470 int *ctx
= calloc(1, sizeof(int));
1471 xpc_connection_set_context(peer
, ctx
);
1472 xpc_connection_set_finalizer_f(peer
, finalize_connection_context
);
1473 xpc_connection_resume(peer
);
1476 // Make sure we catch errors when we free in a function which does not allocate memory.
1477 void freeButNoMalloc(int *p
, int x
){
1480 //user forgot a return here.
1482 free(p
); // expected-warning {{Attempt to free released memory}}
1489 char* reallocButNoMalloc(struct HasPtr
*a
, int c
, int size
) {
1491 char *b
= realloc(a
->p
, size
);
1492 char *m
= realloc(a
->p
, size
); // expected-warning {{Attempt to free released memory}}
1493 // We don't expect a use-after-free for a->P here because the warning above
1495 return a
->p
; // no-warning
1498 // We should not warn in this case since the caller will presumably free a->p in all cases.
1499 int reallocButNoMallocPR13674(struct HasPtr
*a
, int c
, int size
) {
1501 char *b
= realloc(a
->p
, size
);
1508 // Test realloc with no visible malloc.
1509 void *test(void *ptr
) {
1510 void *newPtr
= realloc(ptr
, 4);
1513 free(ptr
); // no-warning
1519 char *testLeakWithinReturn(char *str
) {
1520 return strdup(strdup(str
)); // expected-warning{{leak}}
1523 char *testWinLeakWithinReturn(char *str
) {
1524 return _strdup(_strdup(str
)); // expected-warning{{leak}}
1527 wchar_t *testWinWideLeakWithinReturn(wchar_t *str
) {
1528 return _wcsdup(_wcsdup(str
)); // expected-warning{{leak}}
1531 void passConstPtr(const char * ptr
);
1533 void testPassConstPointer(void) {
1534 char * string
= malloc(sizeof(char)*10);
1535 passConstPtr(string
);
1536 return; // expected-warning {{leak}}
1539 void testPassConstPointerIndirectly(void) {
1540 char *p
= malloc(1);
1542 memcmp(p
, p
, sizeof(&p
));
1543 return; // expected-warning {{leak}}
1546 void testPassConstPointerIndirectlyStruct(void) {
1549 memcmp(&hp
, &hp
, sizeof(hp
));
1550 return; // expected-warning {{Potential leak of memory pointed to by 'hp.p'}}
1553 void testPassToSystemHeaderFunctionIndirectlyStruct(void) {
1556 fakeSystemHeaderCall(&ss
); // invalidates ss, making ss.p unreachable
1557 // Technically a false negative here -- we know the system function won't free
1558 // ss.p, but nothing else will either!
1561 void testPassToSystemHeaderFunctionIndirectlyStructFree(void) {
1564 fakeSystemHeaderCall(&ss
); // invalidates ss, making ss.p unreachable
1568 void testPassToSystemHeaderFunctionIndirectlyArray(void) {
1570 p
[0] = malloc(sizeof(int));
1571 fakeSystemHeaderCallIntPtr(p
); // invalidates p, making p[0] unreachable
1572 // Technically a false negative here -- we know the system function won't free
1573 // p[0], but nothing else will either!
1576 void testPassToSystemHeaderFunctionIndirectlyArrayFree(void) {
1578 p
[0] = malloc(sizeof(int));
1579 fakeSystemHeaderCallIntPtr(p
); // invalidates p, making p[0] unreachable
1583 int *testOffsetAllocate(size_t size
) {
1584 int *memoryBlock
= (int *)malloc(size
+ sizeof(int));
1585 return &memoryBlock
[1]; // no-warning
1588 void testOffsetDeallocate(int *memoryBlock
) {
1589 free(&memoryBlock
[-1]); // no-warning
1592 void testOffsetOfRegionFreed(void) {
1593 __int64_t
* array
= malloc(sizeof(__int64_t
)*2);
1595 free(&array
[0]); // expected-warning{{Argument to free() is offset by 8 bytes from the start of memory allocated by malloc()}}
1598 void testOffsetOfRegionFreed2(void) {
1599 __int64_t
*p
= malloc(sizeof(__int64_t
)*2);
1601 free(p
); // expected-warning{{Argument to free() is offset by 8 bytes from the start of memory allocated by malloc()}}
1604 void testOffsetOfRegionFreed3(void) {
1605 char *r
= malloc(sizeof(char));
1607 free(r
); // expected-warning {{Argument to free() is offset by -10 bytes from the start of memory allocated by malloc()}}
1610 void testOffsetOfRegionFreedAfterFunctionCall(void) {
1611 int *p
= malloc(sizeof(int)*2);
1614 free(p
); // expected-warning{{Argument to free() is offset by 4 bytes from the start of memory allocated by malloc()}}
1617 void testFixManipulatedPointerBeforeFree(void) {
1618 int * array
= malloc(sizeof(int)*2);
1620 free(&array
[-1]); // no-warning
1623 void testFixManipulatedPointerBeforeFree2(void) {
1624 char *r
= malloc(sizeof(char));
1626 free(r
-10); // no-warning
1629 void freeOffsetPointerPassedToFunction(void) {
1630 __int64_t
*p
= malloc(sizeof(__int64_t
)*2);
1633 myfooint(*p
); // not passing the pointer, only a value pointed by pointer
1634 free(p
); // expected-warning {{Argument to free() is offset by 8 bytes from the start of memory allocated by malloc()}}
1637 int arbitraryInt(void);
1638 void freeUnknownOffsetPointer(void) {
1639 char *r
= malloc(sizeof(char));
1640 r
= r
+ arbitraryInt(); // unable to reason about what the offset might be
1641 free(r
); // no-warning
1644 void testFreeNonMallocPointerWithNoOffset(void) {
1648 free(r
-10); // expected-warning {{Argument to free() is the address of the local variable 'c', which is not memory allocated by malloc()}}
1651 void testFreeNonMallocPointerWithOffset(void) {
1654 free(r
+1); // expected-warning {{Argument to free() is the address of the local variable 'c', which is not memory allocated by malloc()}}
1657 void testOffsetZeroDoubleFree(void) {
1658 int *array
= malloc(sizeof(int)*2);
1661 free(&array
[0]); // expected-warning{{Attempt to free released memory}}
1664 void testOffsetPassedToStrlen(void) {
1665 char * string
= malloc(sizeof(char)*10);
1667 int length
= strlen(string
); // expected-warning {{Potential leak of memory pointed to by 'string'}}
1670 void testOffsetPassedToStrlenThenFree(void) {
1671 char * string
= malloc(sizeof(char)*10);
1673 int length
= strlen(string
);
1674 free(string
); // expected-warning {{Argument to free() is offset by 1 byte from the start of memory allocated by malloc()}}
1677 void testOffsetPassedAsConst(void) {
1678 char * string
= malloc(sizeof(char)*10);
1680 passConstPtr(string
);
1681 free(string
); // expected-warning {{Argument to free() is offset by 1 byte from the start of memory allocated by malloc()}}
1684 char **_vectorSegments
;
1685 int _nVectorSegments
;
1687 void poolFreeC(void* s
) {
1688 free(s
); // no-warning
1690 void freeMemory(void) {
1691 while (_nVectorSegments
) {
1692 poolFreeC(_vectorSegments
[_nVectorSegments
++]);
1697 void testReallocEscaped(void **memory
) {
1698 *memory
= malloc(47);
1699 char *new_memory
= realloc(*memory
, 47);
1700 if (new_memory
!= 0) {
1701 *memory
= new_memory
;
1706 void *smallocNoWarn(size_t size
) {
1708 return malloc(1); // this branch is never called
1711 return malloc(size
);
1715 char *dupstrNoWarn(const char *s
) {
1716 const int len
= strlen(s
);
1717 char *p
= (char*) smallocNoWarn(len
+ 1);
1718 strcpy(p
, s
); // no-warning
1722 void *smallocWarn(size_t size
) {
1727 return malloc(size
);
1731 int *radar15580979(void) {
1732 int *data
= (int *)malloc(32);
1733 int *p
= data
?: (int*)malloc(32); // no warning
1737 // Some data structures may hold onto the pointer and free it later.
1738 void testEscapeThroughSystemCallTakingVoidPointer1(void *queue
) {
1739 int *data
= (int *)malloc(32);
1740 fake_insque(queue
, data
); // no warning
1743 void testEscapeThroughSystemCallTakingVoidPointer2(fake_rb_tree_t
*rbt
) {
1744 int *data
= (int *)malloc(32);
1745 fake_rb_tree_init(rbt
, data
);
1746 } //expected-warning{{Potential leak}}
1748 void testEscapeThroughSystemCallTakingVoidPointer3(fake_rb_tree_t
*rbt
) {
1749 int *data
= (int *)malloc(32);
1750 fake_rb_tree_init(rbt
, data
);
1751 fake_rb_tree_insert_node(rbt
, data
); // no warning
1759 void constEscape(const void *ptr
);
1761 void testConstEscapeThroughAnotherField(void) {
1763 s
.p
= malloc(sizeof(int));
1764 constEscape(&(s
.x
)); // could free s->p!
1768 int testNoCheckerDataPropogationFromLogicalOpOperandToOpResult(void) {
1769 char *param
= malloc(10);
1770 char *value
= malloc(10);
1771 int ok
= (param
&& value
);
1774 // Previously we ended up with 'Use of memory after it is freed' on return.
1775 return ok
; // no warning
1779 void freeIndirectFunctionPtr(void) {
1780 void *p
= (void *)fnptr
;
1781 free(p
); // expected-warning {{Argument to free() is a function pointer}}
1784 void freeFunctionPtr(void) {
1785 free((void *)fnptr
);
1786 // expected-warning@-1{{Argument to free() is a function pointer}}
1787 // expected-warning@-2{{attempt to call free on non-heap object '(void *)fnptr'}}
1790 void allocateSomeMemory(void *offendingParameter
, void **ptr
) {
1794 void testNoCrashOnOffendingParameter(void) {
1795 // "extern" is necessary to avoid unrelated warnings
1796 // on passing uninitialized value.
1797 extern void *offendingParameter
;
1799 allocateSomeMemory(offendingParameter
, &ptr
);
1800 } // expected-warning {{Potential leak of memory pointed to by 'ptr'}}
1803 // Test a false positive caused by a bug in liveness analysis.
1810 void livenessBugRealloc(struct A
*a
) {
1811 a
->buf
= realloc(a
->buf
, sizeof(int)); // no-warning
1813 void testLivenessBug(struct B
*in_b
) {
1815 livenessBugRealloc(b
->a
);
1816 ((void) 0); // An attempt to trick liveness analysis.
1817 livenessBugRealloc(b
->a
);
1821 struct ListInfo
*next
;
1824 struct ConcreteListItem
{
1829 void list_add(struct ListInfo
*list
, struct ListInfo
*item
);
1831 void testCStyleListItems(struct ListInfo
*list
) {
1832 struct ConcreteListItem
*x
= malloc(sizeof(struct ConcreteListItem
));
1833 list_add(list
, &x
->li
); // will free 'x'.
1836 // MEM34-C. Only free memory allocated dynamically
1837 // Second non-compliant example.
1838 // https://wiki.sei.cmu.edu/confluence/display/c/MEM34-C.+Only+free+memory+allocated+dynamically
1839 enum { BUFSIZE
= 256 };
1841 void MEM34_C(void) {
1843 char *p
= (char *)realloc(buf
, 2 * BUFSIZE
);
1844 // expected-warning@-1{{Argument to realloc() is the address of the local \
1845 variable
'buf', which is
not memory allocated by
malloc() [unix
.Malloc
]}}
1851 (*crash_a
)(); // expected-warning{{type specifier missing}}
1852 // A CallEvent without a corresponding FunctionDecl.
1853 crash_b() { crash_a(); } // no-crash
1854 // expected-warning@-1{{type specifier missing}} expected-warning@-1{{non-void}}
1857 void realloc_crash(void) {
1860 realloc(c
, 8); // no-crash
1861 } // expected-warning{{Potential memory leak [unix.Malloc]}}
1863 // ----------------------------------------------------------------------------
1866 void testMallocWithParam(int **p
) {
1867 *p
= (int*) malloc(sizeof(int));
1868 *p
= 0; // FIXME: should warn here
1871 void testMallocWithParam_2(int **p
) {
1872 *p
= (int*) malloc(sizeof(int)); // no-warning
1875 void testPassToSystemHeaderFunctionIndirectly(void) {
1878 fakeSystemHeaderCallInt(p
);
1879 // FIXME: This is a leak: if we think a system function won't free p, it
1880 // won't free (p-1) either.
1883 void testMallocIntoMalloc(void) {
1884 StructWithPtr
*s
= malloc(sizeof(StructWithPtr
));
1885 s
->memP
= malloc(sizeof(int));
1887 } // FIXME: should warn here
1890 void testExtent(void) {
1892 clang_analyzer_dump(x
);
1893 // expected-warning-re@-1 {{{{^conj_\$[[:digit:]]+{int, LC1, S[[:digit:]]+, #1}}}}}}
1894 int *p
= (int *)malloc(x
);
1895 clang_analyzer_dumpExtent(p
);
1896 // expected-warning-re@-1 {{{{^conj_\$[[:digit:]]+{int, LC1, S[[:digit:]]+, #1}}}}}}