1 // RUN: %clang_analyze_cc1 -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.Malloc \
6 // RUN: -analyzer-checker=debug.ExprInspection
8 #include "Inputs/system-header-simulator.h"
10 void clang_analyzer_eval(int);
12 // Without -fms-compatibility, wchar_t isn't a builtin type. MSVC defines
13 // _WCHAR_T_DEFINED if wchar_t is available. Microsoft recommends that you use
14 // the builtin type: "Using the typedef version can cause portability
15 // problems", but we're ok here because we're not actually running anything.
16 // Also of note is this cryptic warning: "The wchar_t type is not supported
17 // when you compile C code".
19 // See the docs for more:
20 // https://msdn.microsoft.com/en-us/library/dh8che7s.aspx
21 #if !defined(_WCHAR_T_DEFINED)
22 // "Microsoft implements wchar_t as a two-byte unsigned value"
23 typedef unsigned short wchar_t;
24 #define _WCHAR_T_DEFINED
25 #endif // !defined(_WCHAR_T_DEFINED)
27 typedef __typeof(sizeof(int)) size_t;
32 void *realloc(void *ptr, size_t size);
33 void *reallocf(void *ptr, size_t size);
34 void *calloc(size_t nmemb, size_t size);
35 char *strdup(const char *s);
36 wchar_t *wcsdup(const wchar_t *s);
37 char *strndup(const char *s, size_t n);
38 int memcmp(const void *s1, const void *s2, size_t n);
41 char *_strdup(const char *strSource);
42 wchar_t *_wcsdup(const wchar_t *strSource);
43 void *_alloca(size_t size);
51 return; // expected-warning{{Potential leak of memory pointed to by 'p'}}
57 free(p); // expected-warning{{Attempt to free released memory}}
63 realloc(p,0); // expected-warning{{Attempt to free released memory}}
68 int *q = realloc(p,0); // no-warning
71 void reallocNotNullPtr(unsigned sizeIn) {
73 char *p = (char*)malloc(size);
75 char *q = (char*)realloc(p, sizeIn);
76 char x = *q; // expected-warning {{Potential leak of memory pointed to by 'q'}}
81 int *p = alloca(sizeof(int));
84 void winAllocaTest() {
85 int *p = _alloca(sizeof(int));
88 void allocaBuiltinTest() {
89 int *p = __builtin_alloca(sizeof(int));
95 return q; // no warning - returning the allocated value
98 // p should be freed if realloc fails.
100 char *p = malloc(12);
101 char *r = realloc(p, 12+1);
109 void reallocSizeZero1() {
110 char *p = malloc(12);
111 char *r = realloc(p, 0);
113 free(p); // expected-warning {{Attempt to free released memory}}
119 void reallocSizeZero2() {
120 char *p = malloc(12);
121 char *r = realloc(p, 0);
123 free(p); // expected-warning {{Attempt to free released memory}}
127 free(p); // expected-warning {{Attempt to free released memory}}
130 void reallocSizeZero3() {
131 char *p = malloc(12);
132 char *r = realloc(p, 0);
136 void reallocSizeZero4() {
137 char *r = realloc(0, 0);
141 void reallocSizeZero5() {
142 char *r = realloc(0, 0);
145 void reallocPtrZero1() {
146 char *r = realloc(0, 12);
147 } // expected-warning {{Potential leak of memory pointed to by 'r'}}
149 void reallocPtrZero2() {
150 char *r = realloc(0, 12);
155 void reallocPtrZero3() {
156 char *r = realloc(0, 12);
160 void reallocRadar6337483_1() {
161 char *buf = malloc(100);
162 buf = (char*)realloc(buf, 0x1000000);
164 return;// expected-warning {{Potential leak of memory pointed to by}}
169 void reallocRadar6337483_2() {
170 char *buf = malloc(100);
171 char *buf2 = (char*)realloc(buf, 0x1000000);
177 } // expected-warning {{Potential leak of memory pointed to by}}
179 void reallocRadar6337483_3() {
180 char * buf = malloc(100);
182 tmp = (char*)realloc(buf, 0x1000000);
191 void reallocRadar6337483_4() {
192 char *buf = malloc(100);
193 char *buf2 = (char*)realloc(buf, 0x1000000);
195 return; // expected-warning {{Potential leak of memory pointed to by}}
201 int *reallocfTest1() {
204 return q; // no warning - returning the allocated value
207 void reallocfRadar6337483_4() {
208 char *buf = malloc(100);
209 char *buf2 = (char*)reallocf(buf, 0x1000000);
211 return; // no warning - reallocf frees even on failure
217 void reallocfRadar6337483_3() {
218 char * buf = malloc(100);
220 tmp = (char*)reallocf(buf, 0x1000000);
222 free(buf); // expected-warning {{Attempt to free released memory}}
229 void reallocfPtrZero1() {
230 char *r = reallocf(0, 12);
231 } // expected-warning {{Potential leak of memory pointed to by}}
233 //------------------- Check usage of zero-allocated memory ---------------------
234 void CheckUseZeroAllocatedNoWarn1() {
236 free(p); // no warning
239 void CheckUseZeroAllocatedNoWarn2() {
240 int *p = alloca(0); // no warning
243 void CheckUseZeroWinAllocatedNoWarn2() {
244 int *p = _alloca(0); // no warning
248 void CheckUseZeroAllocatedNoWarn3() {
250 int *q = realloc(p, 8); // no warning
254 void CheckUseZeroAllocatedNoWarn4() {
255 int *p = realloc(0, 8);
256 *p = 1; // no warning
260 void CheckUseZeroAllocated1() {
262 *p = 1; // expected-warning {{Use of zero-allocated memory}}
266 char CheckUseZeroAllocated2() {
268 return *p; // expected-warning {{Use of zero-allocated memory}}
271 char CheckUseZeroWinAllocated2() {
272 char *p = _alloca(0);
273 return *p; // expected-warning {{Use of zero-allocated memory}}
276 void UseZeroAllocated(int *p) {
278 *p = 7; // expected-warning {{Use of zero-allocated memory}}
280 void CheckUseZeroAllocated3() {
286 void CheckUseZeroAllocated4() {
288 f(*p); // expected-warning {{Use of zero-allocated memory}}
292 void CheckUseZeroAllocated5() {
293 int *p = calloc(0, 2);
294 *p = 1; // expected-warning {{Use of zero-allocated memory}}
298 void CheckUseZeroAllocated6() {
299 int *p = calloc(2, 0);
300 *p = 1; // expected-warning {{Use of zero-allocated memory}}
304 void CheckUseZeroAllocated7() {
305 int *p = realloc(0, 0);
306 *p = 1; // expected-warning {{Use of zero-allocated memory}}
310 void CheckUseZeroAllocated8() {
312 int *q = realloc(p, 0);
313 *q = 1; // expected-warning {{Use of zero-allocated memory}}
317 void CheckUseZeroAllocated9() {
318 int *p = realloc(0, 0);
319 int *q = realloc(p, 0);
320 *q = 1; // expected-warning {{Use of zero-allocated memory}}
324 void CheckUseZeroAllocatedPathNoWarn(_Bool b) {
332 *p = 1; // no warning
337 void CheckUseZeroAllocatedPathWarn(_Bool b) {
345 *p = 1; // expected-warning {{Use of zero-allocated memory}}
350 void CheckUseZeroReallocatedPathNoWarn(_Bool b) {
356 char *q = realloc(p, s);
359 *q = 1; // no warning
364 void CheckUseZeroReallocatedPathWarn(_Bool b) {
370 char *q = realloc(p, s);
373 *q = 1; // expected-warning {{Use of zero-allocated memory}}
378 // This case tests that storing malloc'ed memory to a static variable which is
379 // then returned is not leaked. In the absence of known contracts for functions
380 // or inter-procedural analysis, this is a conservative answer.
384 return p; // no-warning
387 // This case tests that storing malloc'ed memory to a static global variable
388 // which is then returned is not leaked. In the absence of known contracts for
389 // functions or inter-procedural analysis, this is a conservative answer.
390 static int *p_f4 = 0;
393 return p_f4; // no-warning
399 return q; // no-warning
405 return; // no-warning
413 return; // no-warning
430 char *x = (char*) malloc(4);
432 x[0] = 'a'; // expected-warning{{Use of memory after it is freed}}
436 char *x = (char*) malloc(4);
438 char *y = strndup(x, 4); // expected-warning{{Use of memory after it is freed}}
442 char *x = (char*) malloc(4);
444 x[0] = 'a'; // expected-warning{{Use of memory after it is freed}}
448 int *x = malloc(11); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
452 int *buf = malloc(2); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
453 buf[1] = 'c'; // not crash
456 void cast_emtpy_struct() {
460 struct st *s = malloc(sizeof(struct st)); // no-warning
464 void cast_struct_1() {
470 struct st *s = malloc(sizeof(struct st)); // no-warning
474 void cast_struct_2() {
480 struct st *s = malloc(sizeof(struct st)); // no-warning
484 void cast_struct_3() {
490 struct st *s = malloc(sizeof(struct st)); // no-warning
494 void cast_struct_4() {
500 struct st *s = malloc(sizeof(struct st)); // no-warning
504 void cast_struct_5() {
510 struct st *s = malloc(sizeof(struct st) - sizeof(char)); // no-warning
514 void cast_struct_warn_1() {
520 struct st *s = malloc(sizeof(struct st) + 2); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
524 void cast_struct_warn_2() {
530 struct st *s = malloc(2); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
534 void cast_struct_flex_array_1() {
540 struct st *s = malloc(sizeof(struct st) + 3); // no-warning
544 void cast_struct_flex_array_2() {
550 struct st *s = malloc(sizeof(struct st) + 3); // no-warning
554 void cast_struct_flex_array_3() {
560 struct st *s = malloc(sizeof(struct st) + 3); // no-warning
564 void cast_struct_flex_array_4() {
573 struct st *s = malloc(sizeof(struct st) + 3 * sizeof(struct foo)); // no-warning
577 void cast_struct_flex_array_5() {
586 struct st *s = malloc(sizeof(struct st) + 3 * sizeof(struct foo)); // no-warning
590 void cast_struct_flex_array_6() {
599 struct st *s = malloc(sizeof(struct st) + 3 * sizeof(struct foo)); // no-warning
603 void cast_struct_flex_array_warn_1() {
612 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}}
616 void cast_struct_flex_array_warn_2() {
625 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}}
629 void cast_struct_flex_array_warn_3() {
638 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}}
642 void cast_struct_flex_array_warn_4() {
648 struct st *s = malloc(sizeof(struct st) + 3); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
652 void cast_struct_flex_array_warn_5() {
658 struct st *s = malloc(sizeof(struct st) + 3); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
662 void cast_struct_flex_array_warn_6() {
668 struct st *s = malloc(sizeof(struct st) + 3); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
672 void mallocCastToVoid() {
674 const void *cp = p; // not crash
678 void mallocCastToFP() {
680 void (*fp)() = p; // not crash
684 // This tests that malloc() buffers are undefined by default
685 char mallocGarbage () {
686 char *buf = malloc(2);
687 char result = buf[1]; // expected-warning{{undefined}}
692 // This tests that calloc() buffers need to be freed
693 void callocNoFree () {
694 char *buf = calloc(2,2);
695 return; // expected-warning{{Potential leak of memory pointed to by 'buf'}}
698 // These test that calloc() buffers are zeroed by default
699 char callocZeroesGood () {
700 char *buf = calloc(2,2);
701 char result = buf[3]; // no-warning
705 return result; // no-warning
708 char callocZeroesBad () {
709 char *buf = calloc(2,2);
710 char result = buf[3]; // no-warning
712 free(buf); // expected-warning{{never executed}}
714 return result; // expected-warning{{Potential leak of memory pointed to by 'buf'}}
719 free(p); // no warning - a nop
722 void paramFree(int *p) {
724 free(p); // no warning
725 myfoo(p); // expected-warning {{Use of memory after it is freed}}
728 int* mallocEscapeRet() {
730 return p; // no warning
733 void mallocEscapeFoo() {
736 return; // no warning
739 void mallocEscapeFree() {
745 void mallocEscapeFreeFree() {
749 free(p); // expected-warning{{Attempt to free released memory}}
752 void mallocEscapeFreeUse() {
756 myfoo(p); // expected-warning{{Use of memory after it is freed}}
760 void myalloc2(int **p);
762 void mallocEscapeFreeCustomAlloc() {
767 free(p); // no warning
770 void mallocEscapeFreeCustomAlloc2() {
775 free(p); // no warning
778 void mallocBindFreeUse() {
782 myfoo(x); // expected-warning{{Use of memory after it is freed}}
785 void mallocEscapeMalloc() {
789 } // expected-warning{{Potential leak of memory pointed to by}}
791 void mallocMalloc() {
794 } // expected-warning {{Potential leak of memory pointed to by}}
796 void mallocFreeMalloc() {
803 void mallocFreeUse_params() {
806 myfoo(p); //expected-warning{{Use of memory after it is freed}}
809 void mallocFreeUse_params2() {
812 myfooint(*p); //expected-warning{{Use of memory after it is freed}}
815 void mallocFailedOrNot() {
823 struct StructWithInt {
827 int *mallocReturnFreed() {
830 return p; // expected-warning {{Use of memory after it is freed}}
833 int useAfterFreeStruct() {
834 struct StructWithInt *px= malloc(sizeof(struct StructWithInt));
837 return px->g; // expected-warning {{Use of memory after it is freed}}
840 void nonSymbolAsFirstArg(int *pp, struct StructWithInt *p);
842 void mallocEscapeFooNonSymbolArg() {
843 struct StructWithInt *p = malloc(sizeof(struct StructWithInt));
844 nonSymbolAsFirstArg(&p->g, p);
845 return; // no warning
848 void mallocFailedOrNotLeak() {
851 return; // no warning
853 return; // expected-warning {{Potential leak of memory pointed to by}}
856 void mallocAssignment() {
857 char *p = malloc(12);
859 } // expected-warning {{leak}}
862 char *mem = valloc(12);
863 return 0; // expected-warning {{Potential leak of memory pointed to by}}
866 void vallocEscapeFreeUse() {
870 myfoo(p); // expected-warning{{Use of memory after it is freed}}
878 struct GlStTy GlS = {0};
884 void GlobalMalloc() {
888 void GlobalStructMalloc() {
893 void GlobalStructMallocFree() {
901 void globalArrayTest() {
902 char *p = (char*)malloc(12);
906 // Make sure that we properly handle a pointer stored into a local struct/array.
907 typedef struct _StructWithPtr {
911 static StructWithPtr arrOfStructs[10];
917 arrOfStructs[0] = St; // no-warning
920 StructWithPtr testMalloc2() {
924 return St; // no-warning
930 return y; // no-warning
933 void testStructLeak() {
935 St.memP = malloc(12);
936 return; // expected-warning {{Potential leak of memory pointed to by 'St.memP'}}
939 void testElemRegion1() {
940 char *x = (void*)malloc(2);
945 void testElemRegion2(int **pp) {
951 void testElemRegion3(int **pp) {
956 // Region escape testing.
958 unsigned takePtrToPtr(int **p);
959 void PassTheAddrOfAllocatedData(int f) {
961 // We don't know what happens after the call. Should stop tracking here.
962 if (takePtrToPtr(&p))
964 free(p); // no warning
970 unsigned takePtrToStruct(struct X *s);
971 int ** foo2(int *g, int f) {
973 struct X *px= malloc(sizeof(struct X));
975 // We don't know what happens after this call. Should not track px nor p.
976 if (takePtrToStruct(px))
982 struct X* RegInvalidationDetect1(struct X *s2) {
983 struct X *px= malloc(sizeof(struct X));
986 return px; // expected-warning {{Potential leak of memory pointed to by}}
989 struct X* RegInvalidationGiveUp1() {
991 struct X *px= malloc(sizeof(struct X));
996 int **RegInvalidationDetect2(int **pp) {
1000 return 0;// expected-warning {{Potential leak of memory pointed to by}}
1003 extern void exit(int) __attribute__ ((__noreturn__));
1004 void mallocExit(int *g) {
1005 struct xx *p = malloc(12);
1012 extern void __assert_fail (__const char *__assertion, __const char *__file,
1013 unsigned int __line, __const char *__function)
1014 __attribute__ ((__noreturn__));
1015 #define assert(expr) \
1016 ((expr) ? (void)(0) : __assert_fail (#expr, __FILE__, __LINE__, __func__))
1017 void mallocAssert(int *g) {
1018 struct xx *p = malloc(12);
1025 void doNotInvalidateWhenPassedToSystemCalls(char *s) {
1026 char *p = malloc(12);
1034 } // expected-warning {{leak}}
1036 // Treat source buffer contents as escaped.
1037 void escapeSourceContents(char *s) {
1038 char *p = malloc(12);
1039 memcpy(s, &p, 12); // no warning
1041 void *p1 = malloc(7);
1043 memcpy(&a, &p1, sizeof a);
1044 // FIXME: No warning due to limitations imposed by current modelling of
1045 // 'memcpy' (regions metadata is not copied).
1048 int *allocated = (int *)malloc(4);
1049 memcpy(&ptrs[0], &allocated, sizeof(int *));
1050 // FIXME: No warning due to limitations imposed by current modelling of
1051 // 'memcpy' (regions metadata is not copied).
1054 void invalidateDestinationContents() {
1056 int *p = (int *)malloc(4);
1057 memcpy(&p, &null, sizeof(int *));
1059 int *ptrs1[2]; // expected-warning {{Potential leak of memory pointed to by}}
1060 ptrs1[0] = (int *)malloc(4);
1061 memcpy(ptrs1, &null, sizeof(int *));
1063 int *ptrs2[2]; // expected-warning {{Potential memory leak}}
1064 ptrs2[0] = (int *)malloc(4);
1065 memcpy(&ptrs2[1], &null, sizeof(int *));
1067 int *ptrs3[2]; // expected-warning {{Potential memory leak}}
1068 ptrs3[0] = (int *)malloc(4);
1069 memcpy(&ptrs3[0], &null, sizeof(int *));
1070 } // expected-warning {{Potential memory leak}}
1072 // Rely on the CString checker evaluation of the strcpy API to convey that the result of strcpy is equal to p.
1073 void symbolLostWithStrcpy(char *s) {
1074 char *p = malloc(12);
1080 // The same test as the one above, but with what is actually generated on a mac.
1081 static __inline char *
1082 __inline_strcpy_chk (char *restrict __dest, const char *restrict __src)
1084 return __builtin___strcpy_chk (__dest, __src, __builtin_object_size (__dest, 2 > 1));
1087 void symbolLostWithStrcpy_InlineStrcpyVersion(char *s) {
1088 char *p = malloc(12);
1089 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));
1093 // Here we are returning a pointer one past the allocated value. An idiom which
1094 // can be used for implementing special malloc. The correct uses of this might
1095 // be rare enough so that we could keep this as a warning.
1096 static void *specialMalloc(int n){
1106 // Potentially, the user could free the struct by performing pointer arithmetic on the return value.
1107 // This is a variation of the specialMalloc issue, though probably would be more rare in correct code.
1108 int *specialMallocWithStruct() {
1109 struct StructWithInt *px= malloc(sizeof(struct StructWithInt));
1113 // Test various allocation/deallocation functions.
1114 void testStrdup(const char *s, unsigned validIndex) {
1115 char *s2 = strdup(s);
1116 s2[validIndex + 1] = 'b';
1117 } // expected-warning {{Potential leak of memory pointed to by}}
1119 void testWinStrdup(const char *s, unsigned validIndex) {
1120 char *s2 = _strdup(s);
1121 s2[validIndex + 1] = 'b';
1122 } // expected-warning {{Potential leak of memory pointed to by}}
1124 void testWcsdup(const wchar_t *s, unsigned validIndex) {
1125 wchar_t *s2 = wcsdup(s);
1126 s2[validIndex + 1] = 'b';
1127 } // expected-warning {{Potential leak of memory pointed to by}}
1129 void testWinWcsdup(const wchar_t *s, unsigned validIndex) {
1130 wchar_t *s2 = _wcsdup(s);
1131 s2[validIndex + 1] = 'b';
1132 } // expected-warning {{Potential leak of memory pointed to by}}
1134 int testStrndup(const char *s, unsigned validIndex, unsigned size) {
1135 char *s2 = strndup(s, size);
1136 s2 [validIndex + 1] = 'b';
1137 if (s2[validIndex] != 'a')
1140 return 1;// expected-warning {{Potential leak of memory pointed to by}}
1143 void testStrdupContentIsDefined(const char *s, unsigned validIndex) {
1144 char *s2 = strdup(s);
1145 char result = s2[1];// no warning
1149 void testWinStrdupContentIsDefined(const char *s, unsigned validIndex) {
1150 char *s2 = _strdup(s);
1151 char result = s2[1];// no warning
1155 void testWcsdupContentIsDefined(const wchar_t *s, unsigned validIndex) {
1156 wchar_t *s2 = wcsdup(s);
1157 wchar_t result = s2[1];// no warning
1161 void testWinWcsdupContentIsDefined(const wchar_t *s, unsigned validIndex) {
1162 wchar_t *s2 = _wcsdup(s);
1163 wchar_t result = s2[1];// no warning
1167 // ----------------------------------------------------------------------------
1168 // Test the system library functions to which the pointer can escape.
1169 // This tests false positive suppression.
1171 // For now, we assume memory passed to pthread_specific escapes.
1172 // TODO: We could check that if a new pthread binding is set, the existing
1173 // binding must be freed; otherwise, a memory leak can occur.
1174 void testPthereadSpecificEscape(pthread_key_t key) {
1175 void *buf = malloc(12);
1176 pthread_setspecific(key, buf); // no warning
1179 // PR12101: Test funopen().
1180 static int releasePtr(void *_ctx) {
1184 FILE *useFunOpen() {
1185 void *ctx = malloc(sizeof(int));
1186 FILE *f = funopen(ctx, 0, 0, 0, releasePtr); // no warning
1192 FILE *useFunOpenNoReleaseFunction() {
1193 void *ctx = malloc(sizeof(int));
1194 FILE *f = funopen(ctx, 0, 0, 0, 0);
1198 return f; // expected-warning{{leak}}
1201 static int readNothing(void *_ctx, char *buf, int size) {
1204 FILE *useFunOpenReadNoRelease() {
1205 void *ctx = malloc(sizeof(int));
1206 FILE *f = funopen(ctx, readNothing, 0, 0, 0);
1210 return f; // expected-warning{{leak}}
1213 // Test setbuf, setvbuf.
1214 int my_main_no_warning() {
1215 char *p = malloc(100);
1216 setvbuf(stdout, p, 0, 100);
1219 int my_main_no_warning2() {
1220 char *p = malloc(100);
1221 setbuf(__stdoutp, p);
1224 int my_main_warn(FILE *f) {
1225 char *p = malloc(100);
1226 setvbuf(f, p, 0, 100);
1227 return 0;// expected-warning {{leak}}
1230 // <rdar://problem/10978247>.
1231 // some people use stack allocated memory as an optimization to avoid
1232 // a heap allocation for small work sizes. This tests the analyzer's
1233 // understanding that the malloc'ed memory is not the same as stackBuffer.
1234 void radar10978247(int myValueSize) {
1235 char stackBuffer[128];
1238 if (myValueSize <= sizeof(stackBuffer))
1239 buffer = stackBuffer;
1241 buffer = malloc(myValueSize);
1243 // do stuff with the buffer
1244 if (buffer != stackBuffer)
1248 void radar10978247_positive(int myValueSize) {
1249 char stackBuffer[128];
1252 if (myValueSize <= sizeof(stackBuffer))
1253 buffer = stackBuffer;
1255 buffer = malloc(myValueSize);
1257 // do stuff with the buffer
1258 if (buffer == stackBuffer)
1261 return; // expected-warning {{leak}}
1263 // <rdar://problem/11269741> Previously this triggered a false positive
1264 // because malloc() is known to return uninitialized memory and the binding
1265 // of 'o' to 'p->n' was not getting propertly handled. Now we report a leak.
1266 struct rdar11269741_a_t {
1267 struct rdar11269741_b_t {
1272 int rdar11269741(struct rdar11269741_b_t o)
1274 struct rdar11269741_a_t *p = (struct rdar11269741_a_t *) malloc(sizeof(*p));
1276 return p->n.m; // expected-warning {{leak}}
1279 // Pointer arithmetic, returning an ElementRegion.
1280 void *radar11329382(unsigned bl) {
1281 void *ptr = malloc (16);
1282 ptr = ptr + (2 - bl);
1283 return ptr; // no warning
1286 void __assert_rtn(const char *, const char *, int, const char *) __attribute__((__noreturn__));
1287 int strcmp(const char *, const char *);
1289 void radar11270219(void) {
1290 char *x = a(), *y = a();
1291 (__builtin_expect(!(x && y), 0) ? __assert_rtn(__func__, "/Users/zaks/tmp/ex.c", 24, "x && y") : (void)0);
1292 strcmp(x, y); // no warning
1295 void radar_11358224_test_double_assign_ints_positive_2()
1297 void *ptr = malloc(16);
1299 } // expected-warning {{leak}}
1301 // Assume that functions which take a function pointer can free memory even if
1302 // they are defined in system headers and take the const pointer to the
1303 // allocated memory. (radar://11160612)
1304 int const_ptr_and_callback(int, const char*, int n, void(*)(void*));
1305 void r11160612_1() {
1306 char *x = malloc(12);
1307 const_ptr_and_callback(0, x, 12, free); // no - warning
1310 // Null is passed as callback.
1311 void r11160612_2() {
1312 char *x = malloc(12);
1313 const_ptr_and_callback(0, x, 12, 0);
1314 } // expected-warning {{leak}}
1316 // Callback is passed to a function defined in a system header.
1317 void r11160612_4() {
1318 char *x = malloc(12);
1319 sqlite3_bind_text_my(0, x, 12, free); // no - warning
1322 // Passing callbacks in a struct.
1323 void r11160612_5(StWithCallback St) {
1324 void *x = malloc(12);
1325 dealocateMemWhenDoneByVal(x, St);
1327 void r11160612_6(StWithCallback St) {
1328 void *x = malloc(12);
1329 dealocateMemWhenDoneByRef(&St, x);
1332 int mySub(int, int);
1333 int myAdd(int, int);
1334 int fPtr(unsigned cond, int x) {
1335 return (cond ? mySub : myAdd)(x, x);
1338 // Test anti-aliasing.
1340 void dependsOnValueOfPtr(int *g, unsigned f) {
1352 return; // no warning
1356 int CMPRegionHeapToStack() {
1358 int *x1 = malloc(8);
1360 clang_analyzer_eval(x1 == x2); // expected-warning{{FALSE}}
1365 int CMPRegionHeapToHeap2() {
1367 int *x1 = malloc(8);
1368 int *x2 = malloc(8);
1371 clang_analyzer_eval(x4 == x5); // expected-warning{{FALSE}}
1377 int CMPRegionHeapToHeap() {
1379 int *x1 = malloc(8);
1383 return 5/x; // expected-warning{{Division by zero}}
1385 return x;// expected-warning{{This statement is never executed}}
1388 int HeapAssignment() {
1393 clang_analyzer_eval(*x != *y); // expected-warning{{FALSE}}
1399 int *retPtrMightAlias(int *x);
1400 int cmpHeapAllocationToUnknown() {
1402 int *yBefore = retPtr();
1404 int *yAfter = retPtrMightAlias(m);
1405 clang_analyzer_eval(yBefore == m); // expected-warning{{FALSE}}
1406 clang_analyzer_eval(yAfter == m); // expected-warning{{FALSE}}
1411 void localArrayTest() {
1412 char *p = (char*)malloc(12);
1415 } // expected-warning {{leak}}
1417 void localStructTest() {
1419 StructWithPtr *pSt = &St;
1420 pSt->memP = malloc(12);
1421 } // expected-warning{{Potential leak of memory pointed to by}}
1423 #ifdef __INTPTR_TYPE__
1424 // Test double assignment through integers.
1425 typedef __INTPTR_TYPE__ intptr_t;
1426 typedef unsigned __INTPTR_TYPE__ uintptr_t;
1428 static intptr_t glob;
1429 void test_double_assign_ints()
1431 void *ptr = malloc (16); // no-warning
1432 glob = (intptr_t)(uintptr_t)ptr;
1435 void test_double_assign_ints_positive()
1437 void *ptr = malloc(16);
1438 (void*)(intptr_t)(uintptr_t)ptr; // expected-warning {{unused}}
1439 } // expected-warning {{leak}}
1442 void testCGContextNoLeak()
1444 void *ptr = malloc(16);
1445 CGContextRef context = CGBitmapContextCreate(ptr);
1447 // Because you can get the data back out like this, even much later,
1448 // CGBitmapContextCreate is one of our "stop-tracking" exceptions.
1449 free(CGBitmapContextGetData(context));
1452 void testCGContextLeak()
1454 void *ptr = malloc(16);
1455 CGContextRef context = CGBitmapContextCreate(ptr);
1456 // However, this time we're just leaking the data, because the context
1457 // object doesn't escape and it hasn't been freed in this function.
1460 // Allow xpc context to escape. radar://11635258
1461 // TODO: Would be great if we checked that the finalize_connection_context actually releases it.
1462 static void finalize_connection_context(void *ctx) {
1466 void foo (xpc_connection_t peer) {
1467 int *ctx = calloc(1, sizeof(int));
1468 xpc_connection_set_context(peer, ctx);
1469 xpc_connection_set_finalizer_f(peer, finalize_connection_context);
1470 xpc_connection_resume(peer);
1473 // Make sure we catch errors when we free in a function which does not allocate memory.
1474 void freeButNoMalloc(int *p, int x){
1477 //user forgot a return here.
1479 free(p); // expected-warning {{Attempt to free released memory}}
1486 char* reallocButNoMalloc(struct HasPtr *a, int c, int size) {
1488 char *b = realloc(a->p, size);
1489 char *m = realloc(a->p, size); // expected-warning {{Attempt to free released memory}}
1490 // We don't expect a use-after-free for a->P here because the warning above
1492 return a->p; // no-warning
1495 // We should not warn in this case since the caller will presumably free a->p in all cases.
1496 int reallocButNoMallocPR13674(struct HasPtr *a, int c, int size) {
1498 char *b = realloc(a->p, size);
1505 // Test realloc with no visible malloc.
1506 void *test(void *ptr) {
1507 void *newPtr = realloc(ptr, 4);
1510 free(ptr); // no-warning
1516 char *testLeakWithinReturn(char *str) {
1517 return strdup(strdup(str)); // expected-warning{{leak}}
1520 char *testWinLeakWithinReturn(char *str) {
1521 return _strdup(_strdup(str)); // expected-warning{{leak}}
1524 wchar_t *testWinWideLeakWithinReturn(wchar_t *str) {
1525 return _wcsdup(_wcsdup(str)); // expected-warning{{leak}}
1528 void passConstPtr(const char * ptr);
1530 void testPassConstPointer() {
1531 char * string = malloc(sizeof(char)*10);
1532 passConstPtr(string);
1533 return; // expected-warning {{leak}}
1536 void testPassConstPointerIndirectly() {
1537 char *p = malloc(1);
1539 memcmp(p, p, sizeof(&p));
1540 return; // expected-warning {{leak}}
1543 void testPassConstPointerIndirectlyStruct() {
1546 memcmp(&hp, &hp, sizeof(hp));
1547 return; // expected-warning {{Potential leak of memory pointed to by 'hp.p'}}
1550 void testPassToSystemHeaderFunctionIndirectlyStruct() {
1553 fakeSystemHeaderCall(&ss); // invalidates ss, making ss.p unreachable
1554 // Technically a false negative here -- we know the system function won't free
1555 // ss.p, but nothing else will either!
1558 void testPassToSystemHeaderFunctionIndirectlyStructFree() {
1561 fakeSystemHeaderCall(&ss); // invalidates ss, making ss.p unreachable
1565 void testPassToSystemHeaderFunctionIndirectlyArray() {
1567 p[0] = malloc(sizeof(int));
1568 fakeSystemHeaderCallIntPtr(p); // invalidates p, making p[0] unreachable
1569 // Technically a false negative here -- we know the system function won't free
1570 // p[0], but nothing else will either!
1573 void testPassToSystemHeaderFunctionIndirectlyArrayFree() {
1575 p[0] = malloc(sizeof(int));
1576 fakeSystemHeaderCallIntPtr(p); // invalidates p, making p[0] unreachable
1580 int *testOffsetAllocate(size_t size) {
1581 int *memoryBlock = (int *)malloc(size + sizeof(int));
1582 return &memoryBlock[1]; // no-warning
1585 void testOffsetDeallocate(int *memoryBlock) {
1586 free(&memoryBlock[-1]); // no-warning
1589 void testOffsetOfRegionFreed() {
1590 __int64_t * array = malloc(sizeof(__int64_t)*2);
1592 free(&array[0]); // expected-warning{{Argument to free() is offset by 8 bytes from the start of memory allocated by malloc()}}
1595 void testOffsetOfRegionFreed2() {
1596 __int64_t *p = malloc(sizeof(__int64_t)*2);
1598 free(p); // expected-warning{{Argument to free() is offset by 8 bytes from the start of memory allocated by malloc()}}
1601 void testOffsetOfRegionFreed3() {
1602 char *r = malloc(sizeof(char));
1604 free(r); // expected-warning {{Argument to free() is offset by -10 bytes from the start of memory allocated by malloc()}}
1607 void testOffsetOfRegionFreedAfterFunctionCall() {
1608 int *p = malloc(sizeof(int)*2);
1611 free(p); // expected-warning{{Argument to free() is offset by 4 bytes from the start of memory allocated by malloc()}}
1614 void testFixManipulatedPointerBeforeFree() {
1615 int * array = malloc(sizeof(int)*2);
1617 free(&array[-1]); // no-warning
1620 void testFixManipulatedPointerBeforeFree2() {
1621 char *r = malloc(sizeof(char));
1623 free(r-10); // no-warning
1626 void freeOffsetPointerPassedToFunction() {
1627 __int64_t *p = malloc(sizeof(__int64_t)*2);
1630 myfooint(*p); // not passing the pointer, only a value pointed by pointer
1631 free(p); // expected-warning {{Argument to free() is offset by 8 bytes from the start of memory allocated by malloc()}}
1635 void freeUnknownOffsetPointer() {
1636 char *r = malloc(sizeof(char));
1637 r = r + arbitraryInt(); // unable to reason about what the offset might be
1638 free(r); // no-warning
1641 void testFreeNonMallocPointerWithNoOffset() {
1645 free(r-10); // expected-warning {{Argument to free() is the address of the local variable 'c', which is not memory allocated by malloc()}}
1648 void testFreeNonMallocPointerWithOffset() {
1651 free(r+1); // expected-warning {{Argument to free() is the address of the local variable 'c', which is not memory allocated by malloc()}}
1654 void testOffsetZeroDoubleFree() {
1655 int *array = malloc(sizeof(int)*2);
1658 free(&array[0]); // expected-warning{{Attempt to free released memory}}
1661 void testOffsetPassedToStrlen() {
1662 char * string = malloc(sizeof(char)*10);
1664 int length = strlen(string); // expected-warning {{Potential leak of memory pointed to by 'string'}}
1667 void testOffsetPassedToStrlenThenFree() {
1668 char * string = malloc(sizeof(char)*10);
1670 int length = strlen(string);
1671 free(string); // expected-warning {{Argument to free() is offset by 1 byte from the start of memory allocated by malloc()}}
1674 void testOffsetPassedAsConst() {
1675 char * string = malloc(sizeof(char)*10);
1677 passConstPtr(string);
1678 free(string); // expected-warning {{Argument to free() is offset by 1 byte from the start of memory allocated by malloc()}}
1681 char **_vectorSegments;
1682 int _nVectorSegments;
1684 void poolFreeC(void* s) {
1685 free(s); // no-warning
1688 while (_nVectorSegments) {
1689 poolFreeC(_vectorSegments[_nVectorSegments++]);
1694 void testReallocEscaped(void **memory) {
1695 *memory = malloc(47);
1696 char *new_memory = realloc(*memory, 47);
1697 if (new_memory != 0) {
1698 *memory = new_memory;
1703 void *smallocNoWarn(size_t size) {
1705 return malloc(1); // this branch is never called
1708 return malloc(size);
1712 char *dupstrNoWarn(const char *s) {
1713 const int len = strlen(s);
1714 char *p = (char*) smallocNoWarn(len + 1);
1715 strcpy(p, s); // no-warning
1719 void *smallocWarn(size_t size) {
1724 return malloc(size);
1728 int *radar15580979() {
1729 int *data = (int *)malloc(32);
1730 int *p = data ?: (int*)malloc(32); // no warning
1734 // Some data structures may hold onto the pointer and free it later.
1735 void testEscapeThroughSystemCallTakingVoidPointer1(void *queue) {
1736 int *data = (int *)malloc(32);
1737 fake_insque(queue, data); // no warning
1740 void testEscapeThroughSystemCallTakingVoidPointer2(fake_rb_tree_t *rbt) {
1741 int *data = (int *)malloc(32);
1742 fake_rb_tree_init(rbt, data);
1743 } //expected-warning{{Potential leak}}
1745 void testEscapeThroughSystemCallTakingVoidPointer3(fake_rb_tree_t *rbt) {
1746 int *data = (int *)malloc(32);
1747 fake_rb_tree_init(rbt, data);
1748 fake_rb_tree_insert_node(rbt, data); // no warning
1756 void constEscape(const void *ptr);
1758 void testConstEscapeThroughAnotherField() {
1760 s.p = malloc(sizeof(int));
1761 constEscape(&(s.x)); // could free s->p!
1765 int testNoCheckerDataPropogationFromLogicalOpOperandToOpResult(void) {
1766 char *param = malloc(10);
1767 char *value = malloc(10);
1768 int ok = (param && value);
1771 // Previously we ended up with 'Use of memory after it is freed' on return.
1772 return ok; // no warning
1776 void freeIndirectFunctionPtr() {
1777 void *p = (void *)fnptr;
1778 free(p); // expected-warning {{Argument to free() is a function pointer}}
1781 void freeFunctionPtr() {
1782 free((void *)fnptr); // expected-warning {{Argument to free() is a function pointer}}
1785 void allocateSomeMemory(void *offendingParameter, void **ptr) {
1789 void testNoCrashOnOffendingParameter() {
1790 // "extern" is necessary to avoid unrelated warnings
1791 // on passing uninitialized value.
1792 extern void *offendingParameter;
1794 allocateSomeMemory(offendingParameter, &ptr);
1795 } // expected-warning {{Potential leak of memory pointed to by 'ptr'}}
1797 // ----------------------------------------------------------------------------
1800 void testMallocWithParam(int **p) {
1801 *p = (int*) malloc(sizeof(int));
1802 *p = 0; // FIXME: should warn here
1805 void testMallocWithParam_2(int **p) {
1806 *p = (int*) malloc(sizeof(int)); // no-warning
1809 void testPassToSystemHeaderFunctionIndirectly() {
1812 fakeSystemHeaderCallInt(p);
1813 // FIXME: This is a leak: if we think a system function won't free p, it
1814 // won't free (p-1) either.
1817 void testMallocIntoMalloc() {
1818 StructWithPtr *s = malloc(sizeof(StructWithPtr));
1819 s->memP = malloc(sizeof(int));
1821 } // FIXME: should warn here