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