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