1// RUN: %clang_analyze_cc1 -triple i386-apple-darwin9 -analyzer-checker=core,alpha.core.CastToStruct,alpha.security.ReturnPtrRange,alpha.security.ArrayBound -verify -fblocks -Wno-objc-root-class -Wno-strict-prototypes -Wno-error=implicit-function-declaration %s
2// RUN: %clang_analyze_cc1 -triple x86_64-apple-darwin9 -DTEST_64 -analyzer-checker=core,alpha.core.CastToStruct,alpha.security.ReturnPtrRange,alpha.security.ArrayBound -verify -fblocks   -Wno-objc-root-class -Wno-strict-prototypes -Wno-error=implicit-function-declaration %s
3
4typedef long unsigned int size_t;
5void *memcpy(void *, const void *, size_t);
6void *alloca(size_t);
7
8typedef struct objc_selector *SEL;
9typedef signed char BOOL;
10typedef int NSInteger;
11typedef unsigned int NSUInteger;
12typedef struct _NSZone NSZone;
13@class NSInvocation, NSMethodSignature, NSCoder, NSString, NSEnumerator;
14@protocol NSObject  - (BOOL)isEqual:(id)object; @end
15@protocol NSCopying  - (id)copyWithZone:(NSZone *)zone; @end
16@protocol NSMutableCopying  - (id)mutableCopyWithZone:(NSZone *)zone; @end
17@protocol NSCoding  - (void)encodeWithCoder:(NSCoder *)aCoder; @end
18@interface NSObject <NSObject> {} - (id)init; @end
19extern id NSAllocateObject(Class aClass, NSUInteger extraBytes, NSZone *zone);
20@interface NSString : NSObject <NSCopying, NSMutableCopying, NSCoding>
21- (NSUInteger)length;
22+ (id)stringWithUTF8String:(const char *)nullTerminatedCString;
23@end extern NSString * const NSBundleDidLoadNotification;
24@interface NSAssertionHandler : NSObject {}
25+ (NSAssertionHandler *)currentHandler;
26- (void)handleFailureInMethod:(SEL)selector object:(id)object file:(NSString *)fileName lineNumber:(NSInteger)line description:(NSString *)format,...;
27@end
28extern NSString * const NSConnectionReplyMode;
29
30#ifdef TEST_64
31typedef long long int64_t;
32typedef int64_t intptr_t;
33#else
34typedef int int32_t;
35typedef int32_t intptr_t;
36#endif
37
38//---------------------------------------------------------------------------
39// Test case 'checkaccess_union' differs for region store and basic store.
40// The basic store doesn't reason about compound literals, so the code
41// below won't fire an "uninitialized value" warning.
42//---------------------------------------------------------------------------
43
44// PR 2948 (testcase; crash on VisitLValue for union types)
45// http://llvm.org/bugs/show_bug.cgi?id=2948
46void checkaccess_union(void) {
47  int ret = 0, status;
48  // Since RegionStore doesn't handle unions yet,
49  // this branch condition won't be triggered
50  // as involving an uninitialized value.
51  if (((((__extension__ (((union {  // no-warning
52    __typeof (status) __in; int __i;}
53    )
54    {
55      .__in = (status)}
56      ).__i))) & 0xff00) >> 8) == 1)
57        ret = 1;
58}
59
60// Check our handling of fields being invalidated by function calls.
61struct test2_struct { int x; int y; char* s; };
62void test2_help(struct test2_struct* p);
63
64char test2(void) {
65  struct test2_struct s;
66  test2_help(&s);
67  char *p = 0;
68
69  if (s.x > 1) {
70    if (s.s != 0) {
71      p = "hello";
72    }
73  }
74
75  if (s.x > 1) {
76    if (s.s != 0) {
77      return *p;
78    }
79  }
80
81  return 'a';
82}
83
84// BasicStore handles this case incorrectly because it doesn't reason about
85// the value pointed to by 'x' and thus creates different symbolic values
86// at the declarations of 'a' and 'b' respectively.  RegionStore handles
87// it correctly. See the companion test in 'misc-ps-basic-store.m'.
88void test_trivial_symbolic_comparison_pointer_parameter(int *x) {
89  int a = *x;
90  int b = *x;
91  if (a != b) {
92    int *p = 0;
93    *p = 0xDEADBEEF;     // no-warning
94  }
95}
96
97// This is a modified test from 'misc-ps.m'.  Here we have the extra
98// NULL dereferences which are pruned out by RegionStore's symbolic reasoning
99// of fields.
100typedef struct _BStruct { void *grue; } BStruct;
101void testB_aux(void *ptr);
102
103void testB(BStruct *b) {
104  {
105    int *__gruep__ = ((int *)&((b)->grue));
106    int __gruev__ = *__gruep__;
107    int __gruev2__ = *__gruep__;
108    if (__gruev__ != __gruev2__) {
109      int *p = 0;
110      *p = 0xDEADBEEF; // no-warning
111    }
112
113    testB_aux(__gruep__);
114  }
115  {
116    int *__gruep__ = ((int *)&((b)->grue));
117    int __gruev__ = *__gruep__;
118    int __gruev2__ = *__gruep__;
119    if (__gruev__ != __gruev2__) {
120      int *p = 0;
121      *p = 0xDEADBEEF; // no-warning
122    }
123
124    if (~0 != __gruev__) {}
125  }
126}
127
128void testB_2(BStruct *b) {
129  {
130    int **__gruep__ = ((int **)&((b)->grue));
131    int *__gruev__ = *__gruep__;
132    testB_aux(__gruep__);
133  }
134  {
135    int **__gruep__ = ((int **)&((b)->grue));
136    int *__gruev__ = *__gruep__;
137    if ((int*)~0 != __gruev__) {}
138  }
139}
140
141// This test case is a reduced case of a caching bug discovered by an
142// assertion failure in RegionStoreManager::BindArray.  Essentially the
143// DeclStmt is evaluated twice, but on the second loop iteration the
144// engine caches out.  Previously a false transition would cause UnknownVal
145// to bind to the variable, firing an assertion failure.  This bug was fixed
146// in r76262.
147void test_declstmt_caching(void) {
148again:
149  {
150    const char a[] = "I like to crash";
151    goto again;
152  }
153}
154
155//===----------------------------------------------------------------------===//
156// Reduced test case from <rdar://problem/7114618>.
157// Basically a null check is performed on the field value, which is then
158// assigned to a variable and then checked again.
159//===----------------------------------------------------------------------===//
160struct s_7114618 { int *p; };
161void test_rdar_7114618(struct s_7114618 *s) {
162  if (s->p) {
163    int *p = s->p;
164    if (!p) {
165      // Infeasible
166      int *dead = 0;
167      *dead = 0xDEADBEEF; // no-warning
168    }
169  }
170}
171
172// Test pointers increment correctly.
173void f(void) {
174  int a[2];
175  a[1] = 3;
176  int *p = a;
177  p++;
178  if (*p != 3) {
179    int *q = 0;
180    *q = 3; // no-warning
181  }
182}
183
184//===----------------------------------------------------------------------===//
185// <rdar://problem/7185607>
186// Bit-fields of a struct should be invalidated when blasting the entire
187// struct with an integer constant.
188//===----------------------------------------------------------------------===//
189struct test_7185607 {
190  int x : 10;
191  int y : 22;
192};
193int rdar_test_7185607(void) {
194  struct test_7185607 s; // Uninitialized.
195  *((unsigned *) &s) = 0U;
196  return s.x; // no-warning
197}
198
199//===----------------------------------------------------------------------===//
200// <rdar://problem/7242006> [RegionStore] compound literal assignment with
201//  floats not honored
202// This test case is mirrored in misc-ps.m, but this case is a negative.
203//===----------------------------------------------------------------------===//
204typedef float CGFloat;
205typedef struct _NSSize {
206    CGFloat width;
207    CGFloat height;
208} NSSize;
209
210CGFloat rdar7242006_negative(CGFloat x) {
211  NSSize y;
212  return y.width; // expected-warning{{garbage}}
213}
214
215//===----------------------------------------------------------------------===//
216// <rdar://problem/7249340> - Allow binding of values to symbolic regions.
217// This test case shows how RegionStore tracks the value bound to 'x'
218// after the assignment.
219//===----------------------------------------------------------------------===//
220typedef int* ptr_rdar_7249340;
221void rdar_7249340(ptr_rdar_7249340 x) {
222  *x = 1;
223  if (*x)
224    return;
225  int *p = 0;   // This is unreachable.
226  *p = 0xDEADBEEF; // no-warning
227}
228
229//===----------------------------------------------------------------------===//
230// <rdar://problem/7249327> - This test case tests both value tracking of
231// array values and that we handle symbolic values that are casted
232// between different integer types.  Note the assignment 'n = *a++'; here
233// 'n' is and 'int' and '*a' is 'unsigned'.  Previously we got a false positive
234// at 'x += *b++' (undefined value) because we got a false path.
235//===----------------------------------------------------------------------===//
236int rdar_7249327_aux(void);
237
238void rdar_7249327(unsigned int A[2*32]) {
239  int B[2*32];
240  int *b;
241  unsigned int *a;
242  int x = 0;
243
244  int n;
245
246  a = A;
247  b = B;
248
249  n = *a++;
250  if (n)
251    *b++ = rdar_7249327_aux();
252
253  a = A;
254  b = B;
255
256  n = *a++;
257  if (n)
258    x += *b++; // no-warning
259}
260
261//===----------------------------------------------------------------------===//
262// <rdar://problem/6914474> - Check that 'x' is invalidated because its
263// address is passed in as a value to a struct.
264//===----------------------------------------------------------------------===//
265struct doodad_6914474 { int *v; };
266extern void prod_6914474(struct doodad_6914474 *d);
267int rdar_6914474(void) {
268  int x;
269  struct doodad_6914474 d;
270  d.v = &x;
271  prod_6914474(&d);
272  return x; // no-warning
273}
274
275// Test invalidation of a single field.
276struct s_test_field_invalidate {
277  int x;
278};
279extern void test_invalidate_field(int *x);
280int test_invalidate_field_test(void) {
281  struct s_test_field_invalidate y;
282  test_invalidate_field(&y.x);
283  return y.x; // no-warning
284}
285int test_invalidate_field_test_positive(void) {
286  struct s_test_field_invalidate y;
287  return y.x; // expected-warning{{garbage}}
288}
289
290// This test case illustrates how a typeless array of bytes casted to a
291// struct should be treated as initialized.  RemoveDeadBindings previously
292// had a bug that caused 'x' to lose its default symbolic value after the
293// assignment to 'p', thus causing 'p->z' to evaluate to "undefined".
294struct ArrayWrapper { unsigned char y[16]; };
295struct WrappedStruct { unsigned z; };
296
297void test_handle_array_wrapper_helper();
298
299int test_handle_array_wrapper(void) {
300  struct ArrayWrapper x;
301  test_handle_array_wrapper_helper(&x);
302  struct WrappedStruct *p = (struct WrappedStruct*) x.y; // expected-warning{{Casting a non-structure type to a structure type and accessing a field can lead to memory access errors or data corruption}}
303  return p->z;  // no-warning
304}
305
306//===----------------------------------------------------------------------===//
307// <rdar://problem/7261075> [RegionStore] crash when
308//   handling load: '*((unsigned int *)"????")'
309//===----------------------------------------------------------------------===//
310
311int rdar_7261075(void) {
312  unsigned int var = 0;
313  if (var == *((unsigned int *)"????"))
314    return 1;
315  return 0;
316}
317
318//===----------------------------------------------------------------------===//
319// <rdar://problem/7275774> false path due to limited pointer
320//                          arithmetic constraints
321//===----------------------------------------------------------------------===//
322
323void rdar_7275774(void *data, unsigned n) {
324  if (!(data || n == 0))
325    return;
326
327  unsigned short *p = (unsigned short*) data;
328  unsigned short *q = p + (n / 2);
329
330  if (p < q) {
331    // If we reach here, 'p' cannot be null.  If 'p' is null, then 'n' must
332    // be '0', meaning that this branch is not feasible.
333    *p = *q; // no-warning
334  }
335}
336
337//===----------------------------------------------------------------------===//
338// <rdar://problem/7312221>
339//
340//  Test that Objective-C instance variables aren't prematurely pruned
341//  from the analysis state.
342//===----------------------------------------------------------------------===//
343
344struct rdar_7312221_value { int x; };
345
346@interface RDar7312221
347{
348  struct rdar_7312221_value *y;
349}
350- (void) doSomething_7312221;
351@end
352
353extern struct rdar_7312221_value *rdar_7312221_helper(void);
354extern int rdar_7312221_helper_2(id o);
355extern void rdar_7312221_helper_3(int z);
356
357@implementation RDar7312221
358- (void) doSomething_7312221 {
359  if (y == 0) {
360    y = rdar_7312221_helper();
361    if (y != 0) {
362      y->x = rdar_7312221_helper_2(self);
363      // The following use of 'y->x' previously triggered a null dereference, as the value of 'y'
364      // before 'y = rdar_7312221_helper()' would be used.
365      rdar_7312221_helper_3(y->x); // no-warning
366    }
367  }
368}
369@end
370
371struct rdar_7312221_container {
372  struct rdar_7312221_value *y;
373};
374
375extern int rdar_7312221_helper_4(struct rdar_7312221_container *s);
376
377// This test case essentially matches the one in [RDar7312221 doSomething_7312221].
378void doSomething_7312221_with_struct(struct rdar_7312221_container *Self) {
379  if (Self->y == 0) {
380    Self->y = rdar_7312221_helper();
381    if (Self->y != 0) {
382      Self->y->x = rdar_7312221_helper_4(Self);
383      rdar_7312221_helper_3(Self->y->x); // no-warning
384    }
385  }
386}
387
388//===----------------------------------------------------------------------===//
389// <rdar://problem/7332673> - Just more tests cases for regions
390//===----------------------------------------------------------------------===//
391
392void rdar_7332673_test1(void) {
393    char value[1];
394    if ( *(value) != 1 ) {} // expected-warning{{The left operand of '!=' is a garbage value}}
395}
396int rdar_7332673_test2_aux(char *x);
397void rdar_7332673_test2(void) {
398    char *value;
399    if ( rdar_7332673_test2_aux(value) != 1 ) {} // expected-warning{{1st function call argument is an uninitialized value}}
400}
401
402//===----------------------------------------------------------------------===//
403// <rdar://problem/7347252>: Because of a bug in
404//   RegionStoreManager::RemoveDeadBindings(), the symbol for s->session->p
405//   would incorrectly be pruned from the state after the call to
406//   rdar7347252_malloc1(), and would incorrectly result in a warning about
407//   passing a null pointer to rdar7347252_memcpy().
408//===----------------------------------------------------------------------===//
409
410struct rdar7347252_AA { char *p;};
411typedef struct {
412 struct rdar7347252_AA *session;
413 int t;
414 char *q;
415} rdar7347252_SSL1;
416
417int rdar7347252_f(rdar7347252_SSL1 *s);
418char *rdar7347252_malloc1(int);
419char *rdar7347252_memcpy1(char *d, char *s, int n) __attribute__((nonnull (1,2)));
420
421int rdar7347252(rdar7347252_SSL1 *s) {
422 rdar7347252_f(s);  // the SymbolicRegion of 's' is set a default binding of conjured symbol
423 if (s->session->p == ((void*)0)) {
424   if ((s->session->p = rdar7347252_malloc1(10)) == ((void*)0)) {
425     return 0;
426   }
427   rdar7347252_memcpy1(s->session->p, "aa", 2); // no-warning
428 }
429 return 0;
430}
431
432//===----------------------------------------------------------------------===//
433// PR 5316 - "crash when accessing field of lazy compound value"
434//  Previously this caused a crash at the MemberExpr '.chr' when loading
435//  a field value from a LazyCompoundVal
436//===----------------------------------------------------------------------===//
437
438typedef unsigned int pr5316_wint_t;
439typedef pr5316_wint_t pr5316_REFRESH_CHAR;
440typedef struct {
441  pr5316_REFRESH_CHAR chr;
442}
443pr5316_REFRESH_ELEMENT;
444static void pr5316(pr5316_REFRESH_ELEMENT *dst, const pr5316_REFRESH_ELEMENT *src) {
445  while ((*dst++ = *src++).chr != L'\0')  ;
446}
447
448//===----------------------------------------------------------------------===//
449// Exercise creating ElementRegion with symbolic super region.
450//===----------------------------------------------------------------------===//
451void element_region_with_symbolic_superregion(int* p) {
452  int *x;
453  int a;
454  if (p[0] == 1)
455    x = &a;
456  if (p[0] == 1)
457    (void)*x; // no-warning
458}
459
460//===----------------------------------------------------------------------===//
461// Test returning an out-of-bounds pointer (CWE-466)
462//===----------------------------------------------------------------------===//
463
464static int test_cwe466_return_outofbounds_pointer_a[10]; // expected-note{{Original object declared here}}
465int *test_cwe466_return_outofbounds_pointer(void) {
466  int *p = test_cwe466_return_outofbounds_pointer_a+11;
467  return p; // expected-warning{{Returned pointer value points outside the original object}}
468            // expected-note@-1{{Original object 'test_cwe466_return_outofbounds_pointer_a' is an array of 10 'int' objects, returned pointer points at index 11}}
469}
470
471//===----------------------------------------------------------------------===//
472// PR 3135 - Test case that shows that a variable may get invalidated when its
473// address is included in a structure that is passed-by-value to an unknown function.
474//===----------------------------------------------------------------------===//
475
476typedef struct { int *a; } pr3135_structure;
477int pr3135_bar(pr3135_structure *x);
478int pr3135(void) {
479  int x;
480  pr3135_structure y = { &x };
481  // the call to pr3135_bar may initialize x
482  if (pr3135_bar(&y) && x) // no-warning
483    return 1;
484  return 0;
485}
486
487//===----------------------------------------------------------------------===//
488// <rdar://problem/7403269> - Test that we handle compound initializers with
489// partially unspecified array values. Previously this caused a crash.
490//===----------------------------------------------------------------------===//
491
492typedef struct RDar7403269 {
493  unsigned x[10];
494  unsigned y;
495} RDar7403269;
496
497void rdar7403269(void) {
498  RDar7403269 z = { .y = 0 };
499  if (z.x[4] == 0)
500    return;
501  int *p = 0;
502  *p = 0xDEADBEEF; // no-warning
503}
504
505typedef struct RDar7403269_b {
506  struct zorg { int w; int k; } x[10];
507  unsigned y;
508} RDar7403269_b;
509
510void rdar7403269_b(void) {
511  RDar7403269_b z = { .y = 0 };
512  if (z.x[5].w == 0)
513    return;
514  int *p = 0;
515  *p = 0xDEADBEEF; // no-warning
516}
517
518void rdar7403269_b_pos(void) {
519  RDar7403269_b z = { .y = 0 };
520  if (z.x[5].w == 1)
521    return;
522  int *p = 0;
523  *p = 0xDEADBEEF; // expected-warning{{Dereference of null pointer}}
524}
525
526
527//===----------------------------------------------------------------------===//
528// Test that incrementing a non-null pointer results in a non-null pointer.
529// (<rdar://problem/7191542>)
530//===----------------------------------------------------------------------===//
531
532void test_increment_nonnull_rdar_7191542(const char *path) {
533  const char *alf = 0;
534
535  for (;;) {
536    // When using basic-store, we get a null dereference here because we lose information
537    // about path after the pointer increment.
538    char c = *path++; // no-warning
539    if (c == 'a') {
540      alf = path;
541    }
542
543    if (alf)
544      return;
545  }
546}
547
548//===----------------------------------------------------------------------===//
549// Test that the store (implicitly) tracks values for doubles/floats that are
550// uninitialized (<rdar://problem/6811085>)
551//===----------------------------------------------------------------------===//
552
553double rdar_6811085(void) {
554  double u;
555  return u + 10; // expected-warning{{The left operand of '+' is a garbage value}}
556}
557
558//===----------------------------------------------------------------------===//
559// Path-sensitive tests for blocks.
560//===----------------------------------------------------------------------===//
561
562void indirect_block_call(void (^f)(void));
563
564int blocks_1(int *p, int z) {
565  __block int *q = 0;
566  void (^bar)(void) = ^{ q = p; };
567
568  if (z == 1) {
569    // The call to 'bar' might cause 'q' to be invalidated.
570    bar();
571    *q = 0x1; // no-warning
572  }
573  else if (z == 2) {
574    // The function 'indirect_block_call' might invoke bar, thus causing
575    // 'q' to possibly be invalidated.
576    indirect_block_call(bar);
577    *q = 0x1; // no-warning
578  }
579  else {
580    *q = 0xDEADBEEF; // expected-warning{{Dereference of null pointer}}
581  }
582  return z;
583}
584
585int blocks_2(int *p, int z) {
586  int *q = 0;
587  void (^bar)(int **) = ^(int **r){ *r = p; };
588
589  if (z) {
590    // The call to 'bar' might cause 'q' to be invalidated.
591    bar(&q);
592    *q = 0x1; // no-warning
593  }
594  else {
595    *q = 0xDEADBEEF; // expected-warning{{Dereference of null pointer}}
596  }
597  return z;
598}
599
600// Test that the value of 'x' is considered invalidated after the block
601// is passed as an argument to the message expression.
602typedef void (^RDar7582031CB)(void);
603@interface RDar7582031
604- rdar7582031:RDar7582031CB;
605- rdar7582031_b:RDar7582031CB;
606@end
607
608// Test with one block.
609unsigned rdar7582031(RDar7582031 *o) {
610  __block unsigned x;
611  [o rdar7582031:^{ x = 1; }];
612  return x; // no-warning
613}
614
615// Test with two blocks.
616unsigned long rdar7582031_b(RDar7582031 *o) {
617  __block unsigned y;
618  __block unsigned long x;
619  [o rdar7582031:^{ y = 1; }];
620  [o rdar7582031_b:^{ x = 1LL; }];
621  return x + (unsigned long) y; // no-warning
622}
623
624// Show we get an error when 'o' is null because the message
625// expression has no effect.
626unsigned long rdar7582031_b2(RDar7582031 *o) {
627  __block unsigned y;
628  __block unsigned long x;
629  if (o)
630    return 1;
631  [o rdar7582031:^{ y = 1; }];
632  [o rdar7582031_b:^{ x = 1LL; }];
633  return x + (unsigned long) y; // expected-warning{{The left operand of '+' is a garbage value}}
634}
635
636// Show that we handle static variables also getting invalidated.
637void rdar7582031_aux(void (^)(void));
638RDar7582031 *rdar7582031_aux_2(void);
639
640unsigned rdar7582031_static(void) {
641  static RDar7582031 *o = 0;
642  rdar7582031_aux(^{ o = rdar7582031_aux_2(); });
643
644  __block unsigned x;
645  [o rdar7582031:^{ x = 1; }];
646  return x; // no-warning
647}
648
649//===----------------------------------------------------------------------===//
650// <rdar://problem/7462324> - Test that variables passed using __blocks
651//  are not treated as being uninitialized.
652//===----------------------------------------------------------------------===//
653
654typedef void (^RDar_7462324_Callback)(id obj);
655
656@interface RDar7462324
657- (void) foo:(id)target;
658- (void) foo_positive:(id)target;
659
660@end
661
662@implementation RDar7462324
663- (void) foo:(id)target {
664  __block RDar_7462324_Callback builder = ((void*) 0);
665  builder = ^(id object) {
666    if (object) {
667      builder(self); // no-warning
668    }
669  };
670  builder(target);
671}
672- (void) foo_positive:(id)target {
673  __block RDar_7462324_Callback builder = ((void*) 0);
674  builder = ^(id object) {
675    id x;
676    if (object) {
677      builder(x); // expected-warning{{1st block call argument is an uninitialized value}}
678    }
679  };
680  builder(target);
681}
682@end
683
684//===----------------------------------------------------------------------===//
685// <rdar://problem/7468209> - Scanning for live variables within a block should
686//  not crash on variables passed by reference via __block.
687//===----------------------------------------------------------------------===//
688
689int rdar7468209_aux(void);
690void rdar7468209_aux_2(void);
691
692void rdar7468209(void) {
693  __block int x = 0;
694  ^{
695    x = rdar7468209_aux();
696    // We need a second statement so that 'x' would be removed from the store if it wasn't
697    // passed by reference.
698    rdar7468209_aux_2();
699  }();
700}
701
702//===----------------------------------------------------------------------===//
703// PR 5857 - Test loading an integer from a byte array that has also been
704//  reinterpreted to be loaded as a field.
705//===----------------------------------------------------------------------===//
706
707typedef struct { int x; } TestFieldLoad;
708int pr5857(char *src) {
709  TestFieldLoad *tfl = (TestFieldLoad *) (intptr_t) src;
710  int y = tfl->x;
711  long long *z = (long long *) (intptr_t) src;
712  long long w = 0;
713  int n = 0;
714  for (n = 0; n < y; ++n) {
715    // Previously we crashed analyzing this statement.
716    w = *z++;
717  }
718  return 1;
719}
720
721//===----------------------------------------------------------------------===//
722// PR 4358 - Without field-sensitivity, this code previously triggered
723//  a false positive that 'uninit' could be uninitialized at the call
724//  to pr4358_aux().
725//===----------------------------------------------------------------------===//
726
727struct pr4358 {
728  int bar;
729  int baz;
730};
731void pr4358_aux(int x);
732void pr4358(struct pr4358 *pnt) {
733  int uninit;
734  if (pnt->bar < 3) {
735    uninit = 1;
736  } else if (pnt->baz > 2) {
737    uninit = 3;
738  } else if (pnt->baz <= 2) {
739    uninit = 2;
740  }
741  pr4358_aux(uninit); // no-warning
742}
743
744//===----------------------------------------------------------------------===//
745// <rdar://problem/7526777>
746// Test handling fields of values returned from function calls or
747// message expressions.
748//===----------------------------------------------------------------------===//
749
750typedef struct testReturn_rdar_7526777 {
751  int x;
752  int y;
753} testReturn_rdar_7526777;
754
755@interface TestReturnStruct_rdar_7526777
756- (testReturn_rdar_7526777) foo;
757@end
758
759int test_return_struct(TestReturnStruct_rdar_7526777 *x) {
760  return [x foo].x;
761}
762
763testReturn_rdar_7526777 test_return_struct_2_aux_rdar_7526777(void);
764
765int test_return_struct_2_rdar_7526777(void) {
766  return test_return_struct_2_aux_rdar_7526777().x;
767}
768
769//===----------------------------------------------------------------------===//
770// <rdar://problem/7527292> Assertion failed: (Op == BinaryOperator::Add ||
771//                                             Op == BinaryOperator::Sub)
772// This test case previously triggered an assertion failure due to a discrepancy
773// been the loaded/stored value in the array
774//===----------------------------------------------------------------------===//
775
776_Bool OSAtomicCompareAndSwapPtrBarrier( void *__oldValue, void *__newValue, void * volatile *__theValue );
777
778void rdar_7527292(void) {
779  static id Cache7527292[32];
780  for (signed long idx = 0;
781       idx < 32;
782       idx++) {
783    id v = Cache7527292[idx];
784    if (v && OSAtomicCompareAndSwapPtrBarrier(v, ((void*)0), (void * volatile *)(Cache7527292 + idx))) {
785    }
786  }
787}
788
789//===----------------------------------------------------------------------===//
790// <rdar://problem/7515938> - Handle initialization of incomplete arrays
791//  in structures using a compound value.  Previously this crashed.
792//===----------------------------------------------------------------------===//
793
794struct rdar_7515938 {
795  int x;
796  int y[];
797};
798
799const struct rdar_7515938 *rdar_7515938(void) {
800  static const struct rdar_7515938 z = { 0, { 1, 2 } };
801  if (z.y[0] != 1) {
802    int *p = 0;
803    *p = 0xDEADBEEF; // no-warning
804  }
805  return &z;
806}
807
808struct rdar_7515938_str {
809  int x;
810  char y[];
811};
812
813const struct rdar_7515938_str *rdar_7515938_str(void) {
814  static const struct rdar_7515938_str z = { 0, "hello" };
815  return &z;
816}
817
818//===----------------------------------------------------------------------===//
819// Assorted test cases from PR 4172.
820//===----------------------------------------------------------------------===//
821
822struct PR4172A_s { int *a; };
823
824void PR4172A_f2(struct PR4172A_s *p);
825
826int PR4172A_f1(void) {
827    struct PR4172A_s m;
828    int b[4];
829    m.a = b;
830    PR4172A_f2(&m);
831    return b[3]; // no-warning
832}
833
834struct PR4172B_s { int *a; };
835
836void PR4172B_f2(struct PR4172B_s *p);
837
838int PR4172B_f1(void) {
839    struct PR4172B_s m;
840    int x;
841    m.a = &x;
842    PR4172B_f2(&m);
843    return x; // no-warning
844}
845
846//===----------------------------------------------------------------------===//
847// Test invalidation of values in struct literals.
848//===----------------------------------------------------------------------===//
849
850struct s_rev96062 { int *x; int *y; };
851struct s_rev96062_nested { struct s_rev96062 z; };
852
853void test_a_rev96062_aux(struct s_rev96062 *s);
854void test_a_rev96062_aux2(struct s_rev96062_nested *s);
855
856int test_a_rev96062(void) {
857  int a, b;
858  struct s_rev96062 x = { &a, &b };
859  test_a_rev96062_aux(&x);
860  return a + b; // no-warning
861}
862int test_b_rev96062(void) {
863  int a, b;
864  struct s_rev96062 x = { &a, &b };
865  struct s_rev96062 z = x;
866  test_a_rev96062_aux(&z);
867  return a + b; // no-warning
868}
869int test_c_rev96062(void) {
870  int a, b;
871  struct s_rev96062 x = { &a, &b };
872  struct s_rev96062_nested w = { x };
873  struct s_rev96062_nested z = w;
874  test_a_rev96062_aux2(&z);
875  return a + b; // no-warning
876}
877
878//===----------------------------------------------------------------------===//
879// <rdar://problem/7242010> - The access to y[0] at the bottom previously
880//  was reported as an uninitialized value.
881//===----------------------------------------------------------------------===//
882
883char *rdar_7242010(int count, char **y) {
884  char **x = alloca((count + 4) * sizeof(*x));
885  x[0] = "hi";
886  x[1] = "there";
887  x[2] = "every";
888  x[3] = "body";
889  memcpy(x + 4, y, count * sizeof(*x));
890  y = x;
891  return y[0]; // no-warning
892}
893
894//===----------------------------------------------------------------------===//
895// <rdar://problem/7770737>
896//===----------------------------------------------------------------------===//
897
898struct rdar_7770737_s { intptr_t p; };
899void rdar_7770737_aux(struct rdar_7770737_s *p);
900int rdar_7770737(void)
901{
902  int x;
903
904  // Previously 'f' was not properly invalidated, causing the use of
905  // an uninitailized value below.
906  struct rdar_7770737_s f = { .p = (intptr_t)&x };
907  rdar_7770737_aux(&f);
908  return x; // no-warning
909}
910int rdar_7770737_pos(void)
911{
912  int x;
913  struct rdar_7770737_s f = { .p = (intptr_t)&x };
914  return x; // expected-warning{{Undefined or garbage value returned to caller}}
915}
916
917//===----------------------------------------------------------------------===//
918// Test handling of the implicit 'isa' field.  For now we don't do anything
919// interesting.
920//===----------------------------------------------------------------------===//
921
922void pr6302(id x, Class y) {
923  // This previously crashed the analyzer (reported in PR 6302)
924  x->isa  = y; // expected-warning {{assignment to Objective-C's isa is deprecated in favor of object_setClass()}}
925}
926
927//===----------------------------------------------------------------------===//
928// Specially handle global variables that are declared constant.  In the
929// example below, this forces the loop to take exactly 2 iterations.
930//===----------------------------------------------------------------------===//
931
932const int pr6288_L_N = 2;
933void pr6288_(void) {
934  int x[2];
935  int *px[2];
936  int i;
937  for (i = 0; i < pr6288_L_N; i++)
938    px[i] = &x[i];
939  *(px[0]) = 0; // no-warning
940}
941
942void pr6288_pos(int z) {
943  int x[2];
944  int *px[2];
945  int i;
946  for (i = 0; i < z; i++)
947    px[i] = &x[i]; // expected-warning{{Access out-of-bound array element (buffer overflow)}}
948  *(px[0]) = 0; // expected-warning{{Dereference of undefined pointer value}}
949}
950
951void pr6288_b(void) {
952  const int L_N = 2;
953  int x[2];
954  int *px[2];
955  int i;
956  for (i = 0; i < L_N; i++)
957    px[i] = &x[i];
958  *(px[0]) = 0; // no-warning
959}
960
961// <rdar://problem/7817800> - A bug in RemoveDeadBindings was causing instance variable bindings
962//  to get prematurely pruned from the state.
963@interface Rdar7817800 {
964  char *x;
965}
966- (void) rdar7817800_baz;
967@end
968
969char *rdar7817800_foobar(void);
970void rdar7817800_qux(void*);
971
972@implementation Rdar7817800
973- (void) rdar7817800_baz {
974  if (x)
975    rdar7817800_qux(x);
976  x = rdar7817800_foobar();
977  // Previously this triggered a bogus null dereference warning.
978  x[1] = 'a'; // no-warning
979}
980@end
981
982// PR 6036 - This test case triggered a crash inside StoreManager::CastRegion because the size
983// of 'unsigned long (*)[0]' is 0.
984struct pr6036_a { int pr6036_b; };
985struct pr6036_c;
986void u132monitk (struct pr6036_c *pr6036_d) {
987  (void) ((struct pr6036_a *) (unsigned long (*)[0]) ((char *) pr6036_d - 1))->pr6036_b; // expected-warning{{Casting a non-structure type to a structure type and accessing a field can lead to memory access errors or data corruption}}
988}
989
990// <rdar://problem/7813989> - ?-expressions used as a base of a member expression should be treated as an lvalue
991typedef struct rdar7813989_NestedVal { int w; } rdar7813989_NestedVal;
992typedef struct rdar7813989_Val { rdar7813989_NestedVal nv; } rdar7813989_Val;
993
994int rdar7813989(int x, rdar7813989_Val *a, rdar7813989_Val *b) {
995  // This previously crashed with an assertion failure.
996  int z = (x ? a->nv : b->nv).w;
997  return z + 1;
998}
999
1000// PR 6844 - Don't crash on vaarg expression.
1001typedef __builtin_va_list va_list;
1002void map(int srcID, ...) {
1003  va_list ap;
1004  int i;
1005  for (i = 0; i < srcID; i++) {
1006    int v = __builtin_va_arg(ap, int);
1007  }
1008}
1009
1010// PR 6854 - crash when casting symbolic memory address to a float
1011// Handle casting from a symbolic region to a 'float'.  This isn't
1012// really all that intelligent, but previously this caused a crash
1013// in SimpleSValuator.
1014void pr6854(void * arg) {
1015  void * a = arg;
1016  *(void**)a = arg;
1017  float f = *(float*) a;
1018}
1019
1020// <rdar://problem/8032791> False positive due to symbolic store not find
1021//  value because of 'const' qualifier
1022double rdar_8032791_2(void);
1023double rdar_8032791_1(void) {
1024   struct R8032791 { double x[2]; double y; }
1025   data[3] = {
1026     {{1.0, 3.0}, 3.0},  //  1   2   3
1027     {{1.0, 1.0}, 0.0},  // 1 1 2 2 3 3
1028     {{1.0, 3.0}, 1.0}   //    1   2   3
1029   };
1030
1031   double x = 0.0;
1032   for (unsigned i = 0 ; i < 3; i++) {
1033     const struct R8032791 *p = &data[i];
1034     x += p->y + rdar_8032791_2(); // no-warning
1035   }
1036   return x;
1037}
1038
1039// PR 7450 - Handle pointer arithmetic with __builtin_alloca
1040void pr_7450_aux(void *x);
1041void pr_7450(void) {
1042  void *p = __builtin_alloca(10);
1043  // Don't crash when analyzing the following statement.
1044  pr_7450_aux(p + 8);
1045}
1046
1047// <rdar://problem/8243408> - Symbolicate struct values returned by value.
1048struct s_rdar_8243408 { int x; };
1049extern struct s_rdar_8243408 rdar_8243408_aux(void);
1050void rdar_8243408(void) {
1051  struct s_rdar_8243408 a = { 1 }, *b = 0;
1052  while (a.x && !b)
1053    a = rdar_8243408_aux();
1054
1055  // Previously there was a false error here with 'b' being null.
1056  (void) (a.x && b->x); // no-warning
1057
1058  // Introduce a null deref to ensure we are checking this path.
1059  int *p = 0;
1060  *p = 0xDEADBEEF; // expected-warning{{Dereference of null pointer}}
1061}
1062
1063// <rdar://problem/8258814>
1064int r8258814(void)
1065{
1066  int foo;
1067  int * a = &foo;
1068  a[0] = 10;
1069  // Do not warn that the value of 'foo' is uninitialized.
1070  return foo; // no-warning
1071}
1072
1073// PR 8052 - Don't crash when reasoning about loads from a function address.\n
1074typedef unsigned int __uint32_t;
1075typedef unsigned long vm_offset_t;
1076typedef __uint32_t pd_entry_t;
1077typedef unsigned char u_char;
1078typedef unsigned int u_int;
1079typedef unsigned long u_long;
1080extern int      bootMP_size;
1081void            bootMP(void);
1082static void
1083pr8052(u_int boot_addr)
1084{
1085    int             x;
1086    int             size = *(int *) ((u_long) & bootMP_size);
1087    u_char         *src = (u_char *) ((u_long) bootMP);
1088    u_char         *dst = (u_char *) boot_addr + ((vm_offset_t) ((((((((1 <<
108912) / (sizeof(pd_entry_t))) - 1) - 1) - (260 - 2))) << 22) | ((0) << 12)));
1090#ifdef TEST_64
1091// expected-warning@-3 {{cast to 'u_char *' (aka 'unsigned char *') from smaller integer type 'u_int' (aka 'unsigned int')}}
1092#endif
1093    for (x = 0;
1094         x < size;
1095         ++x)
1096        *dst++ = *src++;
1097}
1098
1099// PR 8015 - don't return undefined values for arrays when using a valid
1100// symbolic index
1101int pr8015_A(void);
1102void pr8015_B(const char *);
1103
1104void pr8015_C(void) {
1105  int number = pr8015_A();
1106  const char *numbers[] = { "zero" };
1107  if (number == 0) {
1108      pr8015_B(numbers[number]); // no-warning
1109  }
1110}
1111
1112// Tests that we correctly handle that 'number' is perfectly constrained
1113// after 'if (number == 0)', allowing us to resolve that
1114// numbers[number] == numbers[0].
1115void pr8015_D_FIXME(void) {
1116  int number = pr8015_A();
1117  const char *numbers[] = { "zero" };
1118  if (number == 0) {
1119    if (numbers[number] == numbers[0])
1120      return;
1121    // Unreachable.
1122    int *p = 0;
1123    *p = 0xDEADBEEF; // no-warnng
1124  }
1125}
1126
1127void pr8015_E(void) {
1128  // Similar to pr8015_C, but number is allowed to be a valid range.
1129  unsigned number = pr8015_A();
1130  const char *numbers[] = { "zero", "one", "two" };
1131  if (number < 3) {
1132    pr8015_B(numbers[number]); // no-warning
1133  }
1134}
1135
1136void pr8015_F_FIXME(void) {
1137  // Similar to pr8015_E, but like pr8015_D we check if the pointer
1138  // is the same as one of the string literals.  The null dereference
1139  // here is not feasible in practice, so this is a false positive.
1140  int number = pr8015_A();
1141  const char *numbers[] = { "zero", "one", "two" };
1142  if (number < 3) {
1143    const char *p = numbers[number];
1144    if (p == numbers[0] || p == numbers[1] || p == numbers[2])
1145      return;
1146    int *q = 0;
1147    *q = 0xDEADBEEF; // expected-warning{{Dereference of null pointer}}
1148  }
1149}
1150
1151// PR 8141.  Previously the statement expression in the for loop caused
1152// the CFG builder to crash.
1153struct list_pr8141
1154{
1155  struct list_pr8141 *tail;
1156};
1157
1158struct list_pr8141 *
1159pr8141 (void) {
1160  struct list_pr8141 *items;
1161  for (;; items = ({ do { } while (0); items->tail; })) // expected-warning{{dereference of an undefined pointer value}}
1162    {
1163    }
1164}
1165
1166// Don't crash when building the CFG.
1167void do_not_crash(int x) {
1168  while (x - ({do {} while (0); x; })) {
1169  }
1170}
1171
1172// <rdar://problem/8424269> - Handle looking at the size of a VLA in
1173// ArrayBoundChecker.  Nothing intelligent (yet); just don't crash.
1174typedef struct RDar8424269_A {
1175  int RDar8424269_C;
1176} RDar8424269_A;
1177static void RDar8424269_B(RDar8424269_A *p, unsigned char *RDar8424269_D,
1178                          const unsigned char *RDar8424269_E, int RDar8424269_F,
1179    int b_w, int b_h, int dx, int dy) {
1180  int x, y, b, r, l;
1181  unsigned char tmp2t[3][RDar8424269_F * (32 + 8)];
1182  unsigned char *tmp2 = tmp2t[0];
1183  if (p && !p->RDar8424269_C)
1184    b = 15;
1185  tmp2 = tmp2t[1];
1186  if (b & 2) { // expected-warning{{The left operand of '&' is a garbage value}}
1187    for (y = 0; y < b_h; y++) {
1188      for (x = 0; x < b_w + 1; x++) {
1189        int am = 0;
1190        tmp2[x] = am;
1191      }
1192    }
1193  }
1194  tmp2 = tmp2t[2];
1195}
1196
1197// <rdar://problem/8642434> - Handle transparent unions with the NonNullParamChecker.
1198typedef union {
1199  struct rdar_8642434_typeA *_dq;
1200}
1201rdar_8642434_typeB __attribute__((transparent_union));
1202
1203__attribute__((visibility("default"))) __attribute__((__nonnull__)) __attribute__((__nothrow__))
1204void rdar_8642434_funcA(rdar_8642434_typeB object);
1205
1206void rdar_8642434_funcB(struct rdar_8642434_typeA *x, struct rdar_8642434_typeA *y) {
1207  rdar_8642434_funcA(x);
1208  if (!y)
1209    rdar_8642434_funcA(y); // expected-warning{{Null pointer passed to 1st parameter expecting 'nonnull'}}
1210}
1211
1212// <rdar://problem/8848957> - Handle loads and stores from a symbolic index
1213// into array without warning about an uninitialized value being returned.
1214// While RegionStore can't fully reason about this example, it shouldn't
1215// warn here either.
1216typedef struct s_test_rdar8848957 {
1217  int x, y, z;
1218} s_test_rdar8848957;
1219
1220s_test_rdar8848957 foo_rdar8848957(void);
1221int rdar8848957(int index) {
1222  s_test_rdar8848957 vals[10];
1223  vals[index] = foo_rdar8848957();
1224  return vals[index].x; // no-warning
1225}
1226
1227// PR 9049 - crash on symbolicating unions.  This test exists solely to
1228// test that the analyzer doesn't crash.
1229typedef struct pr9048_cdev *pr9048_cdev_t;
1230typedef union pr9048_abstracted_disklabel { void *opaque; } pr9048_disklabel_t;
1231struct pr9048_diskslice { pr9048_disklabel_t ds_label; };
1232struct pr9048_diskslices {
1233  int dss_secmult;
1234  struct pr9048_diskslice dss_slices[16];
1235};
1236void pr9048(pr9048_cdev_t dev, struct pr9048_diskslices * ssp, unsigned int slice)
1237{
1238  pr9048_disklabel_t     lp;
1239  struct pr9048_diskslice *sp;
1240  sp = &ssp->dss_slices[slice];
1241  if (ssp->dss_secmult == 1) {
1242  } else if ((lp = sp->ds_label).opaque != ((void *) 0)) {
1243  }
1244}
1245
1246// Test Store reference counting in the presence of Lazy compound values.
1247// This previously caused an infinite recursion.
1248typedef struct {} Rdar_9103310_A;
1249typedef struct Rdar_9103310_B Rdar_9103310_B_t;
1250struct Rdar_9103310_B {
1251  unsigned char           Rdar_9103310_C[101];
1252};
1253void Rdar_9103310_E(Rdar_9103310_A * x, struct Rdar_9103310_C * b) { // expected-warning {{declaration of 'struct Rdar_9103310_C' will not be visible outside of this function}}
1254  char Rdar_9103310_D[4][4] = { "a", "b", "c", "d"};
1255  int i;
1256  Rdar_9103310_B_t *y = (Rdar_9103310_B_t *) x;
1257  for (i = 0; i < 101; i++) {
1258    Rdar_9103310_F(b, "%2d%s ", (y->Rdar_9103310_C[i]) / 4, Rdar_9103310_D[(y->Rdar_9103310_C[i]) % 4]); // expected-warning {{call to undeclared function 'Rdar_9103310_F'; ISO C99 and later do not support implicit function declarations}}
1259  }
1260}
1261
1262// Test handling binding lazy compound values to a region and then have
1263// specific elements have other bindings.
1264int PR9455(void) {
1265  char arr[4] = "000";
1266  arr[0] = '1';
1267  if (arr[1] == '0')
1268    return 1;
1269  int *p = 0;
1270  *p = 0xDEADBEEF; // no-warning
1271  return 1;
1272}
1273int PR9455_2(void) {
1274  char arr[4] = "000";
1275  arr[0] = '1';
1276  if (arr[1] == '0') {
1277    int *p = 0;
1278    *p = 0xDEADBEEF; // expected-warning {{null}}
1279  }
1280  return 1;
1281}
1282
1283// Test initialization of substructs via lazy compound values.
1284typedef float RDar9163742_Float;
1285
1286typedef struct {
1287    RDar9163742_Float x, y;
1288} RDar9163742_Point;
1289typedef struct {
1290    RDar9163742_Float width, height;
1291} RDar9163742_Size;
1292typedef struct {
1293    RDar9163742_Point origin;
1294    RDar9163742_Size size;
1295} RDar9163742_Rect;
1296
1297extern  RDar9163742_Rect RDar9163742_RectIntegral(RDar9163742_Rect);
1298
1299RDar9163742_Rect RDar9163742_IntegralRect(RDar9163742_Rect frame)
1300{
1301    RDar9163742_Rect integralFrame;
1302    integralFrame.origin.x = frame.origin.x;
1303    integralFrame.origin.y = frame.origin.y;
1304    integralFrame.size = frame.size;
1305    return RDar9163742_RectIntegral(integralFrame); // no-warning; all fields initialized
1306}
1307
1308// Test correct handling of prefix '--' operator.
1309void rdar9444714(void) {
1310  int   x;
1311  char    str[ 32 ];
1312  char    buf[ 32 ];
1313  char *  dst;
1314  char *  ptr;
1315
1316  x = 1234;
1317  dst = str;
1318  ptr = buf;
1319  do
1320  {
1321    *ptr++ = (char)( '0' + ( x % 10 ) );
1322    x /= 10;
1323  } while( x > 0 );
1324
1325  while( ptr > buf )
1326  {
1327    *dst++ = *( --( ptr ) ); // no-warning
1328  }
1329  *dst = '\0';
1330}
1331
1332// Test handling symbolic elements with field accesses.
1333// <rdar://problem/11127008>
1334typedef struct {
1335    unsigned value;
1336} RDar11127008;
1337
1338signed rdar_11127008_index(void);
1339
1340static unsigned rdar_11127008(void) {
1341    RDar11127008 values[] = {{.value = 0}, {.value = 1}};
1342    signed index = rdar_11127008_index();
1343    if (index < 0) return 0;
1344    if (index >= 2) return 0;
1345    return values[index].value;
1346}
1347
1348// Test handling invalidating arrays passed to a block via captured
1349// pointer value (not a __block variable).
1350typedef void (^radar11125868_cb)(int *, unsigned);
1351
1352void rdar11125868_aux(radar11125868_cb cb);
1353
1354int rdar11125868(void) {
1355  int integersStackArray[1];
1356  int *integers = integersStackArray;
1357  rdar11125868_aux(^(int *integerValue, unsigned index) {
1358      integers[index] = integerValue[index];
1359    });
1360  return integers[0] == 0; // no-warning
1361}
1362
1363int rdar11125868_positive(void) {
1364  int integersStackArray[1];
1365  int *integers = integersStackArray;
1366  return integers[0] == 0; // expected-warning {{The left operand of '==' is a}}
1367}
1368