1 // RUN: %clang_analyze_cc1 -Wno-strict-prototypes -Wno-error=implicit-int -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 \
7 // RUN: -analyzer-checker=alpha.security.taint.TaintPropagation \
8 // RUN: -analyzer-checker=optin.taint.TaintedAlloc
10 #include "Inputs/system-header-simulator.h"
12 void clang_analyzer_eval(int);
13 void clang_analyzer_dump(int);
14 void clang_analyzer_dumpExtent(void *);
16 // Without -fms-compatibility, wchar_t isn't a builtin type. MSVC defines
17 // _WCHAR_T_DEFINED if wchar_t is available. Microsoft recommends that you use
18 // the builtin type: "Using the typedef version can cause portability
19 // problems", but we're ok here because we're not actually running anything.
20 // Also of note is this cryptic warning: "The wchar_t type is not supported
21 // when you compile C code".
23 // See the docs for more:
24 // https://msdn.microsoft.com/en-us/library/dh8che7s.aspx
25 #if !defined(_WCHAR_T_DEFINED)
26 // "Microsoft implements wchar_t as a two-byte unsigned value"
27 typedef unsigned short wchar_t;
28 #define _WCHAR_T_DEFINED
29 #endif // !defined(_WCHAR_T_DEFINED)
31 typedef __typeof(sizeof(int)) size_t;
36 void *realloc(void *ptr
, size_t size
);
37 void *reallocf(void *ptr
, size_t size
);
38 void *calloc(size_t nmemb
, size_t size
);
39 char *strdup(const char *s
);
40 wchar_t *wcsdup(const wchar_t *s
);
41 char *strndup(const char *s
, size_t n
);
42 int memcmp(const void *s1
, const void *s2
, size_t n
);
45 char *_strdup(const char *strSource
);
46 wchar_t *_wcsdup(const wchar_t *strSource
);
47 void *_alloca(size_t size
);
51 char *fooRetPtr(void);
56 int *p
= malloc(size
); // expected-warning{{malloc is called with a tainted (potentially attacker controlled) value}}
63 int *p
= calloc(size
,2); // expected-warning{{calloc is called with a tainted (potentially attacker controlled) value}}
72 int *p
= malloc(size
); // No warning expected as the the user input is bound
78 int *p
= malloc(sizeof(int));
80 p
= (int*) realloc((void*) p
, size
); // expected-warning{{realloc is called with a tainted (potentially attacker controlled) value}}
86 int *p
= alloca(sizeof(int));
88 p
= (int*) alloca(size
); // expected-warning{{alloca is called with a tainted (potentially attacker controlled) value}}
94 return; // expected-warning{{Potential leak of memory pointed to by 'p'}}
100 free(p
); // expected-warning{{Attempt to free released memory}}
103 void f2_realloc_0(void) {
106 realloc(p
,0); // expected-warning{{Attempt to free released memory}}
109 void f2_realloc_1(void) {
111 int *q
= realloc(p
,0); // no-warning
114 void reallocNotNullPtr(unsigned sizeIn
) {
116 char *p
= (char*)malloc(size
);
118 char *q
= (char*)realloc(p
, sizeIn
);
119 char x
= *q
; // expected-warning {{Potential leak of memory pointed to by 'q'}}
123 void allocaTest(void) {
124 int *p
= alloca(sizeof(int));
127 void winAllocaTest(void) {
128 int *p
= _alloca(sizeof(int));
131 void allocaBuiltinTest(void) {
132 int *p
= __builtin_alloca(sizeof(int));
135 int *realloctest1(void) {
138 return q
; // no warning - returning the allocated value
141 // p should be freed if realloc fails.
142 void reallocFails(void) {
143 char *p
= malloc(12);
144 char *r
= realloc(p
, 12+1);
152 void reallocSizeZero1(void) {
153 char *p
= malloc(12);
154 char *r
= realloc(p
, 0);
156 free(p
); // expected-warning {{Attempt to free released memory}}
162 void reallocSizeZero2(void) {
163 char *p
= malloc(12);
164 char *r
= realloc(p
, 0);
166 free(p
); // expected-warning {{Attempt to free released memory}}
170 free(p
); // expected-warning {{Attempt to free released memory}}
173 void reallocSizeZero3(void) {
174 char *p
= malloc(12);
175 char *r
= realloc(p
, 0);
179 void reallocSizeZero4(void) {
180 char *r
= realloc(0, 0);
184 void reallocSizeZero5(void) {
185 char *r
= realloc(0, 0);
188 void reallocPtrZero1(void) {
189 char *r
= realloc(0, 12);
190 } // expected-warning {{Potential leak of memory pointed to by 'r'}}
192 void reallocPtrZero2(void) {
193 char *r
= realloc(0, 12);
198 void reallocPtrZero3(void) {
199 char *r
= realloc(0, 12);
203 void reallocRadar6337483_1(void) {
204 char *buf
= malloc(100);
205 buf
= (char*)realloc(buf
, 0x1000000);
207 return;// expected-warning {{Potential leak of memory pointed to by}}
212 void reallocRadar6337483_2(void) {
213 char *buf
= malloc(100);
214 char *buf2
= (char*)realloc(buf
, 0x1000000);
220 } // expected-warning {{Potential leak of memory pointed to by}}
222 void reallocRadar6337483_3(void) {
223 char * buf
= malloc(100);
225 tmp
= (char*)realloc(buf
, 0x1000000);
234 void reallocRadar6337483_4(void) {
235 char *buf
= malloc(100);
236 char *buf2
= (char*)realloc(buf
, 0x1000000);
238 return; // expected-warning {{Potential leak of memory pointed to by}}
244 int *reallocfTest1(void) {
247 return q
; // no warning - returning the allocated value
250 void reallocfRadar6337483_4(void) {
251 char *buf
= malloc(100);
252 char *buf2
= (char*)reallocf(buf
, 0x1000000);
254 return; // no warning - reallocf frees even on failure
260 void reallocfRadar6337483_3(void) {
261 char * buf
= malloc(100);
263 tmp
= (char*)reallocf(buf
, 0x1000000);
265 free(buf
); // expected-warning {{Attempt to free released memory}}
272 void reallocfPtrZero1(void) {
273 char *r
= reallocf(0, 12);
274 } // expected-warning {{Potential leak of memory pointed to by}}
276 //------------------- Check usage of zero-allocated memory ---------------------
277 void CheckUseZeroAllocatedNoWarn1(void) {
279 free(p
); // no warning
282 void CheckUseZeroAllocatedNoWarn2(void) {
283 int *p
= alloca(0); // no warning
286 void CheckUseZeroWinAllocatedNoWarn2(void) {
287 int *p
= _alloca(0); // no warning
291 void CheckUseZeroAllocatedNoWarn3(void) {
293 int *q
= realloc(p
, 8); // no warning
297 void CheckUseZeroAllocatedNoWarn4(void) {
298 int *p
= realloc(0, 8);
299 *p
= 1; // no warning
303 void CheckUseZeroAllocated1(void) {
305 *p
= 1; // expected-warning {{Use of memory allocated with size zero}}
309 char CheckUseZeroAllocated2(void) {
310 // NOTE: The `AllocaRegion` that models the return value of `alloca()`
311 // doesn't have an associated symbol, so the current implementation of
312 // `MallocChecker::checkUseZeroAllocated()` cannot provide warnings for it.
313 // However, other checkers like core.uninitialized.UndefReturn (that
314 // activates in these TCs) or the array bound checkers provide more generic,
315 // but still sufficient warnings in these cases, so I think it isn't
316 // important to cover this in MallocChecker.
318 return *p
; // expected-warning {{Undefined or garbage value returned to caller}}
321 char CheckUseZeroWinAllocated2(void) {
322 // Note: Same situation as `CheckUseZeroAllocated2()`.
323 char *p
= _alloca(0);
324 return *p
; // expected-warning {{Undefined or garbage value returned to caller}}
327 void UseZeroAllocated(int *p
) {
329 *p
= 7; // expected-warning {{Use of memory allocated with size zero}}
331 void CheckUseZeroAllocated3(void) {
337 void CheckUseZeroAllocated4(void) {
339 f(*p
); // expected-warning {{Use of memory allocated with size zero}}
343 void CheckUseZeroAllocated5(void) {
344 int *p
= calloc(0, 2);
345 *p
= 1; // expected-warning {{Use of memory allocated with size zero}}
349 void CheckUseZeroAllocated6(void) {
350 int *p
= calloc(2, 0);
351 *p
= 1; // expected-warning {{Use of memory allocated with size zero}}
355 void CheckUseZeroAllocated7(void) {
356 int *p
= realloc(0, 0);
357 *p
= 1; // expected-warning {{Use of memory allocated with size zero}}
361 void CheckUseZeroAllocated8(void) {
363 int *q
= realloc(p
, 0);
364 *q
= 1; // expected-warning {{Use of memory allocated with size zero}}
368 void CheckUseZeroAllocated9(void) {
369 int *p
= realloc(0, 0);
370 int *q
= realloc(p
, 0);
371 *q
= 1; // expected-warning {{Use of memory allocated with size zero}}
375 void CheckUseZeroAllocatedPathNoWarn(_Bool b
) {
383 *p
= 1; // no warning
388 void CheckUseZeroAllocatedPathWarn(_Bool b
) {
396 *p
= 1; // expected-warning {{Use of memory allocated with size zero}}
401 void CheckUseZeroReallocatedPathNoWarn(_Bool b
) {
407 char *q
= realloc(p
, s
);
410 *q
= 1; // no warning
415 void CheckUseZeroReallocatedPathWarn(_Bool b
) {
421 char *q
= realloc(p
, s
);
424 *q
= 1; // expected-warning {{Use of memory allocated with size zero}}
429 // This case tests that storing malloc'ed memory to a static variable which is
430 // then returned is not leaked. In the absence of known contracts for functions
431 // or inter-procedural analysis, this is a conservative answer.
435 return p
; // no-warning
438 // This case tests that storing malloc'ed memory to a static global variable
439 // which is then returned is not leaked. In the absence of known contracts for
440 // functions or inter-procedural analysis, this is a conservative answer.
441 static int *p_f4
= 0;
444 return p_f4
; // no-warning
450 return q
; // no-warning
456 return; // no-warning
461 void f6_realloc(void) {
464 return; // no-warning
481 char *x
= (char*) malloc(4);
483 x
[0] = 'a'; // expected-warning{{Use of memory after it is freed}}
487 char *x
= (char*) malloc(4);
489 char *y
= strndup(x
, 4); // expected-warning{{Use of memory after it is freed}}
492 void f7_realloc(void) {
493 char *x
= (char*) malloc(4);
495 x
[0] = 'a'; // expected-warning{{Use of memory after it is freed}}
499 int *x
= malloc(11); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
503 int *buf
= malloc(2); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
504 buf
[1] = 'c'; // not crash
507 void cast_emtpy_struct(void) {
511 struct st
*s
= malloc(sizeof(struct st
)); // no-warning
515 void cast_struct_1(void) {
521 struct st
*s
= malloc(sizeof(struct st
)); // no-warning
525 void cast_struct_2(void) {
531 struct st
*s
= malloc(sizeof(struct st
)); // no-warning
535 void cast_struct_3(void) {
541 struct st
*s
= malloc(sizeof(struct st
)); // no-warning
545 void cast_struct_4(void) {
551 struct st
*s
= malloc(sizeof(struct st
)); // no-warning
555 void cast_struct_5(void) {
561 struct st
*s
= malloc(sizeof(struct st
) - sizeof(char)); // no-warning
565 void cast_struct_warn_1(void) {
571 struct st
*s
= malloc(sizeof(struct st
) + 2); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
575 void cast_struct_warn_2(void) {
581 struct st
*s
= malloc(2); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
585 void cast_struct_flex_array_1(void) {
591 struct st
*s
= malloc(sizeof(struct st
) + 3); // no-warning
595 void cast_struct_flex_array_2(void) {
601 struct st
*s
= malloc(sizeof(struct st
) + 3); // no-warning
605 void cast_struct_flex_array_3(void) {
611 struct st
*s
= malloc(sizeof(struct st
) + 3); // no-warning
615 void cast_struct_flex_array_4(void) {
624 struct st
*s
= malloc(sizeof(struct st
) + 3 * sizeof(struct foo
)); // no-warning
628 void cast_struct_flex_array_5(void) {
637 struct st
*s
= malloc(sizeof(struct st
) + 3 * sizeof(struct foo
)); // no-warning
641 void cast_struct_flex_array_6(void) {
650 struct st
*s
= malloc(sizeof(struct st
) + 3 * sizeof(struct foo
)); // no-warning
654 void cast_struct_flex_array_warn_1(void) {
663 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}}
667 void cast_struct_flex_array_warn_2(void) {
676 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}}
680 void cast_struct_flex_array_warn_3(void) {
689 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}}
693 void cast_struct_flex_array_warn_4(void) {
699 struct st
*s
= malloc(sizeof(struct st
) + 3); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
703 void cast_struct_flex_array_warn_5(void) {
709 struct st
*s
= malloc(sizeof(struct st
) + 3); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
713 void cast_struct_flex_array_warn_6(void) {
719 struct st
*s
= malloc(sizeof(struct st
) + 3); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
723 void mallocCastToVoid(void) {
725 const void *cp
= p
; // not crash
729 void mallocCastToFP(void) {
731 void (*fp
)(void) = p
; // not crash
735 // This tests that 'malloc()' buffers are undefined by default
736 char mallocGarbage (void) {
737 char *buf
= malloc(2);
738 char result
= buf
[1]; // expected-warning{{undefined}}
743 // This tests that calloc() buffers need to be freed
744 void callocNoFree (void) {
745 char *buf
= calloc(2,2);
746 return; // expected-warning{{Potential leak of memory pointed to by 'buf'}}
749 // These test that calloc() buffers are zeroed by default
750 char callocZeroesGood (void) {
751 char *buf
= calloc(2,2);
752 char result
= buf
[3]; // no-warning
756 return result
; // no-warning
759 char callocZeroesBad (void) {
760 char *buf
= calloc(2,2);
761 char result
= buf
[3]; // no-warning
763 free(buf
); // expected-warning{{never executed}}
765 return result
; // expected-warning{{Potential leak of memory pointed to by 'buf'}}
768 void nullFree(void) {
770 free(p
); // no warning - a nop
773 void paramFree(int *p
) {
775 free(p
); // no warning
776 myfoo(p
); // expected-warning {{Use of memory after it is freed}}
779 void allocaFree(void) {
780 int *p
= alloca(sizeof(int));
781 free(p
); // expected-warning {{Memory allocated by 'alloca()' should not be deallocated}}
784 void allocaFreeBuiltin(void) {
785 int *p
= __builtin_alloca(sizeof(int));
786 free(p
); // expected-warning {{Memory allocated by 'alloca()' should not be deallocated}}
789 void allocaFreeBuiltinAlign(void) {
790 int *p
= __builtin_alloca_with_align(sizeof(int), 64);
791 free(p
); // expected-warning {{Memory allocated by 'alloca()' should not be deallocated}}
795 int* mallocEscapeRet(void) {
797 return p
; // no warning
800 void mallocEscapeFoo(void) {
803 return; // no warning
806 void mallocEscapeFree(void) {
812 void mallocEscapeFreeFree(void) {
816 free(p
); // expected-warning{{Attempt to free released memory}}
819 void mallocEscapeFreeUse(void) {
823 myfoo(p
); // expected-warning{{Use of memory after it is freed}}
827 void myalloc2(int **p
);
829 void mallocEscapeFreeCustomAlloc(void) {
834 free(p
); // no warning
837 void mallocEscapeFreeCustomAlloc2(void) {
842 free(p
); // no warning
845 void mallocBindFreeUse(void) {
849 myfoo(x
); // expected-warning{{Use of memory after it is freed}}
852 void mallocEscapeMalloc(void) {
856 } // expected-warning{{Potential leak of memory pointed to by}}
858 void mallocMalloc(void) {
861 } // expected-warning {{Potential leak of memory pointed to by}}\
862 // expected-warning {{Potential leak of memory pointed to by}}
864 void mallocFreeMalloc(void) {
871 void mallocFreeUse_params(void) {
874 myfoo(p
); //expected-warning{{Use of memory after it is freed}}
877 void mallocFreeUse_params2(void) {
880 myfooint(*p
); //expected-warning{{Use of memory after it is freed}}
883 void mallocFailedOrNot(void) {
891 struct StructWithInt
{
895 int *mallocReturnFreed(void) {
898 return p
; // expected-warning {{Use of memory after it is freed}}
901 int useAfterFreeStruct(void) {
902 struct StructWithInt
*px
= malloc(sizeof(struct StructWithInt
));
905 return px
->g
; // expected-warning {{Use of memory after it is freed}}
908 void nonSymbolAsFirstArg(int *pp
, struct StructWithInt
*p
);
910 void mallocEscapeFooNonSymbolArg(void) {
911 struct StructWithInt
*p
= malloc(sizeof(struct StructWithInt
));
912 nonSymbolAsFirstArg(&p
->g
, p
);
913 return; // no warning
916 void mallocFailedOrNotLeak(void) {
919 return; // no warning
921 return; // expected-warning {{Potential leak of memory pointed to by}}
924 void mallocAssignment(void) {
925 char *p
= malloc(12);
927 } // expected-warning {{leak}}
929 int vallocTest(void) {
930 char *mem
= valloc(12);
931 return 0; // expected-warning {{Potential leak of memory pointed to by}}
934 void vallocEscapeFreeUse(void) {
938 myfoo(p
); // expected-warning{{Use of memory after it is freed}}
946 struct GlStTy GlS
= {0};
948 void GlobalFree(void) {
952 void GlobalMalloc(void) {
956 void GlobalStructMalloc(void) {
961 void GlobalStructMallocFree(void) {
969 void globalArrayTest(void) {
970 char *p
= (char*)malloc(12);
974 // Make sure that we properly handle a pointer stored into a local struct/array.
975 typedef struct _StructWithPtr
{
979 static StructWithPtr arrOfStructs
[10];
981 void testMalloc(void) {
985 arrOfStructs
[0] = St
; // no-warning
988 StructWithPtr
testMalloc2(void) {
992 return St
; // no-warning
995 int *testMalloc3(void) {
998 return y
; // no-warning
1001 void testStructLeak(void) {
1003 St
.memP
= malloc(12);
1004 return; // expected-warning {{Potential leak of memory pointed to by 'St.memP'}}
1007 void testElemRegion1(void) {
1008 char *x
= (void*)malloc(2);
1013 void testElemRegion2(int **pp
) {
1014 int *p
= malloc(12);
1019 void testElemRegion3(int **pp
) {
1020 int *p
= malloc(12);
1024 // Region escape testing.
1026 unsigned takePtrToPtr(int **p
);
1027 void PassTheAddrOfAllocatedData(int f
) {
1028 int *p
= malloc(12);
1029 // We don't know what happens after the call. Should stop tracking here.
1030 if (takePtrToPtr(&p
))
1032 free(p
); // no warning
1038 unsigned takePtrToStruct(struct X
*s
);
1039 int ** foo2(int *g
, int f
) {
1040 int *p
= malloc(12);
1041 struct X
*px
= malloc(sizeof(struct X
));
1043 // We don't know what happens after this call. Should not track px nor p.
1044 if (takePtrToStruct(px
))
1050 struct X
* RegInvalidationDetect1(struct X
*s2
) {
1051 struct X
*px
= malloc(sizeof(struct X
));
1054 return px
; // expected-warning {{Potential leak of memory pointed to by}}
1057 struct X
* RegInvalidationGiveUp1(void) {
1058 int *p
= malloc(12);
1059 struct X
*px
= malloc(sizeof(struct X
));
1064 int **RegInvalidationDetect2(int **pp
) {
1065 int *p
= malloc(12);
1068 return 0;// expected-warning {{Potential leak of memory pointed to by}}
1071 extern void exit(int) __attribute__ ((__noreturn__
));
1072 void mallocExit(int *g
) {
1073 struct xx
*p
= malloc(12);
1080 extern void __assert_fail (__const
char *__assertion
, __const
char *__file
,
1081 unsigned int __line
, __const
char *__function
)
1082 __attribute__ ((__noreturn__
));
1083 #define assert(expr) \
1084 ((expr) ? (void)(0) : __assert_fail (#expr, __FILE__, __LINE__, __func__))
1085 void mallocAssert(int *g
) {
1086 struct xx
*p
= malloc(12);
1093 void doNotInvalidateWhenPassedToSystemCalls(char *s
) {
1094 char *p
= malloc(12);
1102 } // expected-warning {{leak}}
1104 // Treat source buffer contents as escaped.
1105 void escapeSourceContents(char *s
) {
1106 char *p
= malloc(12);
1107 memcpy(s
, &p
, 12); // no warning
1109 void *p1
= malloc(7);
1111 memcpy(&a
, &p1
, sizeof a
);
1112 // FIXME: No warning due to limitations imposed by current modelling of
1113 // 'memcpy' (regions metadata is not copied).
1116 int *allocated
= (int *)malloc(4);
1117 memcpy(&ptrs
[0], &allocated
, sizeof(int *));
1118 // FIXME: No warning due to limitations imposed by current modelling of
1119 // 'memcpy' (regions metadata is not copied).
1122 void invalidateDestinationContents(void) {
1124 int *p
= (int *)malloc(4);
1125 memcpy(&p
, &null
, sizeof(int *));
1127 int *ptrs1
[2]; // expected-warning {{Potential leak of memory pointed to by}}
1128 ptrs1
[0] = (int *)malloc(4);
1129 memcpy(ptrs1
, &null
, sizeof(int *));
1131 int *ptrs2
[2]; // expected-warning {{Potential memory leak}}
1132 ptrs2
[0] = (int *)malloc(4);
1133 memcpy(&ptrs2
[1], &null
, sizeof(int *));
1135 int *ptrs3
[2]; // expected-warning {{Potential memory leak}}
1136 ptrs3
[0] = (int *)malloc(4);
1137 memcpy(&ptrs3
[0], &null
, sizeof(int *));
1138 } // expected-warning {{Potential memory leak}}
1140 // Rely on the CString checker evaluation of the strcpy API to convey that the result of strcpy is equal to p.
1141 void symbolLostWithStrcpy(char *s
) {
1142 char *p
= malloc(12);
1148 // The same test as the one above, but with what is actually generated on a mac.
1149 static __inline
char *
1150 __inline_strcpy_chk (char *restrict __dest
, const char *restrict __src
)
1152 return __builtin___strcpy_chk (__dest
, __src
, __builtin_object_size (__dest
, 2 > 1));
1155 void symbolLostWithStrcpy_InlineStrcpyVersion(char *s
) {
1156 char *p
= malloc(12);
1157 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
));
1161 // Here we are returning a pointer one past the allocated value. An idiom which
1162 // can be used for implementing special malloc. The correct uses of this might
1163 // be rare enough so that we could keep this as a warning.
1164 static void *specialMalloc(int n
){
1174 // Potentially, the user could free the struct by performing pointer arithmetic on the return value.
1175 // This is a variation of the specialMalloc issue, though probably would be more rare in correct code.
1176 int *specialMallocWithStruct(void) {
1177 struct StructWithInt
*px
= malloc(sizeof(struct StructWithInt
));
1181 // Test various allocation/deallocation functions.
1182 void testStrdup(const char *s
, unsigned validIndex
) {
1183 char *s2
= strdup(s
);
1184 s2
[validIndex
+ 1] = 'b';
1185 } // expected-warning {{Potential leak of memory pointed to by}}
1187 void testWinStrdup(const char *s
, unsigned validIndex
) {
1188 char *s2
= _strdup(s
);
1189 s2
[validIndex
+ 1] = 'b';
1190 } // expected-warning {{Potential leak of memory pointed to by}}
1192 void testWcsdup(const wchar_t *s
, unsigned validIndex
) {
1193 wchar_t *s2
= wcsdup(s
);
1194 s2
[validIndex
+ 1] = 'b';
1195 } // expected-warning {{Potential leak of memory pointed to by}}
1197 void testWinWcsdup(const wchar_t *s
, unsigned validIndex
) {
1198 wchar_t *s2
= _wcsdup(s
);
1199 s2
[validIndex
+ 1] = 'b';
1200 } // expected-warning {{Potential leak of memory pointed to by}}
1202 int testStrndup(const char *s
, unsigned validIndex
, unsigned size
) {
1203 char *s2
= strndup(s
, size
);
1204 s2
[validIndex
+ 1] = 'b';
1205 if (s2
[validIndex
] != 'a')
1208 return 1;// expected-warning {{Potential leak of memory pointed to by}}
1211 void testStrdupContentIsDefined(const char *s
, unsigned validIndex
) {
1212 char *s2
= strdup(s
);
1213 char result
= s2
[1];// no warning
1217 void testWinStrdupContentIsDefined(const char *s
, unsigned validIndex
) {
1218 char *s2
= _strdup(s
);
1219 char result
= s2
[1];// no warning
1223 void testWcsdupContentIsDefined(const wchar_t *s
, unsigned validIndex
) {
1224 wchar_t *s2
= wcsdup(s
);
1225 wchar_t result
= s2
[1];// no warning
1229 void testWinWcsdupContentIsDefined(const wchar_t *s
, unsigned validIndex
) {
1230 wchar_t *s2
= _wcsdup(s
);
1231 wchar_t result
= s2
[1];// no warning
1235 // ----------------------------------------------------------------------------
1236 // Test the system library functions to which the pointer can escape.
1237 // This tests false positive suppression.
1239 // For now, we assume memory passed to pthread_specific escapes.
1240 // TODO: We could check that if a new pthread binding is set, the existing
1241 // binding must be freed; otherwise, a memory leak can occur.
1242 void testPthereadSpecificEscape(pthread_key_t key
) {
1243 void *buf
= malloc(12);
1244 pthread_setspecific(key
, buf
); // no warning
1247 // PR12101: Test funopen().
1248 static int releasePtr(void *_ctx
) {
1252 FILE *useFunOpen(void) {
1253 void *ctx
= malloc(sizeof(int));
1254 FILE *f
= funopen(ctx
, 0, 0, 0, releasePtr
); // no warning
1260 FILE *useFunOpenNoReleaseFunction(void) {
1261 void *ctx
= malloc(sizeof(int));
1262 FILE *f
= funopen(ctx
, 0, 0, 0, 0);
1266 return f
; // expected-warning{{leak}}
1269 static int readNothing(void *_ctx
, char *buf
, int size
) {
1272 FILE *useFunOpenReadNoRelease(void) {
1273 void *ctx
= malloc(sizeof(int));
1274 FILE *f
= funopen(ctx
, readNothing
, 0, 0, 0);
1278 return f
; // expected-warning{{leak}}
1281 // Test setbuf, setvbuf.
1282 int my_main_no_warning(void) {
1283 char *p
= malloc(100);
1284 setvbuf(stdout
, p
, 0, 100);
1287 int my_main_no_warning2(void) {
1288 char *p
= malloc(100);
1289 setbuf(__stdoutp
, p
);
1292 int my_main_warn(FILE *f
) {
1293 char *p
= malloc(100);
1294 setvbuf(f
, p
, 0, 100);
1295 return 0;// expected-warning {{leak}}
1298 // some people use stack allocated memory as an optimization to avoid
1299 // a heap allocation for small work sizes. This tests the analyzer's
1300 // understanding that the malloc'ed memory is not the same as stackBuffer.
1301 void radar10978247(int myValueSize
) {
1302 char stackBuffer
[128];
1305 if (myValueSize
<= sizeof(stackBuffer
))
1306 buffer
= stackBuffer
;
1308 buffer
= malloc(myValueSize
);
1310 // do stuff with the buffer
1311 if (buffer
!= stackBuffer
)
1315 void radar10978247_positive(int myValueSize
) {
1316 char stackBuffer
[128];
1319 if (myValueSize
<= sizeof(stackBuffer
))
1320 buffer
= stackBuffer
;
1322 buffer
= malloc(myValueSize
);
1324 // do stuff with the buffer
1325 if (buffer
== stackBuffer
)
1328 return; // expected-warning {{leak}}
1330 // Previously this triggered a false positive because 'malloc()' is known to
1331 // return uninitialized memory and the binding of 'o' to 'p->n' was not getting
1332 // propertly handled. Now we report a leak.
1333 struct rdar11269741_a_t
{
1334 struct rdar11269741_b_t
{
1339 int rdar11269741(struct rdar11269741_b_t o
)
1341 struct rdar11269741_a_t
*p
= (struct rdar11269741_a_t
*) malloc(sizeof(*p
));
1343 return p
->n
.m
; // expected-warning {{leak}}
1346 // Pointer arithmetic, returning an ElementRegion.
1347 void *radar11329382(unsigned bl
) {
1348 void *ptr
= malloc (16);
1349 ptr
= ptr
+ (2 - bl
);
1350 return ptr
; // no warning
1353 void __assert_rtn(const char *, const char *, int, const char *) __attribute__((__noreturn__
));
1354 int strcmp(const char *, const char *);
1356 void radar11270219(void) {
1357 char *x
= a(), *y
= a();
1358 (__builtin_expect(!(x
&& y
), 0) ? __assert_rtn(__func__
, "/Users/zaks/tmp/ex.c", 24, "x && y") : (void)0);
1359 strcmp(x
, y
); // no warning
1362 void radar_11358224_test_double_assign_ints_positive_2(void)
1364 void *ptr
= malloc(16);
1366 } // expected-warning {{leak}}
1368 // Assume that functions which take a function pointer can free memory even if
1369 // they are defined in system headers and take the const pointer to the
1370 // allocated memory.
1371 int const_ptr_and_callback(int, const char*, int n
, void(*)(void*));
1372 void r11160612_1(void) {
1373 char *x
= malloc(12);
1374 const_ptr_and_callback(0, x
, 12, free
); // no - warning
1377 // Null is passed as callback.
1378 void r11160612_2(void) {
1379 char *x
= malloc(12);
1380 const_ptr_and_callback(0, x
, 12, 0);
1381 } // expected-warning {{leak}}
1383 // Callback is passed to a function defined in a system header.
1384 void r11160612_4(void) {
1385 char *x
= malloc(12);
1386 sqlite3_bind_text_my(0, x
, 12, free
); // no - warning
1389 // Passing callbacks in a struct.
1390 void r11160612_5(StWithCallback St
) {
1391 void *x
= malloc(12);
1392 dealocateMemWhenDoneByVal(x
, St
);
1394 void r11160612_6(StWithCallback St
) {
1395 void *x
= malloc(12);
1396 dealocateMemWhenDoneByRef(&St
, x
);
1399 int mySub(int, int);
1400 int myAdd(int, int);
1401 int fPtr(unsigned cond
, int x
) {
1402 return (cond
? mySub
: myAdd
)(x
, x
);
1405 // Test anti-aliasing.
1407 void dependsOnValueOfPtr(int *g
, unsigned f
) {
1419 return; // no warning
1423 int CMPRegionHeapToStack(void) {
1425 int *x1
= malloc(8);
1427 clang_analyzer_eval(x1
== x2
); // expected-warning{{FALSE}}
1432 int CMPRegionHeapToHeap2(void) {
1434 int *x1
= malloc(8);
1435 int *x2
= malloc(8);
1438 clang_analyzer_eval(x4
== x5
); // expected-warning{{FALSE}}
1444 int CMPRegionHeapToHeap(void) {
1446 int *x1
= malloc(8);
1450 return 5/x
; // expected-warning{{Division by zero}}
1452 return x
;// expected-warning{{This statement is never executed}}
1455 int HeapAssignment(void) {
1460 clang_analyzer_eval(*x
!= *y
); // expected-warning{{FALSE}}
1466 int *retPtrMightAlias(int *x
);
1467 int cmpHeapAllocationToUnknown(void) {
1469 int *yBefore
= retPtr();
1471 int *yAfter
= retPtrMightAlias(m
);
1472 clang_analyzer_eval(yBefore
== m
); // expected-warning{{FALSE}}
1473 clang_analyzer_eval(yAfter
== m
); // expected-warning{{FALSE}}
1478 void localArrayTest(void) {
1479 char *p
= (char*)malloc(12);
1482 } // expected-warning {{leak}}
1484 void localStructTest(void) {
1486 StructWithPtr
*pSt
= &St
;
1487 pSt
->memP
= malloc(12);
1488 } // expected-warning{{Potential leak of memory pointed to by}}
1490 #ifdef __INTPTR_TYPE__
1491 // Test double assignment through integers.
1492 typedef __INTPTR_TYPE__
intptr_t;
1493 typedef unsigned __INTPTR_TYPE__
uintptr_t;
1495 static intptr_t glob
;
1496 void test_double_assign_ints(void)
1498 void *ptr
= malloc (16); // no-warning
1499 glob
= (intptr_t)(uintptr_t)ptr
;
1502 void test_double_assign_ints_positive(void)
1504 void *ptr
= malloc(16);
1505 (void*)(intptr_t)(uintptr_t)ptr
; // expected-warning {{unused}}
1506 } // expected-warning {{leak}}
1509 void testCGContextNoLeak(void)
1511 void *ptr
= malloc(16);
1512 CGContextRef context
= CGBitmapContextCreate(ptr
);
1514 // Because you can get the data back out like this, even much later,
1515 // CGBitmapContextCreate is one of our "stop-tracking" exceptions.
1516 free(CGBitmapContextGetData(context
));
1519 void testCGContextLeak(void)
1521 void *ptr
= malloc(16);
1522 CGContextRef context
= CGBitmapContextCreate(ptr
);
1523 // However, this time we're just leaking the data, because the context
1524 // object doesn't escape and it hasn't been freed in this function.
1527 // Allow xpc context to escape.
1528 // TODO: Would be great if we checked that the finalize_connection_context actually releases it.
1529 static void finalize_connection_context(void *ctx
) {
1533 void foo (xpc_connection_t peer
) {
1534 int *ctx
= calloc(1, sizeof(int));
1535 xpc_connection_set_context(peer
, ctx
);
1536 xpc_connection_set_finalizer_f(peer
, finalize_connection_context
);
1537 xpc_connection_resume(peer
);
1540 // Make sure we catch errors when we free in a function which does not allocate memory.
1541 void freeButNoMalloc(int *p
, int x
){
1544 //user forgot a return here.
1546 free(p
); // expected-warning {{Attempt to free released memory}}
1553 char* reallocButNoMalloc(struct HasPtr
*a
, int c
, int size
) {
1555 char *b
= realloc(a
->p
, size
);
1556 char *m
= realloc(a
->p
, size
); // expected-warning {{Attempt to free released memory}}
1557 // We don't expect a use-after-free for a->P here because the warning above
1559 return a
->p
; // no-warning
1562 // We should not warn in this case since the caller will presumably free a->p in all cases.
1563 int reallocButNoMallocPR13674(struct HasPtr
*a
, int c
, int size
) {
1565 char *b
= realloc(a
->p
, size
);
1572 // Test realloc with no visible malloc.
1573 void *test(void *ptr
) {
1574 void *newPtr
= realloc(ptr
, 4);
1577 free(ptr
); // no-warning
1583 char *testLeakWithinReturn(char *str
) {
1584 return strdup(strdup(str
)); // expected-warning{{leak}}
1587 char *testWinLeakWithinReturn(char *str
) {
1588 return _strdup(_strdup(str
)); // expected-warning{{leak}}
1591 wchar_t *testWinWideLeakWithinReturn(wchar_t *str
) {
1592 return _wcsdup(_wcsdup(str
)); // expected-warning{{leak}}
1595 void passConstPtr(const char * ptr
);
1597 void testPassConstPointer(void) {
1598 char * string
= malloc(sizeof(char)*10);
1599 passConstPtr(string
);
1600 return; // expected-warning {{leak}}
1603 void testPassConstPointerIndirectly(void) {
1604 char *p
= malloc(1);
1606 memcmp(p
, p
, sizeof(&p
));
1607 return; // expected-warning {{leak}}
1610 void testPassConstPointerIndirectlyStruct(void) {
1613 memcmp(&hp
, &hp
, sizeof(hp
));
1614 return; // expected-warning {{Potential leak of memory pointed to by 'hp.p'}}
1617 void testPassToSystemHeaderFunctionIndirectlyStruct(void) {
1620 fakeSystemHeaderCall(&ss
); // invalidates ss, making ss.p unreachable
1621 // Technically a false negative here -- we know the system function won't free
1622 // ss.p, but nothing else will either!
1625 void testPassToSystemHeaderFunctionIndirectlyStructFree(void) {
1628 fakeSystemHeaderCall(&ss
); // invalidates ss, making ss.p unreachable
1632 void testPassToSystemHeaderFunctionIndirectlyArray(void) {
1634 p
[0] = malloc(sizeof(int));
1635 fakeSystemHeaderCallIntPtr(p
); // invalidates p, making p[0] unreachable
1636 // Technically a false negative here -- we know the system function won't free
1637 // p[0], but nothing else will either!
1640 void testPassToSystemHeaderFunctionIndirectlyArrayFree(void) {
1642 p
[0] = malloc(sizeof(int));
1643 fakeSystemHeaderCallIntPtr(p
); // invalidates p, making p[0] unreachable
1647 int *testOffsetAllocate(size_t size
) {
1648 int *memoryBlock
= (int *)malloc(size
+ sizeof(int));
1649 return &memoryBlock
[1]; // no-warning
1652 void testOffsetDeallocate(int *memoryBlock
) {
1653 free(&memoryBlock
[-1]); // no-warning
1656 void testOffsetOfRegionFreed(void) {
1657 __int64_t
* array
= malloc(sizeof(__int64_t
)*2);
1659 free(&array
[0]); // expected-warning{{Argument to 'free()' is offset by 8 bytes from the start of memory allocated by 'malloc()'}}
1662 void testOffsetOfRegionFreed2(void) {
1663 __int64_t
*p
= malloc(sizeof(__int64_t
)*2);
1665 free(p
); // expected-warning{{Argument to 'free()' is offset by 8 bytes from the start of memory allocated by 'malloc()'}}
1668 void testOffsetOfRegionFreed3(void) {
1669 char *r
= malloc(sizeof(char));
1671 free(r
); // expected-warning {{Argument to 'free()' is offset by -10 bytes from the start of memory allocated by 'malloc()'}}
1674 void testOffsetOfRegionFreedAfterFunctionCall(void) {
1675 int *p
= malloc(sizeof(int)*2);
1678 free(p
); // expected-warning{{Argument to 'free()' is offset by 4 bytes from the start of memory allocated by 'malloc()'}}
1681 void testFixManipulatedPointerBeforeFree(void) {
1682 int * array
= malloc(sizeof(int)*2);
1684 free(&array
[-1]); // no-warning
1687 void testFixManipulatedPointerBeforeFree2(void) {
1688 char *r
= malloc(sizeof(char));
1690 free(r
-10); // no-warning
1693 void freeOffsetPointerPassedToFunction(void) {
1694 __int64_t
*p
= malloc(sizeof(__int64_t
)*2);
1697 myfooint(*p
); // not passing the pointer, only a value pointed by pointer
1698 free(p
); // expected-warning {{Argument to 'free()' is offset by 8 bytes from the start of memory allocated by 'malloc()'}}
1701 int arbitraryInt(void);
1702 void freeUnknownOffsetPointer(void) {
1703 char *r
= malloc(sizeof(char));
1704 r
= r
+ arbitraryInt(); // unable to reason about what the offset might be
1705 free(r
); // no-warning
1708 void testFreeNonMallocPointerWithNoOffset(void) {
1712 free(r
-10); // expected-warning {{Argument to 'free()' is the address of the local variable 'c', which is not memory allocated by 'malloc()'}}
1715 void testFreeNonMallocPointerWithOffset(void) {
1718 free(r
+1); // expected-warning {{Argument to 'free()' is the address of the local variable 'c', which is not memory allocated by 'malloc()'}}
1721 void testOffsetZeroDoubleFree(void) {
1722 int *array
= malloc(sizeof(int)*2);
1725 free(&array
[0]); // expected-warning{{Attempt to free released memory}}
1728 void testOffsetPassedToStrlen(void) {
1729 char * string
= malloc(sizeof(char)*10);
1731 int length
= strlen(string
); // expected-warning {{Potential leak of memory pointed to by 'string'}}
1734 void testOffsetPassedToStrlenThenFree(void) {
1735 char * string
= malloc(sizeof(char)*10);
1737 int length
= strlen(string
);
1738 free(string
); // expected-warning {{Argument to 'free()' is offset by 1 byte from the start of memory allocated by 'malloc()'}}
1741 void testOffsetPassedAsConst(void) {
1742 char * string
= malloc(sizeof(char)*10);
1744 passConstPtr(string
);
1745 free(string
); // expected-warning {{Argument to 'free()' is offset by 1 byte from the start of memory allocated by 'malloc()'}}
1748 char **_vectorSegments
;
1749 int _nVectorSegments
;
1751 void poolFreeC(void* s
) {
1752 free(s
); // no-warning
1754 void freeMemory(void) {
1755 while (_nVectorSegments
) {
1756 poolFreeC(_vectorSegments
[_nVectorSegments
++]);
1761 void testReallocEscaped(void **memory
) {
1762 *memory
= malloc(47);
1763 char *new_memory
= realloc(*memory
, 47);
1764 if (new_memory
!= 0) {
1765 *memory
= new_memory
;
1770 void *smallocNoWarn(size_t size
) {
1772 return malloc(1); // this branch is never called
1775 return malloc(size
);
1779 char *dupstrNoWarn(const char *s
) {
1780 const int len
= strlen(s
);
1781 char *p
= (char*) smallocNoWarn(len
+ 1);
1782 strcpy(p
, s
); // no-warning
1786 void *smallocWarn(size_t size
) {
1791 return malloc(size
);
1795 int *radar15580979(void) {
1796 int *data
= (int *)malloc(32);
1797 int *p
= data
?: (int*)malloc(32); // no warning
1801 // Some data structures may hold onto the pointer and free it later.
1802 void testEscapeThroughSystemCallTakingVoidPointer1(void *queue
) {
1803 int *data
= (int *)malloc(32);
1804 fake_insque(queue
, data
); // no warning
1807 void testEscapeThroughSystemCallTakingVoidPointer2(fake_rb_tree_t
*rbt
) {
1808 int *data
= (int *)malloc(32);
1809 fake_rb_tree_init(rbt
, data
);
1810 } //expected-warning{{Potential leak}}
1812 void testEscapeThroughSystemCallTakingVoidPointer3(fake_rb_tree_t
*rbt
) {
1813 int *data
= (int *)malloc(32);
1814 fake_rb_tree_init(rbt
, data
);
1815 fake_rb_tree_insert_node(rbt
, data
); // no warning
1823 void constEscape(const void *ptr
);
1825 void testConstEscapeThroughAnotherField(void) {
1827 s
.p
= malloc(sizeof(int));
1828 constEscape(&(s
.x
)); // could free s->p!
1832 int testNoCheckerDataPropogationFromLogicalOpOperandToOpResult(void) {
1833 char *param
= malloc(10);
1834 char *value
= malloc(10);
1835 int ok
= (param
&& value
);
1838 // Previously we ended up with 'Use of memory after it is freed' on return.
1839 return ok
; // no warning
1843 void freeIndirectFunctionPtr(void) {
1844 void *p
= (void *)fnptr
;
1845 free(p
); // expected-warning {{Argument to 'free()' is a function pointer}}
1848 void freeFunctionPtr(void) {
1849 free((void *)fnptr
);
1850 // expected-warning@-1{{Argument to 'free()' is a function pointer}}
1851 // expected-warning@-2{{attempt to call free on non-heap object '(void *)fnptr'}}
1854 void allocateSomeMemory(void *offendingParameter
, void **ptr
) {
1858 void testNoCrashOnOffendingParameter(void) {
1859 // "extern" is necessary to avoid unrelated warnings
1860 // on passing uninitialized value.
1861 extern void *offendingParameter
;
1863 allocateSomeMemory(offendingParameter
, &ptr
);
1864 } // expected-warning {{Potential leak of memory pointed to by 'ptr'}}
1867 // Test a false positive caused by a bug in liveness analysis.
1874 void livenessBugRealloc(struct A
*a
) {
1875 a
->buf
= realloc(a
->buf
, sizeof(int)); // no-warning
1877 void testLivenessBug(struct B
*in_b
) {
1879 livenessBugRealloc(b
->a
);
1880 ((void) 0); // An attempt to trick liveness analysis.
1881 livenessBugRealloc(b
->a
);
1885 struct ListInfo
*next
;
1888 struct ConcreteListItem
{
1893 void list_add(struct ListInfo
*list
, struct ListInfo
*item
);
1895 void testCStyleListItems(struct ListInfo
*list
) {
1896 struct ConcreteListItem
*x
= malloc(sizeof(struct ConcreteListItem
));
1897 list_add(list
, &x
->li
); // will free 'x'.
1900 // MEM34-C. Only free memory allocated dynamically
1901 // Second non-compliant example.
1902 // https://wiki.sei.cmu.edu/confluence/display/c/MEM34-C.+Only+free+memory+allocated+dynamically
1903 enum { BUFSIZE
= 256 };
1905 void MEM34_C(void) {
1907 char *p
= (char *)realloc(buf
, 2 * BUFSIZE
);
1908 // expected-warning@-1{{Argument to 'realloc()' is the address of the local \
1909 variable
'buf', which is
not memory allocated by
'malloc()' [unix
.Malloc
]}}
1915 (*crash_a
)(); // expected-warning{{type specifier missing}}
1916 // A CallEvent without a corresponding FunctionDecl.
1917 crash_b() { crash_a(); } // no-crash
1918 // expected-warning@-1{{type specifier missing}} expected-warning@-1{{non-void}}
1921 void realloc_crash(void) {
1924 realloc(c
, 8); // no-crash
1925 } // expected-warning{{Potential memory leak [unix.Malloc]}}
1927 // ----------------------------------------------------------------------------
1930 void testMallocWithParam(int **p
) {
1931 *p
= (int*) malloc(sizeof(int));
1932 *p
= 0; // FIXME: should warn here
1935 void testMallocWithParam_2(int **p
) {
1936 *p
= (int*) malloc(sizeof(int)); // no-warning
1939 void testPassToSystemHeaderFunctionIndirectly(void) {
1942 fakeSystemHeaderCallInt(p
);
1943 // FIXME: This is a leak: if we think a system function won't free p, it
1944 // won't free (p-1) either.
1947 void testMallocIntoMalloc(void) {
1948 StructWithPtr
*s
= malloc(sizeof(StructWithPtr
));
1949 s
->memP
= malloc(sizeof(int));
1951 } // FIXME: should warn here
1954 void testExtent(void) {
1956 clang_analyzer_dump(x
);
1957 // expected-warning-re@-1 {{{{^conj_\$[[:digit:]]+{int, LC1, S[[:digit:]]+, #1}}}}}}
1958 int *p
= (int *)malloc(x
);
1959 clang_analyzer_dumpExtent(p
);
1960 // expected-warning-re@-1 {{{{^conj_\$[[:digit:]]+{int, LC1, S[[:digit:]]+, #1}}}}}}