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