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