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