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 \
6 // RUN:   -analyzer-checker=debug.ExprInspection
7 
8 #include "Inputs/system-header-simulator.h"
9 
10 void clang_analyzer_eval(int);
11 
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".
18 //
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)
26 
27 typedef __typeof(sizeof(int)) size_t;
28 void *malloc(size_t);
29 void *alloca(size_t);
30 void *valloc(size_t);
31 void free(void *);
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);
39 
40 // Windows variants
41 char *_strdup(const char *strSource);
42 wchar_t *_wcsdup(const wchar_t *strSource);
43 void *_alloca(size_t size);
44 
45 void myfoo(int *p);
46 void myfooint(int p);
47 char *fooRetPtr();
48 
f1()49 void f1() {
50   int *p = malloc(12);
51   return; // expected-warning{{Potential leak of memory pointed to by 'p'}}
52 }
53 
f2()54 void f2() {
55   int *p = malloc(12);
56   free(p);
57   free(p); // expected-warning{{Attempt to free released memory}}
58 }
59 
f2_realloc_0()60 void f2_realloc_0() {
61   int *p = malloc(12);
62   realloc(p,0);
63   realloc(p,0); // expected-warning{{Attempt to free released memory}}
64 }
65 
f2_realloc_1()66 void f2_realloc_1() {
67   int *p = malloc(12);
68   int *q = realloc(p,0); // no-warning
69 }
70 
reallocNotNullPtr(unsigned sizeIn)71 void reallocNotNullPtr(unsigned sizeIn) {
72   unsigned size = 12;
73   char *p = (char*)malloc(size);
74   if (p) {
75     char *q = (char*)realloc(p, sizeIn);
76     char x = *q; // expected-warning {{Potential leak of memory pointed to by 'q'}}
77   }
78 }
79 
allocaTest()80 void allocaTest() {
81   int *p = alloca(sizeof(int));
82 } // no warn
83 
winAllocaTest()84 void winAllocaTest() {
85   int *p = _alloca(sizeof(int));
86 } // no warn
87 
allocaBuiltinTest()88 void allocaBuiltinTest() {
89   int *p = __builtin_alloca(sizeof(int));
90 } // no warn
91 
realloctest1()92 int *realloctest1() {
93   int *q = malloc(12);
94   q = realloc(q, 20);
95   return q; // no warning - returning the allocated value
96 }
97 
98 // p should be freed if realloc fails.
reallocFails()99 void reallocFails() {
100   char *p = malloc(12);
101   char *r = realloc(p, 12+1);
102   if (!r) {
103     free(p);
104   } else {
105     free(r);
106   }
107 }
108 
reallocSizeZero1()109 void reallocSizeZero1() {
110   char *p = malloc(12);
111   char *r = realloc(p, 0);
112   if (!r) {
113     free(p); // expected-warning {{Attempt to free released memory}}
114   } else {
115     free(r);
116   }
117 }
118 
reallocSizeZero2()119 void reallocSizeZero2() {
120   char *p = malloc(12);
121   char *r = realloc(p, 0);
122   if (!r) {
123     free(p); // expected-warning {{Attempt to free released memory}}
124   } else {
125     free(r);
126   }
127   free(p); // expected-warning {{Attempt to free released memory}}
128 }
129 
reallocSizeZero3()130 void reallocSizeZero3() {
131   char *p = malloc(12);
132   char *r = realloc(p, 0);
133   free(r);
134 }
135 
reallocSizeZero4()136 void reallocSizeZero4() {
137   char *r = realloc(0, 0);
138   free(r);
139 }
140 
reallocSizeZero5()141 void reallocSizeZero5() {
142   char *r = realloc(0, 0);
143 }
144 
reallocPtrZero1()145 void reallocPtrZero1() {
146   char *r = realloc(0, 12);
147 } // expected-warning {{Potential leak of memory pointed to by 'r'}}
148 
reallocPtrZero2()149 void reallocPtrZero2() {
150   char *r = realloc(0, 12);
151   if (r)
152     free(r);
153 }
154 
reallocPtrZero3()155 void reallocPtrZero3() {
156   char *r = realloc(0, 12);
157   free(r);
158 }
159 
reallocRadar6337483_1()160 void reallocRadar6337483_1() {
161     char *buf = malloc(100);
162     buf = (char*)realloc(buf, 0x1000000);
163     if (!buf) {
164         return;// expected-warning {{Potential leak of memory pointed to by}}
165     }
166     free(buf);
167 }
168 
reallocRadar6337483_2()169 void reallocRadar6337483_2() {
170     char *buf = malloc(100);
171     char *buf2 = (char*)realloc(buf, 0x1000000);
172     if (!buf2) {
173       ;
174     } else {
175       free(buf2);
176     }
177 } // expected-warning {{Potential leak of memory pointed to by}}
178 
reallocRadar6337483_3()179 void reallocRadar6337483_3() {
180     char * buf = malloc(100);
181     char * tmp;
182     tmp = (char*)realloc(buf, 0x1000000);
183     if (!tmp) {
184         free(buf);
185         return;
186     }
187     buf = tmp;
188     free(buf);
189 }
190 
reallocRadar6337483_4()191 void reallocRadar6337483_4() {
192     char *buf = malloc(100);
193     char *buf2 = (char*)realloc(buf, 0x1000000);
194     if (!buf2) {
195       return;  // expected-warning {{Potential leak of memory pointed to by}}
196     } else {
197       free(buf2);
198     }
199 }
200 
reallocfTest1()201 int *reallocfTest1() {
202   int *q = malloc(12);
203   q = reallocf(q, 20);
204   return q; // no warning - returning the allocated value
205 }
206 
reallocfRadar6337483_4()207 void reallocfRadar6337483_4() {
208     char *buf = malloc(100);
209     char *buf2 = (char*)reallocf(buf, 0x1000000);
210     if (!buf2) {
211       return;  // no warning - reallocf frees even on failure
212     } else {
213       free(buf2);
214     }
215 }
216 
reallocfRadar6337483_3()217 void reallocfRadar6337483_3() {
218     char * buf = malloc(100);
219     char * tmp;
220     tmp = (char*)reallocf(buf, 0x1000000);
221     if (!tmp) {
222         free(buf); // expected-warning {{Attempt to free released memory}}
223         return;
224     }
225     buf = tmp;
226     free(buf);
227 }
228 
reallocfPtrZero1()229 void reallocfPtrZero1() {
230   char *r = reallocf(0, 12);
231 } // expected-warning {{Potential leak of memory pointed to by}}
232 
233 //------------------- Check usage of zero-allocated memory ---------------------
CheckUseZeroAllocatedNoWarn1()234 void CheckUseZeroAllocatedNoWarn1() {
235   int *p = malloc(0);
236   free(p); // no warning
237 }
238 
CheckUseZeroAllocatedNoWarn2()239 void CheckUseZeroAllocatedNoWarn2() {
240   int *p = alloca(0); // no warning
241 }
242 
CheckUseZeroWinAllocatedNoWarn2()243 void CheckUseZeroWinAllocatedNoWarn2() {
244   int *p = _alloca(0); // no warning
245 }
246 
247 
CheckUseZeroAllocatedNoWarn3()248 void CheckUseZeroAllocatedNoWarn3() {
249   int *p = malloc(0);
250   int *q = realloc(p, 8); // no warning
251   free(q);
252 }
253 
CheckUseZeroAllocatedNoWarn4()254 void CheckUseZeroAllocatedNoWarn4() {
255   int *p = realloc(0, 8);
256   *p = 1; // no warning
257   free(p);
258 }
259 
CheckUseZeroAllocated1()260 void CheckUseZeroAllocated1() {
261   int *p = malloc(0);
262   *p = 1; // expected-warning {{Use of zero-allocated memory}}
263   free(p);
264 }
265 
CheckUseZeroAllocated2()266 char CheckUseZeroAllocated2() {
267   char *p = alloca(0);
268   return *p; // expected-warning {{Use of zero-allocated memory}}
269 }
270 
CheckUseZeroWinAllocated2()271 char CheckUseZeroWinAllocated2() {
272   char *p = _alloca(0);
273   return *p; // expected-warning {{Use of zero-allocated memory}}
274 }
275 
UseZeroAllocated(int * p)276 void UseZeroAllocated(int *p) {
277   if (p)
278     *p = 7; // expected-warning {{Use of zero-allocated memory}}
279 }
CheckUseZeroAllocated3()280 void CheckUseZeroAllocated3() {
281   int *p = malloc(0);
282   UseZeroAllocated(p);
283 }
284 
285 void f(char);
CheckUseZeroAllocated4()286 void CheckUseZeroAllocated4() {
287   char *p = valloc(0);
288   f(*p); // expected-warning {{Use of zero-allocated memory}}
289   free(p);
290 }
291 
CheckUseZeroAllocated5()292 void CheckUseZeroAllocated5() {
293   int *p = calloc(0, 2);
294   *p = 1; // expected-warning {{Use of zero-allocated memory}}
295   free(p);
296 }
297 
CheckUseZeroAllocated6()298 void CheckUseZeroAllocated6() {
299   int *p = calloc(2, 0);
300   *p = 1; // expected-warning {{Use of zero-allocated memory}}
301   free(p);
302 }
303 
CheckUseZeroAllocated7()304 void CheckUseZeroAllocated7() {
305   int *p = realloc(0, 0);
306   *p = 1; // expected-warning {{Use of zero-allocated memory}}
307   free(p);
308 }
309 
CheckUseZeroAllocated8()310 void CheckUseZeroAllocated8() {
311   int *p = malloc(8);
312   int *q = realloc(p, 0);
313   *q = 1; // expected-warning {{Use of zero-allocated memory}}
314   free(q);
315 }
316 
CheckUseZeroAllocated9()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}}
321   free(q);
322 }
323 
CheckUseZeroAllocatedPathNoWarn(_Bool b)324 void CheckUseZeroAllocatedPathNoWarn(_Bool b) {
325   int s = 0;
326   if (b)
327     s= 10;
328 
329   char *p = malloc(s);
330 
331   if (b)
332     *p = 1; // no warning
333 
334   free(p);
335 }
336 
CheckUseZeroAllocatedPathWarn(_Bool b)337 void CheckUseZeroAllocatedPathWarn(_Bool b) {
338   int s = 10;
339   if (b)
340     s= 0;
341 
342   char *p = malloc(s);
343 
344   if (b)
345     *p = 1; // expected-warning {{Use of zero-allocated memory}}
346 
347   free(p);
348 }
349 
CheckUseZeroReallocatedPathNoWarn(_Bool b)350 void CheckUseZeroReallocatedPathNoWarn(_Bool b) {
351   int s = 0;
352   if (b)
353     s= 10;
354 
355   char *p = malloc(8);
356   char *q = realloc(p, s);
357 
358   if (b)
359     *q = 1; // no warning
360 
361   free(q);
362 }
363 
CheckUseZeroReallocatedPathWarn(_Bool b)364 void CheckUseZeroReallocatedPathWarn(_Bool b) {
365   int s = 10;
366   if (b)
367     s= 0;
368 
369   char *p = malloc(8);
370   char *q = realloc(p, s);
371 
372   if (b)
373     *q = 1; // expected-warning {{Use of zero-allocated memory}}
374 
375   free(q);
376 }
377 
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.
f3()381 int *f3() {
382   static int *p = 0;
383   p = malloc(12);
384   return p; // no-warning
385 }
386 
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;
f4()391 int *f4() {
392   p_f4 = malloc(12);
393   return p_f4; // no-warning
394 }
395 
f5()396 int *f5() {
397   int *q = malloc(12);
398   q = realloc(q, 20);
399   return q; // no-warning
400 }
401 
f6()402 void f6() {
403   int *p = malloc(12);
404   if (!p)
405     return; // no-warning
406   else
407     free(p);
408 }
409 
f6_realloc()410 void f6_realloc() {
411   int *p = malloc(12);
412   if (!p)
413     return; // no-warning
414   else
415     realloc(p,0);
416 }
417 
418 
419 char *doit2();
pr6069()420 void pr6069() {
421   char *buf = doit2();
422   free(buf);
423 }
424 
pr6293()425 void pr6293() {
426   free(0);
427 }
428 
f7()429 void f7() {
430   char *x = (char*) malloc(4);
431   free(x);
432   x[0] = 'a'; // expected-warning{{Use of memory after it is freed}}
433 }
434 
f8()435 void f8() {
436   char *x = (char*) malloc(4);
437   free(x);
438   char *y = strndup(x, 4); // expected-warning{{Use of memory after it is freed}}
439 }
440 
f7_realloc()441 void f7_realloc() {
442   char *x = (char*) malloc(4);
443   realloc(x,0);
444   x[0] = 'a'; // expected-warning{{Use of memory after it is freed}}
445 }
446 
PR6123()447 void PR6123() {
448   int *x = malloc(11); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
449 }
450 
PR7217()451 void PR7217() {
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
454 }
455 
cast_emtpy_struct()456 void cast_emtpy_struct() {
457   struct st {
458   };
459 
460   struct st *s = malloc(sizeof(struct st)); // no-warning
461   free(s);
462 }
463 
cast_struct_1()464 void cast_struct_1() {
465   struct st {
466     int i[100];
467     char j[];
468   };
469 
470   struct st *s = malloc(sizeof(struct st)); // no-warning
471   free(s);
472 }
473 
cast_struct_2()474 void cast_struct_2() {
475   struct st {
476     int i[100];
477     char j[0];
478   };
479 
480   struct st *s = malloc(sizeof(struct st)); // no-warning
481   free(s);
482 }
483 
cast_struct_3()484 void cast_struct_3() {
485   struct st {
486     int i[100];
487     char j[1];
488   };
489 
490   struct st *s = malloc(sizeof(struct st)); // no-warning
491   free(s);
492 }
493 
cast_struct_4()494 void cast_struct_4() {
495   struct st {
496     int i[100];
497     char j[2];
498   };
499 
500   struct st *s = malloc(sizeof(struct st)); // no-warning
501   free(s);
502 }
503 
cast_struct_5()504 void cast_struct_5() {
505   struct st {
506     char i[200];
507     char j[1];
508   };
509 
510   struct st *s = malloc(sizeof(struct st) - sizeof(char)); // no-warning
511   free(s);
512 }
513 
cast_struct_warn_1()514 void cast_struct_warn_1() {
515   struct st {
516     int i[100];
517     char j[2];
518   };
519 
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}}
521   free(s);
522 }
523 
cast_struct_warn_2()524 void cast_struct_warn_2() {
525   struct st {
526     int i[100];
527     char j[2];
528   };
529 
530   struct st *s = malloc(2); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
531   free(s);
532 }
533 
cast_struct_flex_array_1()534 void cast_struct_flex_array_1() {
535   struct st {
536     int i[100];
537     char j[];
538   };
539 
540   struct st *s = malloc(sizeof(struct st) + 3); // no-warning
541   free(s);
542 }
543 
cast_struct_flex_array_2()544 void cast_struct_flex_array_2() {
545   struct st {
546     int i[100];
547     char j[0];
548   };
549 
550   struct st *s = malloc(sizeof(struct st) + 3); // no-warning
551   free(s);
552 }
553 
cast_struct_flex_array_3()554 void cast_struct_flex_array_3() {
555   struct st {
556     int i[100];
557     char j[1];
558   };
559 
560   struct st *s = malloc(sizeof(struct st) + 3); // no-warning
561   free(s);
562 }
563 
cast_struct_flex_array_4()564 void cast_struct_flex_array_4() {
565   struct foo {
566     char f[32];
567   };
568   struct st {
569     char i[100];
570     struct foo data[];
571   };
572 
573   struct st *s = malloc(sizeof(struct st) + 3 * sizeof(struct foo)); // no-warning
574   free(s);
575 }
576 
cast_struct_flex_array_5()577 void cast_struct_flex_array_5() {
578   struct foo {
579     char f[32];
580   };
581   struct st {
582     char i[100];
583     struct foo data[0];
584   };
585 
586   struct st *s = malloc(sizeof(struct st) + 3 * sizeof(struct foo)); // no-warning
587   free(s);
588 }
589 
cast_struct_flex_array_6()590 void cast_struct_flex_array_6() {
591   struct foo {
592     char f[32];
593   };
594   struct st {
595     char i[100];
596     struct foo data[1];
597   };
598 
599   struct st *s = malloc(sizeof(struct st) + 3 * sizeof(struct foo)); // no-warning
600   free(s);
601 }
602 
cast_struct_flex_array_warn_1()603 void cast_struct_flex_array_warn_1() {
604   struct foo {
605     char f[32];
606   };
607   struct st {
608     char i[100];
609     struct foo data[];
610   };
611 
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}}
613   free(s);
614 }
615 
cast_struct_flex_array_warn_2()616 void cast_struct_flex_array_warn_2() {
617   struct foo {
618     char f[32];
619   };
620   struct st {
621     char i[100];
622     struct foo data[0];
623   };
624 
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}}
626   free(s);
627 }
628 
cast_struct_flex_array_warn_3()629 void cast_struct_flex_array_warn_3() {
630   struct foo {
631     char f[32];
632   };
633   struct st {
634     char i[100];
635     struct foo data[1];
636   };
637 
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}}
639   free(s);
640 }
641 
cast_struct_flex_array_warn_4()642 void cast_struct_flex_array_warn_4() {
643   struct st {
644     int i[100];
645     int j[];
646   };
647 
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}}
649   free(s);
650 }
651 
cast_struct_flex_array_warn_5()652 void cast_struct_flex_array_warn_5() {
653   struct st {
654     int i[100];
655     int j[0];
656   };
657 
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}}
659   free(s);
660 }
661 
cast_struct_flex_array_warn_6()662 void cast_struct_flex_array_warn_6() {
663   struct st {
664     int i[100];
665     int j[1];
666   };
667 
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}}
669   free(s);
670 }
671 
mallocCastToVoid()672 void mallocCastToVoid() {
673   void *p = malloc(2);
674   const void *cp = p; // not crash
675   free(p);
676 }
677 
mallocCastToFP()678 void mallocCastToFP() {
679   void *p = malloc(2);
680   void (*fp)() = p; // not crash
681   free(p);
682 }
683 
684 // This tests that malloc() buffers are undefined by default
mallocGarbage()685 char mallocGarbage () {
686 	char *buf = malloc(2);
687 	char result = buf[1]; // expected-warning{{undefined}}
688 	free(buf);
689 	return result;
690 }
691 
692 // This tests that calloc() buffers need to be freed
callocNoFree()693 void callocNoFree () {
694   char *buf = calloc(2,2);
695   return; // expected-warning{{Potential leak of memory pointed to by 'buf'}}
696 }
697 
698 // These test that calloc() buffers are zeroed by default
callocZeroesGood()699 char callocZeroesGood () {
700 	char *buf = calloc(2,2);
701 	char result = buf[3]; // no-warning
702 	if (buf[1] == 0) {
703 	  free(buf);
704 	}
705 	return result; // no-warning
706 }
707 
callocZeroesBad()708 char callocZeroesBad () {
709 	char *buf = calloc(2,2);
710 	char result = buf[3]; // no-warning
711 	if (buf[1] != 0) {
712 	  free(buf); // expected-warning{{never executed}}
713 	}
714 	return result; // expected-warning{{Potential leak of memory pointed to by 'buf'}}
715 }
716 
nullFree()717 void nullFree() {
718   int *p = 0;
719   free(p); // no warning - a nop
720 }
721 
paramFree(int * p)722 void paramFree(int *p) {
723   myfoo(p);
724   free(p); // no warning
725   myfoo(p); // expected-warning {{Use of memory after it is freed}}
726 }
727 
mallocEscapeRet()728 int* mallocEscapeRet() {
729   int *p = malloc(12);
730   return p; // no warning
731 }
732 
mallocEscapeFoo()733 void mallocEscapeFoo() {
734   int *p = malloc(12);
735   myfoo(p);
736   return; // no warning
737 }
738 
mallocEscapeFree()739 void mallocEscapeFree() {
740   int *p = malloc(12);
741   myfoo(p);
742   free(p);
743 }
744 
mallocEscapeFreeFree()745 void mallocEscapeFreeFree() {
746   int *p = malloc(12);
747   myfoo(p);
748   free(p);
749   free(p); // expected-warning{{Attempt to free released memory}}
750 }
751 
mallocEscapeFreeUse()752 void mallocEscapeFreeUse() {
753   int *p = malloc(12);
754   myfoo(p);
755   free(p);
756   myfoo(p); // expected-warning{{Use of memory after it is freed}}
757 }
758 
759 int *myalloc();
760 void myalloc2(int **p);
761 
mallocEscapeFreeCustomAlloc()762 void mallocEscapeFreeCustomAlloc() {
763   int *p = malloc(12);
764   myfoo(p);
765   free(p);
766   p = myalloc();
767   free(p); // no warning
768 }
769 
mallocEscapeFreeCustomAlloc2()770 void mallocEscapeFreeCustomAlloc2() {
771   int *p = malloc(12);
772   myfoo(p);
773   free(p);
774   myalloc2(&p);
775   free(p); // no warning
776 }
777 
mallocBindFreeUse()778 void mallocBindFreeUse() {
779   int *x = malloc(12);
780   int *y = x;
781   free(y);
782   myfoo(x); // expected-warning{{Use of memory after it is freed}}
783 }
784 
mallocEscapeMalloc()785 void mallocEscapeMalloc() {
786   int *p = malloc(12);
787   myfoo(p);
788   p = malloc(12);
789 } // expected-warning{{Potential leak of memory pointed to by}}
790 
mallocMalloc()791 void mallocMalloc() {
792   int *p = malloc(12);
793   p = malloc(12);
794 } // expected-warning {{Potential leak of memory pointed to by}}\
795   // expected-warning {{Potential leak of memory pointed to by}}
796 
mallocFreeMalloc()797 void mallocFreeMalloc() {
798   int *p = malloc(12);
799   free(p);
800   p = malloc(12);
801   free(p);
802 }
803 
mallocFreeUse_params()804 void mallocFreeUse_params() {
805   int *p = malloc(12);
806   free(p);
807   myfoo(p); //expected-warning{{Use of memory after it is freed}}
808 }
809 
mallocFreeUse_params2()810 void mallocFreeUse_params2() {
811   int *p = malloc(12);
812   free(p);
813   myfooint(*p); //expected-warning{{Use of memory after it is freed}}
814 }
815 
mallocFailedOrNot()816 void mallocFailedOrNot() {
817   int *p = malloc(12);
818   if (!p)
819     free(p);
820   else
821     free(p);
822 }
823 
824 struct StructWithInt {
825   int g;
826 };
827 
mallocReturnFreed()828 int *mallocReturnFreed() {
829   int *p = malloc(12);
830   free(p);
831   return p; // expected-warning {{Use of memory after it is freed}}
832 }
833 
useAfterFreeStruct()834 int useAfterFreeStruct() {
835   struct StructWithInt *px= malloc(sizeof(struct StructWithInt));
836   px->g = 5;
837   free(px);
838   return px->g; // expected-warning {{Use of memory after it is freed}}
839 }
840 
841 void nonSymbolAsFirstArg(int *pp, struct StructWithInt *p);
842 
mallocEscapeFooNonSymbolArg()843 void mallocEscapeFooNonSymbolArg() {
844   struct StructWithInt *p = malloc(sizeof(struct StructWithInt));
845   nonSymbolAsFirstArg(&p->g, p);
846   return; // no warning
847 }
848 
mallocFailedOrNotLeak()849 void mallocFailedOrNotLeak() {
850   int *p = malloc(12);
851   if (p == 0)
852     return; // no warning
853   else
854     return; // expected-warning {{Potential leak of memory pointed to by}}
855 }
856 
mallocAssignment()857 void mallocAssignment() {
858   char *p = malloc(12);
859   p = fooRetPtr();
860 } // expected-warning {{leak}}
861 
vallocTest()862 int vallocTest() {
863   char *mem = valloc(12);
864   return 0; // expected-warning {{Potential leak of memory pointed to by}}
865 }
866 
vallocEscapeFreeUse()867 void vallocEscapeFreeUse() {
868   int *p = valloc(12);
869   myfoo(p);
870   free(p);
871   myfoo(p); // expected-warning{{Use of memory after it is freed}}
872 }
873 
874 int *Gl;
875 struct GlStTy {
876   int *x;
877 };
878 
879 struct GlStTy GlS = {0};
880 
GlobalFree()881 void GlobalFree() {
882   free(Gl);
883 }
884 
GlobalMalloc()885 void GlobalMalloc() {
886   Gl = malloc(12);
887 }
888 
GlobalStructMalloc()889 void GlobalStructMalloc() {
890   int *a = malloc(12);
891   GlS.x = a;
892 }
893 
GlobalStructMallocFree()894 void GlobalStructMallocFree() {
895   int *a = malloc(12);
896   GlS.x = a;
897   free(GlS.x);
898 }
899 
900 char *ArrayG[12];
901 
globalArrayTest()902 void globalArrayTest() {
903   char *p = (char*)malloc(12);
904   ArrayG[0] = p;
905 }
906 
907 // Make sure that we properly handle a pointer stored into a local struct/array.
908 typedef struct _StructWithPtr {
909   int *memP;
910 } StructWithPtr;
911 
912 static StructWithPtr arrOfStructs[10];
913 
testMalloc()914 void testMalloc() {
915   int *x = malloc(12);
916   StructWithPtr St;
917   St.memP = x;
918   arrOfStructs[0] = St; // no-warning
919 }
920 
testMalloc2()921 StructWithPtr testMalloc2() {
922   int *x = malloc(12);
923   StructWithPtr St;
924   St.memP = x;
925   return St; // no-warning
926 }
927 
testMalloc3()928 int *testMalloc3() {
929   int *x = malloc(12);
930   int *y = x;
931   return y; // no-warning
932 }
933 
testStructLeak()934 void testStructLeak() {
935   StructWithPtr St;
936   St.memP = malloc(12);
937   return; // expected-warning {{Potential leak of memory pointed to by 'St.memP'}}
938 }
939 
testElemRegion1()940 void testElemRegion1() {
941   char *x = (void*)malloc(2);
942   int *ix = (int*)x;
943   free(&(x[0]));
944 }
945 
testElemRegion2(int ** pp)946 void testElemRegion2(int **pp) {
947   int *p = malloc(12);
948   *pp = p;
949   free(pp[0]);
950 }
951 
testElemRegion3(int ** pp)952 void testElemRegion3(int **pp) {
953   int *p = malloc(12);
954   *pp = p;
955   free(*pp);
956 }
957 // Region escape testing.
958 
959 unsigned takePtrToPtr(int **p);
PassTheAddrOfAllocatedData(int f)960 void PassTheAddrOfAllocatedData(int f) {
961   int *p = malloc(12);
962   // We don't know what happens after the call. Should stop tracking here.
963   if (takePtrToPtr(&p))
964     f++;
965   free(p); // no warning
966 }
967 
968 struct X {
969   int *p;
970 };
971 unsigned takePtrToStruct(struct X *s);
foo2(int * g,int f)972 int ** foo2(int *g, int f) {
973   int *p = malloc(12);
974   struct X *px= malloc(sizeof(struct X));
975   px->p = p;
976   // We don't know what happens after this call. Should not track px nor p.
977   if (takePtrToStruct(px))
978     f++;
979   free(p);
980   return 0;
981 }
982 
RegInvalidationDetect1(struct X * s2)983 struct X* RegInvalidationDetect1(struct X *s2) {
984   struct X *px= malloc(sizeof(struct X));
985   px->p = 0;
986   px = s2;
987   return px; // expected-warning {{Potential leak of memory pointed to by}}
988 }
989 
RegInvalidationGiveUp1()990 struct X* RegInvalidationGiveUp1() {
991   int *p = malloc(12);
992   struct X *px= malloc(sizeof(struct X));
993   px->p = p;
994   return px;
995 }
996 
RegInvalidationDetect2(int ** pp)997 int **RegInvalidationDetect2(int **pp) {
998   int *p = malloc(12);
999   pp = &p;
1000   pp++;
1001   return 0;// expected-warning {{Potential leak of memory pointed to by}}
1002 }
1003 
1004 extern void exit(int) __attribute__ ((__noreturn__));
mallocExit(int * g)1005 void mallocExit(int *g) {
1006   struct xx *p = malloc(12);
1007   if (g != 0)
1008     exit(1);
1009   free(p);
1010   return;
1011 }
1012 
1013 extern void __assert_fail (__const char *__assertion, __const char *__file,
1014     unsigned int __line, __const char *__function)
1015      __attribute__ ((__noreturn__));
1016 #define assert(expr) \
1017   ((expr)  ? (void)(0)  : __assert_fail (#expr, __FILE__, __LINE__, __func__))
mallocAssert(int * g)1018 void mallocAssert(int *g) {
1019   struct xx *p = malloc(12);
1020 
1021   assert(g != 0);
1022   free(p);
1023   return;
1024 }
1025 
doNotInvalidateWhenPassedToSystemCalls(char * s)1026 void doNotInvalidateWhenPassedToSystemCalls(char *s) {
1027   char *p = malloc(12);
1028   strlen(p);
1029   strcpy(p, s);
1030   strcpy(s, p);
1031   strcpy(p, p);
1032   memcpy(p, s, 1);
1033   memcpy(s, p, 1);
1034   memcpy(p, p, 1);
1035 } // expected-warning {{leak}}
1036 
1037 // Treat source buffer contents as escaped.
escapeSourceContents(char * s)1038 void escapeSourceContents(char *s) {
1039   char *p = malloc(12);
1040   memcpy(s, &p, 12); // no warning
1041 
1042   void *p1 = malloc(7);
1043   char *a;
1044   memcpy(&a, &p1, sizeof a);
1045   // FIXME: No warning due to limitations imposed by current modelling of
1046   // 'memcpy' (regions metadata is not copied).
1047 
1048   int *ptrs[2];
1049   int *allocated = (int *)malloc(4);
1050   memcpy(&ptrs[0], &allocated, sizeof(int *));
1051   // FIXME: No warning due to limitations imposed by current modelling of
1052   // 'memcpy' (regions metadata is not copied).
1053 }
1054 
invalidateDestinationContents()1055 void invalidateDestinationContents() {
1056   int *null = 0;
1057   int *p = (int *)malloc(4);
1058   memcpy(&p, &null, sizeof(int *));
1059 
1060   int *ptrs1[2]; // expected-warning {{Potential leak of memory pointed to by}}
1061   ptrs1[0] = (int *)malloc(4);
1062   memcpy(ptrs1,  &null, sizeof(int *));
1063 
1064   int *ptrs2[2]; // expected-warning {{Potential memory leak}}
1065   ptrs2[0] = (int *)malloc(4);
1066   memcpy(&ptrs2[1],  &null, sizeof(int *));
1067 
1068   int *ptrs3[2]; // expected-warning {{Potential memory leak}}
1069   ptrs3[0] = (int *)malloc(4);
1070   memcpy(&ptrs3[0],  &null, sizeof(int *));
1071 } // expected-warning {{Potential memory leak}}
1072 
1073 // Rely on the CString checker evaluation of the strcpy API to convey that the result of strcpy is equal to p.
symbolLostWithStrcpy(char * s)1074 void symbolLostWithStrcpy(char *s) {
1075   char *p = malloc(12);
1076   p = strcpy(p, s);
1077   free(p);
1078 }
1079 
1080 
1081 // The same test as the one above, but with what is actually generated on a mac.
1082 static __inline char *
__inline_strcpy_chk(char * restrict __dest,const char * restrict __src)1083 __inline_strcpy_chk (char *restrict __dest, const char *restrict __src)
1084 {
1085   return __builtin___strcpy_chk (__dest, __src, __builtin_object_size (__dest, 2 > 1));
1086 }
1087 
symbolLostWithStrcpy_InlineStrcpyVersion(char * s)1088 void symbolLostWithStrcpy_InlineStrcpyVersion(char *s) {
1089   char *p = malloc(12);
1090   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));
1091   free(p);
1092 }
1093 
1094 // Here we are returning a pointer one past the allocated value. An idiom which
1095 // can be used for implementing special malloc. The correct uses of this might
1096 // be rare enough so that we could keep this as a warning.
specialMalloc(int n)1097 static void *specialMalloc(int n){
1098   int *p;
1099   p = malloc( n+8 );
1100   if( p ){
1101     p[0] = n;
1102     p++;
1103   }
1104   return p;
1105 }
1106 
1107 // Potentially, the user could free the struct by performing pointer arithmetic on the return value.
1108 // This is a variation of the specialMalloc issue, though probably would be more rare in correct code.
specialMallocWithStruct()1109 int *specialMallocWithStruct() {
1110   struct StructWithInt *px= malloc(sizeof(struct StructWithInt));
1111   return &(px->g);
1112 }
1113 
1114 // Test various allocation/deallocation functions.
testStrdup(const char * s,unsigned validIndex)1115 void testStrdup(const char *s, unsigned validIndex) {
1116   char *s2 = strdup(s);
1117   s2[validIndex + 1] = 'b';
1118 } // expected-warning {{Potential leak of memory pointed to by}}
1119 
testWinStrdup(const char * s,unsigned validIndex)1120 void testWinStrdup(const char *s, unsigned validIndex) {
1121   char *s2 = _strdup(s);
1122   s2[validIndex + 1] = 'b';
1123 } // expected-warning {{Potential leak of memory pointed to by}}
1124 
testWcsdup(const wchar_t * s,unsigned validIndex)1125 void testWcsdup(const wchar_t *s, unsigned validIndex) {
1126   wchar_t *s2 = wcsdup(s);
1127   s2[validIndex + 1] = 'b';
1128 } // expected-warning {{Potential leak of memory pointed to by}}
1129 
testWinWcsdup(const wchar_t * s,unsigned validIndex)1130 void testWinWcsdup(const wchar_t *s, unsigned validIndex) {
1131   wchar_t *s2 = _wcsdup(s);
1132   s2[validIndex + 1] = 'b';
1133 } // expected-warning {{Potential leak of memory pointed to by}}
1134 
testStrndup(const char * s,unsigned validIndex,unsigned size)1135 int testStrndup(const char *s, unsigned validIndex, unsigned size) {
1136   char *s2 = strndup(s, size);
1137   s2 [validIndex + 1] = 'b';
1138   if (s2[validIndex] != 'a')
1139     return 0;
1140   else
1141     return 1;// expected-warning {{Potential leak of memory pointed to by}}
1142 }
1143 
testStrdupContentIsDefined(const char * s,unsigned validIndex)1144 void testStrdupContentIsDefined(const char *s, unsigned validIndex) {
1145   char *s2 = strdup(s);
1146   char result = s2[1];// no warning
1147   free(s2);
1148 }
1149 
testWinStrdupContentIsDefined(const char * s,unsigned validIndex)1150 void testWinStrdupContentIsDefined(const char *s, unsigned validIndex) {
1151   char *s2 = _strdup(s);
1152   char result = s2[1];// no warning
1153   free(s2);
1154 }
1155 
testWcsdupContentIsDefined(const wchar_t * s,unsigned validIndex)1156 void testWcsdupContentIsDefined(const wchar_t *s, unsigned validIndex) {
1157   wchar_t *s2 = wcsdup(s);
1158   wchar_t result = s2[1];// no warning
1159   free(s2);
1160 }
1161 
testWinWcsdupContentIsDefined(const wchar_t * s,unsigned validIndex)1162 void testWinWcsdupContentIsDefined(const wchar_t *s, unsigned validIndex) {
1163   wchar_t *s2 = _wcsdup(s);
1164   wchar_t result = s2[1];// no warning
1165   free(s2);
1166 }
1167 
1168 // ----------------------------------------------------------------------------
1169 // Test the system library functions to which the pointer can escape.
1170 // This tests false positive suppression.
1171 
1172 // For now, we assume memory passed to pthread_specific escapes.
1173 // TODO: We could check that if a new pthread binding is set, the existing
1174 // binding must be freed; otherwise, a memory leak can occur.
testPthereadSpecificEscape(pthread_key_t key)1175 void testPthereadSpecificEscape(pthread_key_t key) {
1176   void *buf = malloc(12);
1177   pthread_setspecific(key, buf); // no warning
1178 }
1179 
1180 // PR12101: Test funopen().
releasePtr(void * _ctx)1181 static int releasePtr(void *_ctx) {
1182     free(_ctx);
1183     return 0;
1184 }
useFunOpen()1185 FILE *useFunOpen() {
1186     void *ctx = malloc(sizeof(int));
1187     FILE *f = funopen(ctx, 0, 0, 0, releasePtr); // no warning
1188     if (f == 0) {
1189         free(ctx);
1190     }
1191     return f;
1192 }
useFunOpenNoReleaseFunction()1193 FILE *useFunOpenNoReleaseFunction() {
1194     void *ctx = malloc(sizeof(int));
1195     FILE *f = funopen(ctx, 0, 0, 0, 0);
1196     if (f == 0) {
1197         free(ctx);
1198     }
1199     return f; // expected-warning{{leak}}
1200 }
1201 
readNothing(void * _ctx,char * buf,int size)1202 static int readNothing(void *_ctx, char *buf, int size) {
1203   return 0;
1204 }
useFunOpenReadNoRelease()1205 FILE *useFunOpenReadNoRelease() {
1206   void *ctx = malloc(sizeof(int));
1207   FILE *f = funopen(ctx, readNothing, 0, 0, 0);
1208   if (f == 0) {
1209     free(ctx);
1210   }
1211   return f; // expected-warning{{leak}}
1212 }
1213 
1214 // Test setbuf, setvbuf.
my_main_no_warning()1215 int my_main_no_warning() {
1216     char *p = malloc(100);
1217     setvbuf(stdout, p, 0, 100);
1218     return 0;
1219 }
my_main_no_warning2()1220 int my_main_no_warning2() {
1221     char *p = malloc(100);
1222     setbuf(__stdoutp, p);
1223     return 0;
1224 }
my_main_warn(FILE * f)1225 int my_main_warn(FILE *f) {
1226     char *p = malloc(100);
1227     setvbuf(f, p, 0, 100);
1228     return 0;// expected-warning {{leak}}
1229 }
1230 
1231 // <rdar://problem/10978247>.
1232 // some people use stack allocated memory as an optimization to avoid
1233 // a heap allocation for small work sizes.  This tests the analyzer's
1234 // understanding that the malloc'ed memory is not the same as stackBuffer.
radar10978247(int myValueSize)1235 void radar10978247(int myValueSize) {
1236   char stackBuffer[128];
1237   char *buffer;
1238 
1239   if (myValueSize <= sizeof(stackBuffer))
1240     buffer = stackBuffer;
1241   else
1242     buffer = malloc(myValueSize);
1243 
1244   // do stuff with the buffer
1245   if (buffer != stackBuffer)
1246     free(buffer);
1247 }
1248 
radar10978247_positive(int myValueSize)1249 void radar10978247_positive(int myValueSize) {
1250   char stackBuffer[128];
1251   char *buffer;
1252 
1253   if (myValueSize <= sizeof(stackBuffer))
1254     buffer = stackBuffer;
1255   else
1256     buffer = malloc(myValueSize);
1257 
1258   // do stuff with the buffer
1259   if (buffer == stackBuffer)
1260     return;
1261   else
1262     return; // expected-warning {{leak}}
1263 }
1264 // <rdar://problem/11269741> Previously this triggered a false positive
1265 // because malloc() is known to return uninitialized memory and the binding
1266 // of 'o' to 'p->n' was not getting propertly handled.  Now we report a leak.
1267 struct rdar11269741_a_t {
1268   struct rdar11269741_b_t {
1269     int m;
1270   } n;
1271 };
1272 
rdar11269741(struct rdar11269741_b_t o)1273 int rdar11269741(struct rdar11269741_b_t o)
1274 {
1275   struct rdar11269741_a_t *p = (struct rdar11269741_a_t *) malloc(sizeof(*p));
1276   p->n = o;
1277   return p->n.m; // expected-warning {{leak}}
1278 }
1279 
1280 // Pointer arithmetic, returning an ElementRegion.
radar11329382(unsigned bl)1281 void *radar11329382(unsigned bl) {
1282   void *ptr = malloc (16);
1283   ptr = ptr + (2 - bl);
1284   return ptr; // no warning
1285 }
1286 
1287 void __assert_rtn(const char *, const char *, int, const char *) __attribute__((__noreturn__));
1288 int strcmp(const char *, const char *);
1289 char *a (void);
radar11270219(void)1290 void radar11270219(void) {
1291   char *x = a(), *y = a();
1292   (__builtin_expect(!(x && y), 0) ? __assert_rtn(__func__, "/Users/zaks/tmp/ex.c", 24, "x && y") : (void)0);
1293   strcmp(x, y); // no warning
1294 }
1295 
radar_11358224_test_double_assign_ints_positive_2()1296 void radar_11358224_test_double_assign_ints_positive_2()
1297 {
1298   void *ptr = malloc(16);
1299   ptr = ptr;
1300 } // expected-warning {{leak}}
1301 
1302 // Assume that functions which take a function pointer can free memory even if
1303 // they are defined in system headers and take the const pointer to the
1304 // allocated memory. (radar://11160612)
1305 int const_ptr_and_callback(int, const char*, int n, void(*)(void*));
r11160612_1()1306 void r11160612_1() {
1307   char *x = malloc(12);
1308   const_ptr_and_callback(0, x, 12, free); // no - warning
1309 }
1310 
1311 // Null is passed as callback.
r11160612_2()1312 void r11160612_2() {
1313   char *x = malloc(12);
1314   const_ptr_and_callback(0, x, 12, 0);
1315 } // expected-warning {{leak}}
1316 
1317 // Callback is passed to a function defined in a system header.
r11160612_4()1318 void r11160612_4() {
1319   char *x = malloc(12);
1320   sqlite3_bind_text_my(0, x, 12, free); // no - warning
1321 }
1322 
1323 // Passing callbacks in a struct.
r11160612_5(StWithCallback St)1324 void r11160612_5(StWithCallback St) {
1325   void *x = malloc(12);
1326   dealocateMemWhenDoneByVal(x, St);
1327 }
r11160612_6(StWithCallback St)1328 void r11160612_6(StWithCallback St) {
1329   void *x = malloc(12);
1330   dealocateMemWhenDoneByRef(&St, x);
1331 }
1332 
1333 int mySub(int, int);
1334 int myAdd(int, int);
fPtr(unsigned cond,int x)1335 int fPtr(unsigned cond, int x) {
1336   return (cond ? mySub : myAdd)(x, x);
1337 }
1338 
1339 // Test anti-aliasing.
1340 
dependsOnValueOfPtr(int * g,unsigned f)1341 void dependsOnValueOfPtr(int *g, unsigned f) {
1342   int *p;
1343 
1344   if (f) {
1345     p = g;
1346   } else {
1347     p = malloc(12);
1348   }
1349 
1350   if (p != g)
1351     free(p);
1352   else
1353     return; // no warning
1354   return;
1355 }
1356 
CMPRegionHeapToStack()1357 int CMPRegionHeapToStack() {
1358   int x = 0;
1359   int *x1 = malloc(8);
1360   int *x2 = &x;
1361   clang_analyzer_eval(x1 == x2); // expected-warning{{FALSE}}
1362   free(x1);
1363   return x;
1364 }
1365 
CMPRegionHeapToHeap2()1366 int CMPRegionHeapToHeap2() {
1367   int x = 0;
1368   int *x1 = malloc(8);
1369   int *x2 = malloc(8);
1370   int *x4 = x1;
1371   int *x5 = x2;
1372   clang_analyzer_eval(x4 == x5); // expected-warning{{FALSE}}
1373   free(x1);
1374   free(x2);
1375   return x;
1376 }
1377 
CMPRegionHeapToHeap()1378 int CMPRegionHeapToHeap() {
1379   int x = 0;
1380   int *x1 = malloc(8);
1381   int *x4 = x1;
1382   if (x1 == x4) {
1383     free(x1);
1384     return 5/x; // expected-warning{{Division by zero}}
1385   }
1386   return x;// expected-warning{{This statement is never executed}}
1387 }
1388 
HeapAssignment()1389 int HeapAssignment() {
1390   int m = 0;
1391   int *x = malloc(4);
1392   int *y = x;
1393   *x = 5;
1394   clang_analyzer_eval(*x != *y); // expected-warning{{FALSE}}
1395   free(x);
1396   return 0;
1397 }
1398 
1399 int *retPtr();
1400 int *retPtrMightAlias(int *x);
cmpHeapAllocationToUnknown()1401 int cmpHeapAllocationToUnknown() {
1402   int zero = 0;
1403   int *yBefore = retPtr();
1404   int *m = malloc(8);
1405   int *yAfter = retPtrMightAlias(m);
1406   clang_analyzer_eval(yBefore == m); // expected-warning{{FALSE}}
1407   clang_analyzer_eval(yAfter == m); // expected-warning{{FALSE}}
1408   free(m);
1409   return 0;
1410 }
1411 
localArrayTest()1412 void localArrayTest() {
1413   char *p = (char*)malloc(12);
1414   char *ArrayL[12];
1415   ArrayL[0] = p;
1416 } // expected-warning {{leak}}
1417 
localStructTest()1418 void localStructTest() {
1419   StructWithPtr St;
1420   StructWithPtr *pSt = &St;
1421   pSt->memP = malloc(12);
1422 } // expected-warning{{Potential leak of memory pointed to by}}
1423 
1424 #ifdef __INTPTR_TYPE__
1425 // Test double assignment through integers.
1426 typedef __INTPTR_TYPE__ intptr_t;
1427 typedef unsigned __INTPTR_TYPE__ uintptr_t;
1428 
1429 static intptr_t glob;
test_double_assign_ints()1430 void test_double_assign_ints()
1431 {
1432   void *ptr = malloc (16);  // no-warning
1433   glob = (intptr_t)(uintptr_t)ptr;
1434 }
1435 
test_double_assign_ints_positive()1436 void test_double_assign_ints_positive()
1437 {
1438   void *ptr = malloc(16);
1439   (void*)(intptr_t)(uintptr_t)ptr; // expected-warning {{unused}}
1440 } // expected-warning {{leak}}
1441 #endif
1442 
testCGContextNoLeak()1443 void testCGContextNoLeak()
1444 {
1445   void *ptr = malloc(16);
1446   CGContextRef context = CGBitmapContextCreate(ptr);
1447 
1448   // Because you can get the data back out like this, even much later,
1449   // CGBitmapContextCreate is one of our "stop-tracking" exceptions.
1450   free(CGBitmapContextGetData(context));
1451 }
1452 
testCGContextLeak()1453 void testCGContextLeak()
1454 {
1455   void *ptr = malloc(16);
1456   CGContextRef context = CGBitmapContextCreate(ptr);
1457   // However, this time we're just leaking the data, because the context
1458   // object doesn't escape and it hasn't been freed in this function.
1459 }
1460 
1461 // Allow xpc context to escape. radar://11635258
1462 // TODO: Would be great if we checked that the finalize_connection_context actually releases it.
finalize_connection_context(void * ctx)1463 static void finalize_connection_context(void *ctx) {
1464   int *context = ctx;
1465   free(context);
1466 }
foo(xpc_connection_t peer)1467 void foo (xpc_connection_t peer) {
1468   int *ctx = calloc(1, sizeof(int));
1469   xpc_connection_set_context(peer, ctx);
1470   xpc_connection_set_finalizer_f(peer, finalize_connection_context);
1471   xpc_connection_resume(peer);
1472 }
1473 
1474 // Make sure we catch errors when we free in a function which does not allocate memory.
freeButNoMalloc(int * p,int x)1475 void freeButNoMalloc(int *p, int x){
1476   if (x) {
1477     free(p);
1478     //user forgot a return here.
1479   }
1480   free(p); // expected-warning {{Attempt to free released memory}}
1481 }
1482 
1483 struct HasPtr {
1484   char *p;
1485 };
1486 
reallocButNoMalloc(struct HasPtr * a,int c,int size)1487 char* reallocButNoMalloc(struct HasPtr *a, int c, int size) {
1488   int *s;
1489   char *b = realloc(a->p, size);
1490   char *m = realloc(a->p, size); // expected-warning {{Attempt to free released memory}}
1491   // We don't expect a use-after-free for a->P here because the warning above
1492   // is a sink.
1493   return a->p; // no-warning
1494 }
1495 
1496 // We should not warn in this case since the caller will presumably free a->p in all cases.
reallocButNoMallocPR13674(struct HasPtr * a,int c,int size)1497 int reallocButNoMallocPR13674(struct HasPtr *a, int c, int size) {
1498   int *s;
1499   char *b = realloc(a->p, size);
1500   if (b == 0)
1501     return -1;
1502   a->p = b;
1503   return 0;
1504 }
1505 
1506 // Test realloc with no visible malloc.
test(void * ptr)1507 void *test(void *ptr) {
1508   void *newPtr = realloc(ptr, 4);
1509   if (newPtr == 0) {
1510     if (ptr)
1511       free(ptr); // no-warning
1512   }
1513   return newPtr;
1514 }
1515 
1516 
testLeakWithinReturn(char * str)1517 char *testLeakWithinReturn(char *str) {
1518   return strdup(strdup(str)); // expected-warning{{leak}}
1519 }
1520 
testWinLeakWithinReturn(char * str)1521 char *testWinLeakWithinReturn(char *str) {
1522   return _strdup(_strdup(str)); // expected-warning{{leak}}
1523 }
1524 
testWinWideLeakWithinReturn(wchar_t * str)1525 wchar_t *testWinWideLeakWithinReturn(wchar_t *str) {
1526   return _wcsdup(_wcsdup(str)); // expected-warning{{leak}}
1527 }
1528 
1529 void passConstPtr(const char * ptr);
1530 
testPassConstPointer()1531 void testPassConstPointer() {
1532   char * string = malloc(sizeof(char)*10);
1533   passConstPtr(string);
1534   return; // expected-warning {{leak}}
1535 }
1536 
testPassConstPointerIndirectly()1537 void testPassConstPointerIndirectly() {
1538   char *p = malloc(1);
1539   p++;
1540   memcmp(p, p, sizeof(&p));
1541   return; // expected-warning {{leak}}
1542 }
1543 
testPassConstPointerIndirectlyStruct()1544 void testPassConstPointerIndirectlyStruct() {
1545   struct HasPtr hp;
1546   hp.p = malloc(10);
1547   memcmp(&hp, &hp, sizeof(hp));
1548   return; // expected-warning {{Potential leak of memory pointed to by 'hp.p'}}
1549 }
1550 
testPassToSystemHeaderFunctionIndirectlyStruct()1551 void testPassToSystemHeaderFunctionIndirectlyStruct() {
1552   SomeStruct ss;
1553   ss.p = malloc(1);
1554   fakeSystemHeaderCall(&ss); // invalidates ss, making ss.p unreachable
1555   // Technically a false negative here -- we know the system function won't free
1556   // ss.p, but nothing else will either!
1557 } // no-warning
1558 
testPassToSystemHeaderFunctionIndirectlyStructFree()1559 void testPassToSystemHeaderFunctionIndirectlyStructFree() {
1560   SomeStruct ss;
1561   ss.p = malloc(1);
1562   fakeSystemHeaderCall(&ss); // invalidates ss, making ss.p unreachable
1563   free(ss.p);
1564 } // no-warning
1565 
testPassToSystemHeaderFunctionIndirectlyArray()1566 void testPassToSystemHeaderFunctionIndirectlyArray() {
1567   int *p[1];
1568   p[0] = malloc(sizeof(int));
1569   fakeSystemHeaderCallIntPtr(p); // invalidates p, making p[0] unreachable
1570   // Technically a false negative here -- we know the system function won't free
1571   // p[0], but nothing else will either!
1572 } // no-warning
1573 
testPassToSystemHeaderFunctionIndirectlyArrayFree()1574 void testPassToSystemHeaderFunctionIndirectlyArrayFree() {
1575   int *p[1];
1576   p[0] = malloc(sizeof(int));
1577   fakeSystemHeaderCallIntPtr(p); // invalidates p, making p[0] unreachable
1578   free(p[0]);
1579 } // no-warning
1580 
testOffsetAllocate(size_t size)1581 int *testOffsetAllocate(size_t size) {
1582   int *memoryBlock = (int *)malloc(size + sizeof(int));
1583   return &memoryBlock[1]; // no-warning
1584 }
1585 
testOffsetDeallocate(int * memoryBlock)1586 void testOffsetDeallocate(int *memoryBlock) {
1587   free(&memoryBlock[-1]);  // no-warning
1588 }
1589 
testOffsetOfRegionFreed()1590 void testOffsetOfRegionFreed() {
1591   __int64_t * array = malloc(sizeof(__int64_t)*2);
1592   array += 1;
1593   free(&array[0]); // expected-warning{{Argument to free() is offset by 8 bytes from the start of memory allocated by malloc()}}
1594 }
1595 
testOffsetOfRegionFreed2()1596 void testOffsetOfRegionFreed2() {
1597   __int64_t *p = malloc(sizeof(__int64_t)*2);
1598   p += 1;
1599   free(p); // expected-warning{{Argument to free() is offset by 8 bytes from the start of memory allocated by malloc()}}
1600 }
1601 
testOffsetOfRegionFreed3()1602 void testOffsetOfRegionFreed3() {
1603   char *r = malloc(sizeof(char));
1604   r = r - 10;
1605   free(r); // expected-warning {{Argument to free() is offset by -10 bytes from the start of memory allocated by malloc()}}
1606 }
1607 
testOffsetOfRegionFreedAfterFunctionCall()1608 void testOffsetOfRegionFreedAfterFunctionCall() {
1609   int *p = malloc(sizeof(int)*2);
1610   p += 1;
1611   myfoo(p);
1612   free(p); // expected-warning{{Argument to free() is offset by 4 bytes from the start of memory allocated by malloc()}}
1613 }
1614 
testFixManipulatedPointerBeforeFree()1615 void testFixManipulatedPointerBeforeFree() {
1616   int * array = malloc(sizeof(int)*2);
1617   array += 1;
1618   free(&array[-1]); // no-warning
1619 }
1620 
testFixManipulatedPointerBeforeFree2()1621 void testFixManipulatedPointerBeforeFree2() {
1622   char *r = malloc(sizeof(char));
1623   r = r + 10;
1624   free(r-10); // no-warning
1625 }
1626 
freeOffsetPointerPassedToFunction()1627 void freeOffsetPointerPassedToFunction() {
1628   __int64_t *p = malloc(sizeof(__int64_t)*2);
1629   p[1] = 0;
1630   p += 1;
1631   myfooint(*p); // not passing the pointer, only a value pointed by pointer
1632   free(p); // expected-warning {{Argument to free() is offset by 8 bytes from the start of memory allocated by malloc()}}
1633 }
1634 
1635 int arbitraryInt();
freeUnknownOffsetPointer()1636 void freeUnknownOffsetPointer() {
1637   char *r = malloc(sizeof(char));
1638   r = r + arbitraryInt(); // unable to reason about what the offset might be
1639   free(r); // no-warning
1640 }
1641 
testFreeNonMallocPointerWithNoOffset()1642 void testFreeNonMallocPointerWithNoOffset() {
1643   char c;
1644   char *r = &c;
1645   r = r + 10;
1646   free(r-10); // expected-warning {{Argument to free() is the address of the local variable 'c', which is not memory allocated by malloc()}}
1647 }
1648 
testFreeNonMallocPointerWithOffset()1649 void testFreeNonMallocPointerWithOffset() {
1650   char c;
1651   char *r = &c;
1652   free(r+1); // expected-warning {{Argument to free() is the address of the local variable 'c', which is not memory allocated by malloc()}}
1653 }
1654 
testOffsetZeroDoubleFree()1655 void testOffsetZeroDoubleFree() {
1656   int *array = malloc(sizeof(int)*2);
1657   int *p = &array[0];
1658   free(p);
1659   free(&array[0]); // expected-warning{{Attempt to free released memory}}
1660 }
1661 
testOffsetPassedToStrlen()1662 void testOffsetPassedToStrlen() {
1663   char * string = malloc(sizeof(char)*10);
1664   string += 1;
1665   int length = strlen(string); // expected-warning {{Potential leak of memory pointed to by 'string'}}
1666 }
1667 
testOffsetPassedToStrlenThenFree()1668 void testOffsetPassedToStrlenThenFree() {
1669   char * string = malloc(sizeof(char)*10);
1670   string += 1;
1671   int length = strlen(string);
1672   free(string); // expected-warning {{Argument to free() is offset by 1 byte from the start of memory allocated by malloc()}}
1673 }
1674 
testOffsetPassedAsConst()1675 void testOffsetPassedAsConst() {
1676   char * string = malloc(sizeof(char)*10);
1677   string += 1;
1678   passConstPtr(string);
1679   free(string); // expected-warning {{Argument to free() is offset by 1 byte from the start of memory allocated by malloc()}}
1680 }
1681 
1682 char **_vectorSegments;
1683 int _nVectorSegments;
1684 
poolFreeC(void * s)1685 void poolFreeC(void* s) {
1686   free(s); // no-warning
1687 }
freeMemory()1688 void freeMemory() {
1689   while (_nVectorSegments) {
1690     poolFreeC(_vectorSegments[_nVectorSegments++]);
1691   }
1692 }
1693 
1694 // PR16730
testReallocEscaped(void ** memory)1695 void testReallocEscaped(void **memory) {
1696   *memory = malloc(47);
1697   char *new_memory = realloc(*memory, 47);
1698   if (new_memory != 0) {
1699     *memory = new_memory;
1700   }
1701 }
1702 
1703 // PR16558
smallocNoWarn(size_t size)1704 void *smallocNoWarn(size_t size) {
1705   if (size == 0) {
1706     return malloc(1); // this branch is never called
1707   }
1708   else {
1709     return malloc(size);
1710   }
1711 }
1712 
dupstrNoWarn(const char * s)1713 char *dupstrNoWarn(const char *s) {
1714   const int len = strlen(s);
1715   char *p = (char*) smallocNoWarn(len + 1);
1716   strcpy(p, s); // no-warning
1717   return p;
1718 }
1719 
smallocWarn(size_t size)1720 void *smallocWarn(size_t size) {
1721   if (size == 2) {
1722     return malloc(1);
1723   }
1724   else {
1725     return malloc(size);
1726   }
1727 }
1728 
radar15580979()1729 int *radar15580979() {
1730   int *data = (int *)malloc(32);
1731   int *p = data ?: (int*)malloc(32); // no warning
1732   return p;
1733 }
1734 
1735 // Some data structures may hold onto the pointer and free it later.
testEscapeThroughSystemCallTakingVoidPointer1(void * queue)1736 void testEscapeThroughSystemCallTakingVoidPointer1(void *queue) {
1737   int *data = (int *)malloc(32);
1738   fake_insque(queue, data); // no warning
1739 }
1740 
testEscapeThroughSystemCallTakingVoidPointer2(fake_rb_tree_t * rbt)1741 void testEscapeThroughSystemCallTakingVoidPointer2(fake_rb_tree_t *rbt) {
1742   int *data = (int *)malloc(32);
1743   fake_rb_tree_init(rbt, data);
1744 } //expected-warning{{Potential leak}}
1745 
testEscapeThroughSystemCallTakingVoidPointer3(fake_rb_tree_t * rbt)1746 void testEscapeThroughSystemCallTakingVoidPointer3(fake_rb_tree_t *rbt) {
1747   int *data = (int *)malloc(32);
1748   fake_rb_tree_init(rbt, data);
1749   fake_rb_tree_insert_node(rbt, data); // no warning
1750 }
1751 
1752 struct IntAndPtr {
1753   int x;
1754   int *p;
1755 };
1756 
1757 void constEscape(const void *ptr);
1758 
testConstEscapeThroughAnotherField()1759 void testConstEscapeThroughAnotherField() {
1760   struct IntAndPtr s;
1761   s.p = malloc(sizeof(int));
1762   constEscape(&(s.x)); // could free s->p!
1763 } // no-warning
1764 
1765 // PR15623
testNoCheckerDataPropogationFromLogicalOpOperandToOpResult(void)1766 int testNoCheckerDataPropogationFromLogicalOpOperandToOpResult(void) {
1767    char *param = malloc(10);
1768    char *value = malloc(10);
1769    int ok = (param && value);
1770    free(param);
1771    free(value);
1772    // Previously we ended up with 'Use of memory after it is freed' on return.
1773    return ok; // no warning
1774 }
1775 
1776 void (*fnptr)(int);
freeIndirectFunctionPtr()1777 void freeIndirectFunctionPtr() {
1778   void *p = (void *)fnptr;
1779   free(p); // expected-warning {{Argument to free() is a function pointer}}
1780 }
1781 
freeFunctionPtr()1782 void freeFunctionPtr() {
1783   free((void *)fnptr); // expected-warning {{Argument to free() is a function pointer}}
1784 }
1785 
allocateSomeMemory(void * offendingParameter,void ** ptr)1786 void allocateSomeMemory(void *offendingParameter, void **ptr) {
1787   *ptr = malloc(1);
1788 }
1789 
testNoCrashOnOffendingParameter()1790 void testNoCrashOnOffendingParameter() {
1791   // "extern" is necessary to avoid unrelated warnings
1792   // on passing uninitialized value.
1793   extern void *offendingParameter;
1794   void* ptr;
1795   allocateSomeMemory(offendingParameter, &ptr);
1796 } // expected-warning {{Potential leak of memory pointed to by 'ptr'}}
1797 
1798 
1799 // Test a false positive caused by a bug in liveness analysis.
1800 struct A {
1801   int *buf;
1802 };
1803 struct B {
1804   struct A *a;
1805 };
livenessBugRealloc(struct A * a)1806 void livenessBugRealloc(struct A *a) {
1807   a->buf = realloc(a->buf, sizeof(int)); // no-warning
1808 }
testLivenessBug(struct B * in_b)1809 void testLivenessBug(struct B *in_b) {
1810   struct B *b = in_b;
1811   livenessBugRealloc(b->a);
1812  ((void) 0); // An attempt to trick liveness analysis.
1813   livenessBugRealloc(b->a);
1814 }
1815 
1816 struct ListInfo {
1817   struct ListInfo *next;
1818 };
1819 
1820 struct ConcreteListItem {
1821   struct ListInfo li;
1822   int i;
1823 };
1824 
1825 void list_add(struct ListInfo *list, struct ListInfo *item);
1826 
testCStyleListItems(struct ListInfo * list)1827 void testCStyleListItems(struct ListInfo *list) {
1828   struct ConcreteListItem *x = malloc(sizeof(struct ConcreteListItem));
1829   list_add(list, &x->li); // will free 'x'.
1830 }
1831 
1832 // MEM34-C. Only free memory allocated dynamically
1833 // Second non-compliant example.
1834 // https://wiki.sei.cmu.edu/confluence/display/c/MEM34-C.+Only+free+memory+allocated+dynamically
1835 enum { BUFSIZE = 256 };
1836 
MEM34_C(void)1837 void MEM34_C(void) {
1838   char buf[BUFSIZE];
1839   char *p = (char *)realloc(buf, 2 * BUFSIZE);
1840   // expected-warning@-1{{Argument to realloc() is the address of the local \
1841 variable 'buf', which is not memory allocated by malloc() [unix.Malloc]}}
1842   if (p == NULL) {
1843     /* Handle error */
1844   }
1845 }
1846 
1847 (*crash_a)(); // expected-warning{{type specifier missing}}
1848 // A CallEvent without a corresponding FunctionDecl.
crash_b()1849 crash_b() { crash_a(); } // no-crash
1850 // expected-warning@-1{{type specifier missing}} expected-warning@-1{{non-void}}
1851 
1852 long *global_a;
realloc_crash()1853 void realloc_crash() {
1854   long *c = global_a;
1855   c--;
1856   realloc(c, 8); // no-crash
1857 } // expected-warning{{Potential memory leak [unix.Malloc]}}
1858 
1859 // ----------------------------------------------------------------------------
1860 // False negatives.
1861 
testMallocWithParam(int ** p)1862 void testMallocWithParam(int **p) {
1863   *p = (int*) malloc(sizeof(int));
1864   *p = 0; // FIXME: should warn here
1865 }
1866 
testMallocWithParam_2(int ** p)1867 void testMallocWithParam_2(int **p) {
1868   *p = (int*) malloc(sizeof(int)); // no-warning
1869 }
1870 
testPassToSystemHeaderFunctionIndirectly()1871 void testPassToSystemHeaderFunctionIndirectly() {
1872   int *p = malloc(4);
1873   p++;
1874   fakeSystemHeaderCallInt(p);
1875   // FIXME: This is a leak: if we think a system function won't free p, it
1876   // won't free (p-1) either.
1877 }
1878 
testMallocIntoMalloc()1879 void testMallocIntoMalloc() {
1880   StructWithPtr *s = malloc(sizeof(StructWithPtr));
1881   s->memP = malloc(sizeof(int));
1882   free(s);
1883 } // FIXME: should warn here
1884