1// RUN: rm -rf %t
2// RUN: %clang_cc1 -fblocks -objcmt-migrate-annotation -objcmt-migrate-instancetype -objcmt-migrate-readwrite-property -mt-migrate-directory %t %s -x objective-c -triple x86_64-apple-darwin11
3// RUN: c-arcmt-test -mt-migrate-directory %t | arcmt-test -verify-transformed-files %s.result
4// RUN: %clang_cc1 -fblocks -triple x86_64-apple-darwin10 -fsyntax-only -x objective-c %s.result
5
6#ifndef CF_IMPLICIT_BRIDGING_ENABLED
7#if __has_feature(arc_cf_code_audited)
8#define CF_IMPLICIT_BRIDGING_ENABLED _Pragma("clang arc_cf_code_audited begin")
9#else
10#define CF_IMPLICIT_BRIDGING_ENABLED
11#endif
12#endif
13
14#ifndef CF_IMPLICIT_BRIDGING_DISABLED
15#if __has_feature(arc_cf_code_audited)
16#define CF_IMPLICIT_BRIDGING_DISABLED _Pragma("clang arc_cf_code_audited end")
17#else
18#define CF_IMPLICIT_BRIDGING_DISABLED
19#endif
20#endif
21
22#if __has_feature(attribute_ns_returns_retained)
23#define NS_RETURNS_RETAINED __attribute__((ns_returns_retained))
24#endif
25#if __has_feature(attribute_cf_returns_retained)
26#define CF_RETURNS_RETAINED __attribute__((cf_returns_retained))
27#endif
28#if __has_feature(attribute_ns_returns_not_retained)
29#define NS_RETURNS_NOT_RETAINED __attribute__((ns_returns_not_retained))
30#endif
31#if __has_feature(attribute_cf_returns_not_retained)
32#define CF_RETURNS_NOT_RETAINED __attribute__((cf_returns_not_retained))
33#endif
34#if __has_feature(attribute_ns_consumes_self)
35#define NS_CONSUMES_SELF __attribute__((ns_consumes_self))
36#endif
37#if __has_feature(attribute_ns_consumed)
38#define NS_CONSUMED __attribute__((ns_consumed))
39#endif
40#if __has_feature(attribute_cf_consumed)
41#define CF_CONSUMED __attribute__((cf_consumed))
42#endif
43#if __has_attribute(ns_returns_autoreleased)
44#define NS_RETURNS_AUTORELEASED __attribute__((ns_returns_autoreleased))
45#endif
46
47//===----------------------------------------------------------------------===//
48// The following code is reduced using delta-debugging from Mac OS X headers:
49//
50// #include <Cocoa/Cocoa.h>
51// #include <CoreFoundation/CoreFoundation.h>
52// #include <DiskArbitration/DiskArbitration.h>
53// #include <QuartzCore/QuartzCore.h>
54// #include <Quartz/Quartz.h>
55// #include <IOKit/IOKitLib.h>
56//
57// It includes the basic definitions for the test cases below.
58//===----------------------------------------------------------------------===//
59
60typedef unsigned int __darwin_natural_t;
61typedef unsigned long uintptr_t;
62typedef unsigned int uint32_t;
63typedef unsigned long long uint64_t;
64typedef unsigned int UInt32;
65typedef signed long CFIndex;
66typedef CFIndex CFByteOrder;
67typedef struct {
68    CFIndex location;
69    CFIndex length;
70} CFRange;
71static __inline__ __attribute__((always_inline)) CFRange CFRangeMake(CFIndex loc, CFIndex len) {
72    CFRange range;
73    range.location = loc;
74    range.length = len;
75    return range;
76}
77typedef const void * CFTypeRef;
78typedef const struct __CFString * CFStringRef;
79typedef const struct __CFAllocator * CFAllocatorRef;
80extern const CFAllocatorRef kCFAllocatorDefault;
81extern CFTypeRef CFRetain(CFTypeRef cf);
82extern void CFRelease(CFTypeRef cf);
83extern CFTypeRef CFMakeCollectable(CFTypeRef cf);
84typedef struct {
85}
86CFArrayCallBacks;
87extern const CFArrayCallBacks kCFTypeArrayCallBacks;
88typedef const struct __CFArray * CFArrayRef;
89typedef struct __CFArray * CFMutableArrayRef;
90extern CFMutableArrayRef CFArrayCreateMutable(CFAllocatorRef allocator, CFIndex capacity, const CFArrayCallBacks *callBacks);
91extern const void *CFArrayGetValueAtIndex(CFArrayRef theArray, CFIndex idx);
92extern void CFArrayAppendValue(CFMutableArrayRef theArray, const void *value);
93typedef struct {
94}
95CFDictionaryKeyCallBacks;
96extern const CFDictionaryKeyCallBacks kCFTypeDictionaryKeyCallBacks;
97typedef struct {
98}
99CFDictionaryValueCallBacks;
100extern const CFDictionaryValueCallBacks kCFTypeDictionaryValueCallBacks;
101typedef const struct __CFDictionary * CFDictionaryRef;
102typedef struct __CFDictionary * CFMutableDictionaryRef;
103extern CFMutableDictionaryRef CFDictionaryCreateMutable(CFAllocatorRef allocator, CFIndex capacity, const CFDictionaryKeyCallBacks *keyCallBacks, const CFDictionaryValueCallBacks *valueCallBacks);
104typedef UInt32 CFStringEncoding;
105enum {
106kCFStringEncodingMacRoman = 0,     kCFStringEncodingWindowsLatin1 = 0x0500,     kCFStringEncodingISOLatin1 = 0x0201,     kCFStringEncodingNextStepLatin = 0x0B01,     kCFStringEncodingASCII = 0x0600,     kCFStringEncodingUnicode = 0x0100,     kCFStringEncodingUTF8 = 0x08000100,     kCFStringEncodingNonLossyASCII = 0x0BFF      ,     kCFStringEncodingUTF16 = 0x0100,     kCFStringEncodingUTF16BE = 0x10000100,     kCFStringEncodingUTF16LE = 0x14000100,      kCFStringEncodingUTF32 = 0x0c000100,     kCFStringEncodingUTF32BE = 0x18000100,     kCFStringEncodingUTF32LE = 0x1c000100  };
107extern CFStringRef CFStringCreateWithCString(CFAllocatorRef alloc, const char *cStr, CFStringEncoding encoding);
108typedef double CFTimeInterval;
109typedef CFTimeInterval CFAbsoluteTime;
110extern CFAbsoluteTime CFAbsoluteTimeGetCurrent(void);
111typedef const struct __CFDate * CFDateRef;
112extern CFDateRef CFDateCreate(CFAllocatorRef allocator, CFAbsoluteTime at);
113extern CFAbsoluteTime CFDateGetAbsoluteTime(CFDateRef theDate);
114typedef __darwin_natural_t natural_t;
115typedef natural_t mach_port_name_t;
116typedef mach_port_name_t mach_port_t;
117typedef int kern_return_t;
118typedef kern_return_t mach_error_t;
119enum {
120kCFNumberSInt8Type = 1,     kCFNumberSInt16Type = 2,     kCFNumberSInt32Type = 3,     kCFNumberSInt64Type = 4,     kCFNumberFloat32Type = 5,     kCFNumberFloat64Type = 6,      kCFNumberCharType = 7,     kCFNumberShortType = 8,     kCFNumberIntType = 9,     kCFNumberLongType = 10,     kCFNumberLongLongType = 11,     kCFNumberFloatType = 12,     kCFNumberDoubleType = 13,      kCFNumberCFIndexType = 14,      kCFNumberNSIntegerType = 15,     kCFNumberCGFloatType = 16,     kCFNumberMaxType = 16    };
121typedef CFIndex CFNumberType;
122typedef const struct __CFNumber * CFNumberRef;
123extern CFNumberRef CFNumberCreate(CFAllocatorRef allocator, CFNumberType theType, const void *valuePtr);
124typedef const struct __CFAttributedString *CFAttributedStringRef;
125typedef struct __CFAttributedString *CFMutableAttributedStringRef;
126extern CFAttributedStringRef CFAttributedStringCreate(CFAllocatorRef alloc, CFStringRef str, CFDictionaryRef attributes) ;
127extern CFMutableAttributedStringRef CFAttributedStringCreateMutableCopy(CFAllocatorRef alloc, CFIndex maxLength, CFAttributedStringRef aStr) ;
128extern void CFAttributedStringSetAttribute(CFMutableAttributedStringRef aStr, CFRange range, CFStringRef attrName, CFTypeRef value) ;
129typedef signed char BOOL;
130typedef unsigned long NSUInteger;
131@class NSString, Protocol;
132extern void NSLog(NSString *format, ...) __attribute__((format(__NSString__, 1, 2)));
133typedef struct _NSZone NSZone;
134@class NSInvocation, NSMethodSignature, NSCoder, NSString, NSEnumerator;
135@protocol NSObject
136- (BOOL)isEqual:(id)object;
137- (id)retain;
138- (oneway void)release;
139- (id)autorelease;
140- (NSString *)description;
141- (id)init;
142@end
143@protocol NSCopying
144- (id)copyWithZone:(NSZone *)zone;
145@end
146@protocol NSMutableCopying  - (id)mutableCopyWithZone:(NSZone *)zone;
147@end
148@protocol NSCoding  - (void)encodeWithCoder:(NSCoder *)aCoder;
149@end
150@interface NSObject <NSObject> {}
151+ (id)allocWithZone:(NSZone *)zone;
152+ (id)alloc;
153+ (id)new;
154- (void)dealloc;
155@end
156@interface NSObject (NSCoderMethods)
157- (id)awakeAfterUsingCoder:(NSCoder *)aDecoder;
158@end
159extern id NSAllocateObject(Class aClass, NSUInteger extraBytes, NSZone *zone);
160typedef struct {
161}
162NSFastEnumerationState;
163@protocol NSFastEnumeration
164- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len;
165@end
166@class NSString, NSDictionary;
167@interface NSValue : NSObject <NSCopying, NSCoding>  - (void)getValue:(void *)value;
168@end
169@interface NSNumber : NSValue
170- (char)charValue;
171- (id)initWithInt:(int)value;
172+ (NSNumber *)numberWithInt:(int)value;
173@end
174@class NSString;
175@interface NSArray : NSObject <NSCopying, NSMutableCopying, NSCoding, NSFastEnumeration>
176- (NSUInteger)count;
177- (id)initWithObjects:(const id [])objects count:(NSUInteger)cnt;
178+ (id)arrayWithObject:(id)anObject;
179+ (id)arrayWithObjects:(const id [])objects count:(NSUInteger)cnt;
180+ (id)arrayWithObjects:(id)firstObj, ... __attribute__((sentinel(0,1)));
181- (id)initWithObjects:(id)firstObj, ... __attribute__((sentinel(0,1)));
182- (id)initWithArray:(NSArray *)array;
183@end  @interface NSArray (NSArrayCreation)  + (id)array;
184@end       @interface NSAutoreleasePool : NSObject {
185}
186- (void)drain;
187@end extern NSString * const NSBundleDidLoadNotification;
188typedef double NSTimeInterval;
189@interface NSDate : NSObject <NSCopying, NSCoding>  - (NSTimeInterval)timeIntervalSinceReferenceDate;
190@end            typedef unsigned short unichar;
191@interface NSString : NSObject <NSCopying, NSMutableCopying, NSCoding>
192- (NSUInteger)length;
193- (NSString *)stringByAppendingString:(NSString *)aString;
194- ( const char *)UTF8String;
195- (id)initWithUTF8String:(const char *)nullTerminatedCString;
196+ (id)stringWithUTF8String:(const char *)nullTerminatedCString;
197@end        @class NSString, NSURL, NSError;
198@interface NSData : NSObject <NSCopying, NSMutableCopying, NSCoding>  - (NSUInteger)length;
199+ (id)dataWithBytesNoCopy:(void *)bytes length:(NSUInteger)length;
200+ (id)dataWithBytesNoCopy:(void *)bytes length:(NSUInteger)length freeWhenDone:(BOOL)b;
201@end   @class NSLocale, NSDate, NSCalendar, NSTimeZone, NSError, NSArray, NSMutableDictionary;
202@interface NSDictionary : NSObject <NSCopying, NSMutableCopying, NSCoding, NSFastEnumeration>
203- (NSUInteger)count;
204+ (id)dictionaryWithObjects:(NSArray *)objects forKeys:(NSArray *)keys;
205+ (id)dictionaryWithObjects:(const id [])objects forKeys:(const id <NSCopying> [])keys count:(NSUInteger)cnt;
206@end
207@interface NSMutableDictionary : NSDictionary  - (void)removeObjectForKey:(id)aKey;
208- (void)setObject:(id)anObject forKey:(id)aKey;
209@end  @interface NSMutableDictionary (NSMutableDictionaryCreation)  + (id)dictionaryWithCapacity:(NSUInteger)numItems;
210@end  typedef double CGFloat;
211struct CGSize {
212};
213typedef struct CGSize CGSize;
214struct CGRect {
215};
216typedef struct CGRect CGRect;
217typedef mach_port_t io_object_t;
218typedef char io_name_t[128];
219typedef io_object_t io_iterator_t;
220typedef io_object_t io_service_t;
221typedef struct IONotificationPort * IONotificationPortRef;
222typedef void (*IOServiceMatchingCallback)(  void * refcon,  io_iterator_t iterator );
223io_service_t IOServiceGetMatchingService(  mach_port_t masterPort,  CFDictionaryRef matching );
224kern_return_t IOServiceGetMatchingServices(  mach_port_t masterPort,  CFDictionaryRef matching,  io_iterator_t * existing );
225kern_return_t IOServiceAddNotification(  mach_port_t masterPort,  const io_name_t notificationType,  CFDictionaryRef matching,  mach_port_t wakePort,  uintptr_t reference,  io_iterator_t * notification ) __attribute__((deprecated)); // expected-note {{'IOServiceAddNotification' declared here}}
226kern_return_t IOServiceAddMatchingNotification(  IONotificationPortRef notifyPort,  const io_name_t notificationType,  CFDictionaryRef matching,         IOServiceMatchingCallback callback,         void * refCon,  io_iterator_t * notification );
227CFMutableDictionaryRef IOServiceMatching(  const char * name );
228CFMutableDictionaryRef IOServiceNameMatching(  const char * name );
229CFMutableDictionaryRef IOBSDNameMatching(  mach_port_t masterPort,  uint32_t options,  const char * bsdName );
230CFMutableDictionaryRef IOOpenFirmwarePathMatching(  mach_port_t masterPort,  uint32_t options,  const char * path );
231CFMutableDictionaryRef IORegistryEntryIDMatching(  uint64_t entryID );
232typedef struct __DASession * DASessionRef;
233extern DASessionRef DASessionCreate( CFAllocatorRef allocator );
234typedef struct __DADisk * DADiskRef;
235extern DADiskRef DADiskCreateFromBSDName( CFAllocatorRef allocator, DASessionRef session, const char * name );
236extern DADiskRef DADiskCreateFromIOMedia( CFAllocatorRef allocator, DASessionRef session, io_service_t media );
237extern CFDictionaryRef DADiskCopyDescription( DADiskRef disk );
238extern DADiskRef DADiskCopyWholeDisk( DADiskRef disk );
239@interface NSTask : NSObject - (id)init;
240@end                    typedef struct CGColorSpace *CGColorSpaceRef;
241typedef struct CGImage *CGImageRef;
242typedef struct CGLayer *CGLayerRef;
243@interface NSResponder : NSObject <NSCoding> {
244}
245@end    @protocol NSAnimatablePropertyContainer      - (id)animator;
246@end  extern NSString *NSAnimationTriggerOrderIn ;
247@interface NSView : NSResponder  <NSAnimatablePropertyContainer>  {
248}
249@end @protocol NSValidatedUserInterfaceItem - (SEL)action;
250@end   @protocol NSUserInterfaceValidations - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)anItem;
251@end  @class NSDate, NSDictionary, NSError, NSException, NSNotification;
252@class NSTextField, NSPanel, NSArray, NSWindow, NSImage, NSButton, NSError;
253@interface NSApplication : NSResponder <NSUserInterfaceValidations> {
254}
255- (void)beginSheet:(NSWindow *)sheet modalForWindow:(NSWindow *)docWindow modalDelegate:(id)modalDelegate didEndSelector:(SEL)didEndSelector contextInfo:(void *)contextInfo;
256@end   enum {
257NSTerminateCancel = 0,         NSTerminateNow = 1,         NSTerminateLater = 2 };
258typedef NSUInteger NSApplicationTerminateReply;
259@protocol NSApplicationDelegate <NSObject> @optional        - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender;
260@end  @class NSAttributedString, NSEvent, NSFont, NSFormatter, NSImage, NSMenu, NSText, NSView, NSTextView;
261@interface NSCell : NSObject <NSCopying, NSCoding> {
262}
263@end
264typedef struct {
265}
266CVTimeStamp;
267@interface CIImage : NSObject <NSCoding, NSCopying> {
268}
269typedef int CIFormat;
270@end  enum {
271kDAReturnSuccess = 0,     kDAReturnError = (((0x3eU)&0x3f)<<26) | (((0x368)&0xfff)<<14) | 0x01,     kDAReturnBusy = (((0x3eU)&0x3f)<<26) | (((0x368)&0xfff)<<14) | 0x02,     kDAReturnBadArgument = (((0x3eU)&0x3f)<<26) | (((0x368)&0xfff)<<14) | 0x03,     kDAReturnExclusiveAccess = (((0x3eU)&0x3f)<<26) | (((0x368)&0xfff)<<14) | 0x04,     kDAReturnNoResources = (((0x3eU)&0x3f)<<26) | (((0x368)&0xfff)<<14) | 0x05,     kDAReturnNotFound = (((0x3eU)&0x3f)<<26) | (((0x368)&0xfff)<<14) | 0x06,     kDAReturnNotMounted = (((0x3eU)&0x3f)<<26) | (((0x368)&0xfff)<<14) | 0x07,     kDAReturnNotPermitted = (((0x3eU)&0x3f)<<26) | (((0x368)&0xfff)<<14) | 0x08,     kDAReturnNotPrivileged = (((0x3eU)&0x3f)<<26) | (((0x368)&0xfff)<<14) | 0x09,     kDAReturnNotReady = (((0x3eU)&0x3f)<<26) | (((0x368)&0xfff)<<14) | 0x0A,     kDAReturnNotWritable = (((0x3eU)&0x3f)<<26) | (((0x368)&0xfff)<<14) | 0x0B,     kDAReturnUnsupported = (((0x3eU)&0x3f)<<26) | (((0x368)&0xfff)<<14) | 0x0C };
272typedef mach_error_t DAReturn;
273typedef const struct __DADissenter * DADissenterRef;
274extern DADissenterRef DADissenterCreate( CFAllocatorRef allocator, DAReturn status, CFStringRef string );
275@interface CIContext: NSObject {
276}
277- (CGImageRef)createCGImage:(CIImage *)im fromRect:(CGRect)r;
278- (CGImageRef)createCGImage:(CIImage *)im fromRect:(CGRect)r     format:(CIFormat)f colorSpace:(CGColorSpaceRef)cs;
279- (CGLayerRef)createCGLayerWithSize:(CGSize)size info:(CFDictionaryRef)d;
280@end extern NSString* const QCRendererEventKey;
281@protocol QCCompositionRenderer - (NSDictionary*) attributes;
282@end   @interface QCRenderer : NSObject <QCCompositionRenderer> {
283}
284- (id) createSnapshotImageOfType:(NSString*)type;
285@end  extern NSString* const QCViewDidStartRenderingNotification;
286@interface QCView : NSView <QCCompositionRenderer> {
287}
288- (id) createSnapshotImageOfType:(NSString*)type;
289@end    enum {
290ICEXIFOrientation1 = 1,     ICEXIFOrientation2 = 2,     ICEXIFOrientation3 = 3,     ICEXIFOrientation4 = 4,     ICEXIFOrientation5 = 5,     ICEXIFOrientation6 = 6,     ICEXIFOrientation7 = 7,     ICEXIFOrientation8 = 8, };
291@class ICDevice;
292@protocol ICDeviceDelegate <NSObject>  @required      - (void)didRemoveDevice:(ICDevice*)device;
293@end extern NSString *const ICScannerStatusWarmingUp;
294@class ICScannerDevice;
295@protocol ICScannerDeviceDelegate <ICDeviceDelegate>  @optional       - (void)scannerDeviceDidBecomeAvailable:(ICScannerDevice*)scanner;
296@end
297
298typedef long unsigned int __darwin_size_t;
299typedef __darwin_size_t size_t;
300typedef unsigned long CFTypeID;
301struct CGPoint {
302  CGFloat x;
303  CGFloat y;
304};
305typedef struct CGPoint CGPoint;
306typedef struct CGGradient *CGGradientRef;
307typedef uint32_t CGGradientDrawingOptions;
308extern CFTypeID CGGradientGetTypeID(void);
309extern CGGradientRef CGGradientCreateWithColorComponents(CGColorSpaceRef
310  space, const CGFloat components[], const CGFloat locations[], size_t count);
311extern CGGradientRef CGGradientCreateWithColors(CGColorSpaceRef space,
312  CFArrayRef colors, const CGFloat locations[]);
313extern CGGradientRef CGGradientRetain(CGGradientRef gradient);
314extern void CGGradientRelease(CGGradientRef gradient);
315typedef struct CGContext *CGContextRef;
316extern void CGContextDrawLinearGradient(CGContextRef context,
317    CGGradientRef gradient, CGPoint startPoint, CGPoint endPoint,
318    CGGradientDrawingOptions options);
319extern CGColorSpaceRef CGColorSpaceCreateDeviceRGB(void);
320
321@interface NSMutableArray : NSObject
322- (void)addObject:(id)object;
323+ (id)array;
324@end
325
326// This is how NSMakeCollectable is declared in the OS X 10.8 headers.
327id NSMakeCollectable(CFTypeRef __attribute__((cf_consumed))) __attribute__((ns_returns_retained));
328
329typedef const struct __CFUUID * CFUUIDRef;
330
331extern
332void *CFPlugInInstanceCreate(CFAllocatorRef allocator, CFUUIDRef factoryUUID, CFUUIDRef typeUUID);
333
334//===----------------------------------------------------------------------===//
335// Test cases.
336//===----------------------------------------------------------------------===//
337
338CFAbsoluteTime f1() {
339  CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
340  CFDateRef date = CFDateCreate(0, t);
341  CFRetain(date);
342  CFRelease(date);
343  CFDateGetAbsoluteTime(date); // no-warning
344  CFRelease(date);
345  t = CFDateGetAbsoluteTime(date);   // expected-warning{{Reference-counted object is used after it is released}}
346  return t;
347}
348
349CFAbsoluteTime f2() {
350  CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
351  CFDateRef date = CFDateCreate(0, t);
352  [((NSDate*) date) retain];
353  CFRelease(date);
354  CFDateGetAbsoluteTime(date); // no-warning
355  [((NSDate*) date) release];
356  t = CFDateGetAbsoluteTime(date);   // expected-warning{{Reference-counted object is used after it is released}}
357  return t;
358}
359
360
361NSDate* global_x;
362
363// Test to see if we supresss an error when we store the pointer
364// to a global.
365
366CFAbsoluteTime f3() {
367  CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
368  CFDateRef date = CFDateCreate(0, t);
369  [((NSDate*) date) retain];
370  CFRelease(date);
371  CFDateGetAbsoluteTime(date); // no-warning
372  global_x = (NSDate*) date;
373  [((NSDate*) date) release];
374  t = CFDateGetAbsoluteTime(date);   // no-warning
375  return t;
376}
377
378//---------------------------------------------------------------------------
379// Test case 'f4' differs for region store and basic store.  See
380// retain-release-region-store.m and retain-release-basic-store.m.
381//---------------------------------------------------------------------------
382
383// Test a leak.
384
385CFAbsoluteTime f5(int x) {
386  CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
387  CFDateRef date = CFDateCreate(0, t); // expected-warning{{leak}}
388
389  if (x)
390    CFRelease(date);
391
392  return t;
393}
394
395// Test a leak involving the return.
396
397CFDateRef f6(int x) {
398  CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent());  // expected-warning{{leak}}
399  CFRetain(date);
400  return date;
401}
402
403// Test a leak involving an overwrite.
404
405CFDateRef f7() {
406  CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent());  //expected-warning{{leak}}
407  CFRetain(date);
408  date = CFDateCreate(0, CFAbsoluteTimeGetCurrent()); // expected-warning {{leak}}
409  return date;
410}
411
412// Generalization of Create rule.  MyDateCreate returns a CFXXXTypeRef, and
413// has the word create.
414CFDateRef MyDateCreate();
415
416CFDateRef f8() {
417  CFDateRef date = MyDateCreate(); // expected-warning{{leak}}
418  CFRetain(date);
419  return date;
420}
421
422__attribute__((cf_returns_retained)) CFDateRef f9() {
423  CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent()); // no-warning
424  int *p = 0;
425  // When allocations fail, CFDateCreate can return null.
426  if (!date) *p = 1; // expected-warning{{null}}
427  return date;
428}
429
430// Handle DiskArbitration API:
431//
432// http://developer.apple.com/DOCUMENTATION/DARWIN/Reference/DiscArbitrationFramework/
433//
434void f10(io_service_t media, DADiskRef d, CFStringRef s) {
435  DADiskRef disk = DADiskCreateFromBSDName(kCFAllocatorDefault, 0, "hello"); // expected-warning{{leak}}
436  if (disk) NSLog(@"ok");
437
438  disk = DADiskCreateFromIOMedia(kCFAllocatorDefault, 0, media); // expected-warning{{leak}}
439  if (disk) NSLog(@"ok");
440
441  CFDictionaryRef dict = DADiskCopyDescription(d);  // expected-warning{{leak}}
442  if (dict) NSLog(@"ok");
443
444  disk = DADiskCopyWholeDisk(d); // expected-warning{{leak}}
445  if (disk) NSLog(@"ok");
446
447  DADissenterRef dissenter = DADissenterCreate(kCFAllocatorDefault,   // expected-warning{{leak}}
448                                                kDAReturnSuccess, s);
449  if (dissenter) NSLog(@"ok");
450
451  DASessionRef session = DASessionCreate(kCFAllocatorDefault);  // expected-warning{{leak}}
452  if (session) NSLog(@"ok");
453}
454
455// Test retain/release checker with CFString and CFMutableArray.
456void f11() {
457  // Create the array.
458  CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
459
460  // Create a string.
461  CFStringRef s1 = CFStringCreateWithCString(0, "hello world",
462                                             kCFStringEncodingUTF8);
463
464  // Add the string to the array.
465  CFArrayAppendValue(A, s1);
466
467  // Decrement the reference count.
468  CFRelease(s1); // no-warning
469
470  // Get the string.  We don't own it.
471  s1 = (CFStringRef) CFArrayGetValueAtIndex(A, 0);
472
473  // Release the array.
474  CFRelease(A); // no-warning
475
476  // Release the string.  This is a bug.
477  CFRelease(s1); // expected-warning{{Incorrect decrement of the reference count}}
478}
479
480// PR 3337: Handle functions declared using typedefs.
481typedef CFTypeRef CREATEFUN();
482CFTypeRef MyCreateFun();
483
484void f12() {
485  CFTypeRef o = MyCreateFun(); // expected-warning {{leak}}
486}
487
488void f13_autorelease() {
489  CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
490  [(id) A autorelease]; // no-warning
491}
492
493void f13_autorelease_b() {
494  CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
495  [(id) A autorelease];
496  [(id) A autorelease];
497} // expected-warning{{Object autoreleased too many times}}
498
499CFMutableArrayRef f13_autorelease_c() {
500  CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
501  [(id) A autorelease];
502  [(id) A autorelease];
503  return A; // expected-warning{{Object autoreleased too many times}}
504}
505
506CFMutableArrayRef f13_autorelease_d() {
507  CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
508  [(id) A autorelease];
509  [(id) A autorelease];
510  CFMutableArrayRef B = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning{{Object autoreleased too many times}}
511  CFRelease(B); // no-warning
512  while (1) {}
513}
514
515
516// This case exercises the logic where the leak site is the same as the allocation site.
517void f14_leakimmediately() {
518  CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning{{leak}}
519}
520
521// Test that we track an allocated object beyond the point where the *name*
522// of the variable storing the reference is no longer live.
523void f15() {
524  // Create the array.
525  CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
526  CFMutableArrayRef *B = &A;
527  // At this point, the name 'A' is no longer live.
528  CFRelease(*B);  // no-warning
529}
530
531// Test when we pass NULL to CFRetain/CFRelease/CFMakeCollectable.
532void f16(int x, CFTypeRef p) {
533  if (p)
534    return;
535
536  if (x > 0) {
537    CFRelease(p); // expected-warning{{Null pointer argument in call to CFRelease}}
538  }
539  else if (x < 0) {
540    CFRetain(p); // expected-warning{{Null pointer argument in call to CFRetain}}
541  }
542  else {
543    CFMakeCollectable(p); // expected-warning{{Null pointer argument in call to CFMakeCollectable}}
544  }
545}
546
547// Test that an object is non-null after being CFRetained/CFReleased.
548void f17(int x, CFTypeRef p) {
549  if (x > 0) {
550    CFRelease(p);
551    if (!p)
552      CFRelease(0); // no-warning
553  }
554  else if (x < 0) {
555    CFRetain(p);
556    if (!p)
557      CFRetain(0); // no-warning
558  }
559  else {
560    CFMakeCollectable(p);
561    if (!p)
562      CFMakeCollectable(0); // no-warning
563  }
564}
565
566// Test basic tracking of ivars associated with 'self'.  For the retain/release
567// checker we currently do not want to flag leaks associated with stores
568// of tracked objects to ivars.
569@interface SelfIvarTest : NSObject {
570  id myObj;
571}
572- (void)test_self_tracking;
573@end
574
575@implementation SelfIvarTest
576- (void)test_self_tracking {
577  myObj = (id) CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
578}
579@end
580
581// Test return of non-owned objects in contexts where an owned object
582// is expected.
583@interface TestReturnNotOwnedWhenExpectedOwned
584- (NSString*)newString;
585@end
586
587@implementation TestReturnNotOwnedWhenExpectedOwned
588- (NSString*)newString {
589  NSString *s = [NSString stringWithUTF8String:"hello"];
590  return s; // expected-warning{{Object with a +0 retain count returned to caller where a +1 (owning) retain count is expected}}
591}
592@end
593
594// <rdar://problem/6659160>
595int isFoo(char c);
596
597static void rdar_6659160(char *inkind, char *inname)
598{
599  // We currently expect that [NSObject alloc] cannot fail.  This
600  // will be a toggled flag in the future.  It can indeed return null, but
601  // Cocoa programmers generally aren't expected to reason about out-of-memory
602  // conditions.
603  NSString *kind = [[NSString alloc] initWithUTF8String:inkind];  // expected-warning{{leak}}
604
605  // We do allow stringWithUTF8String to fail.  This isn't really correct, as
606  // far as returning 0.  In most error conditions it will throw an exception.
607  // If allocation fails it could return 0, but again this
608  // isn't expected.
609  NSString *name = [NSString stringWithUTF8String:inname];
610  if(!name)
611    return;
612
613  const char *kindC = 0;
614  const char *nameC = 0;
615
616  // In both cases, we cannot reach a point down below where we
617  // dereference kindC or nameC with either being null.  This is because
618  // we assume that [NSObject alloc] doesn't fail and that we have the guard
619  // up above.
620
621  if(kind)
622    kindC = [kind UTF8String];
623  if(name)
624    nameC = [name UTF8String];
625  if(!isFoo(kindC[0])) // expected-warning{{null}}
626    return;
627  if(!isFoo(nameC[0])) // no-warning
628    return;
629
630  [kind release];
631  [name release]; // expected-warning{{Incorrect decrement of the reference count}}
632}
633
634// PR 3677 - 'allocWithZone' should be treated as following the Cocoa naming
635//  conventions with respect to 'return'ing ownership.
636@interface PR3677: NSObject @end
637@implementation PR3677
638+ (id)allocWithZone:(NSZone *)inZone {
639  return [super allocWithZone:inZone];  // no-warning
640}
641@end
642
643// PR 3820 - Reason about calls to -dealloc
644void pr3820_DeallocInsteadOfRelease(void)
645{
646  id foo = [[NSString alloc] init]; // no-warning
647  [foo dealloc];
648  // foo is not leaked, since it has been deallocated.
649}
650
651void pr3820_ReleaseAfterDealloc(void)
652{
653  id foo = [[NSString alloc] init];
654  [foo dealloc];
655  [foo release];  // expected-warning{{used after it is release}}
656  // NSInternalInconsistencyException: message sent to deallocated object
657}
658
659void pr3820_DeallocAfterRelease(void)
660{
661  NSLog(@"\n\n[%s]", __FUNCTION__);
662  id foo = [[NSString alloc] init];
663  [foo release];
664  [foo dealloc]; // expected-warning{{used after it is released}}
665  // message sent to released object
666}
667
668// From <rdar://problem/6704930>.  The problem here is that 'length' binds to
669// '($0 - 1)' after '--length', but SimpleConstraintManager doesn't know how to
670// reason about '($0 - 1) > constant'.  As a temporary hack, we drop the value
671// of '($0 - 1)' and conjure a new symbol.
672void rdar6704930(unsigned char *s, unsigned int length) {
673  NSString* name = 0;
674  if (s != 0) {
675    if (length > 0) {
676      while (length > 0) {
677        if (*s == ':') {
678          ++s;
679          --length;
680          name = [[NSString alloc] init]; // no-warning
681          break;
682        }
683        ++s;
684        --length;
685      }
686      if ((length == 0) && (name != 0)) {
687        [name release];
688        name = 0;
689      }
690      if (length == 0) { // no ':' found -> use it all as name
691        name = [[NSString alloc] init]; // no-warning
692      }
693    }
694  }
695
696  if (name != 0) {
697    [name release];
698  }
699}
700
701//===----------------------------------------------------------------------===//
702// <rdar://problem/6833332>
703// One build of the analyzer accidentally stopped tracking the allocated
704// object after the 'retain'.
705//===----------------------------------------------------------------------===//
706
707@interface rdar_6833332 : NSObject <NSApplicationDelegate> {
708    NSWindow *window;
709}
710@property (nonatomic, retain) NSWindow *window;
711@end
712
713@implementation rdar_6833332
714@synthesize window;
715- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
716 NSMutableDictionary *dict = [[NSMutableDictionary dictionaryWithCapacity:4] retain]; // expected-warning{{leak}}
717
718 [dict setObject:@"foo" forKey:@"bar"];
719
720 NSLog(@"%@", dict);
721}
722- (void)dealloc {
723    [window release];
724    [super dealloc];
725}
726
727- (void)radar10102244 {
728 NSMutableDictionary *dict = [[NSMutableDictionary dictionaryWithCapacity:4] retain]; // expected-warning{{leak}}
729 if (window)
730   NSLog(@"%@", window);
731}
732@end
733
734//===----------------------------------------------------------------------===//
735// <rdar://problem/6257780> clang checker fails to catch use-after-release
736//===----------------------------------------------------------------------===//
737
738int rdar_6257780_Case1() {
739  NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
740  NSArray *array = [NSArray array];
741  [array release]; // expected-warning{{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
742  [pool drain];
743  return 0;
744}
745
746//===----------------------------------------------------------------------===//
747// <rdar://problem/10640253> Analyzer is confused about NSAutoreleasePool -allocWithZone:.
748//===----------------------------------------------------------------------===//
749
750void rdar_10640253_autorelease_allocWithZone() {
751    NSAutoreleasePool *pool = [[NSAutoreleasePool allocWithZone:(NSZone*)0] init];
752    (void) pool;
753}
754
755//===----------------------------------------------------------------------===//
756// <rdar://problem/6866843> Checker should understand new/setObject:/release constructs
757//===----------------------------------------------------------------------===//
758
759void rdar_6866843() {
760 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
761 NSMutableDictionary* dictionary = [[NSMutableDictionary alloc] init];
762 NSArray* array = [[NSArray alloc] init];
763 [dictionary setObject:array forKey:@"key"];
764 [array release];
765 // Using 'array' here should be fine
766 NSLog(@"array = %@\n", array); // no-warning
767 // Now the array is released
768 [dictionary release];
769 [pool drain];
770}
771
772
773//===----------------------------------------------------------------------===//
774// <rdar://problem/6877235> Classes typedef-ed to CF objects should get the same treatment as CF objects
775//===----------------------------------------------------------------------===//
776
777typedef CFTypeRef OtherRef;
778
779@interface RDar6877235 : NSObject {}
780- (CFTypeRef)_copyCFTypeRef;
781- (OtherRef)_copyOtherRef;
782@end
783
784@implementation RDar6877235
785- (CFTypeRef)_copyCFTypeRef {
786  return [[NSString alloc] init]; // no-warning
787}
788- (OtherRef)_copyOtherRef {
789  return [[NSString alloc] init]; // no-warning
790}
791@end
792
793//===----------------------------------------------------------------------===//
794// <rdar://problem/6320065> false positive - init method returns an object
795// owned by caller
796//===----------------------------------------------------------------------===//
797
798@interface RDar6320065 : NSObject {
799  NSString *_foo;
800}
801- (id)initReturningNewClass;
802- (id)_initReturningNewClassBad;
803- (id)initReturningNewClassBad2;
804@end
805
806@interface RDar6320065Subclass : RDar6320065
807@end
808
809@implementation RDar6320065
810- (id)initReturningNewClass {
811  [self release];
812  self = [[RDar6320065Subclass alloc] init]; // no-warning
813  return self;
814}
815- (id)_initReturningNewClassBad {
816  [self release];
817  [[RDar6320065Subclass alloc] init]; // expected-warning {{leak}}
818  return self;
819}
820- (id)initReturningNewClassBad2 {
821  [self release];
822  self = [[RDar6320065Subclass alloc] init];
823  return [self autorelease]; // expected-warning{{Object with a +0 retain count returned to caller where a +1 (owning) retain count is expected}}
824}
825
826@end
827
828@implementation RDar6320065Subclass
829@end
830
831int RDar6320065_test() {
832  RDar6320065 *test = [[RDar6320065 alloc] init]; // no-warning
833  [test release];
834  return 0;
835}
836
837//===----------------------------------------------------------------------===//
838// <rdar://problem/7129086> -awakeAfterUsingCoder: returns an owned object
839//  and claims the receiver
840//===----------------------------------------------------------------------===//
841
842@interface RDar7129086 : NSObject {} @end
843@implementation RDar7129086
844- (id)awakeAfterUsingCoder:(NSCoder *)aDecoder {
845  [self release]; // no-warning
846  return [NSString alloc];  // no-warning
847}
848@end
849
850//===----------------------------------------------------------------------===//
851// <rdar://problem/6859457> [NSData dataWithBytesNoCopy] does not return a
852//  retained object
853//===----------------------------------------------------------------------===//
854
855@interface RDar6859457 : NSObject {}
856- (NSString*) NoCopyString;
857- (NSString*) noCopyString;
858@end
859
860@implementation RDar6859457
861- (NSString*) NoCopyString { return [[NSString alloc] init]; } // expected-warning{{leak}}
862- (NSString*) noCopyString { return [[NSString alloc] init]; } // expected-warning{{leak}}
863@end
864
865void test_RDar6859457(RDar6859457 *x, void *bytes, NSUInteger dataLength) {
866  [x NoCopyString]; // expected-warning{{leak}}
867  [x noCopyString]; // expected-warning{{leak}}
868  [NSData dataWithBytesNoCopy:bytes length:dataLength];  // no-warning
869  [NSData dataWithBytesNoCopy:bytes length:dataLength freeWhenDone:1]; // no-warning
870}
871
872//===----------------------------------------------------------------------===//
873// PR 4230 - an autorelease pool is not necessarily leaked during a premature
874//  return
875//===----------------------------------------------------------------------===//
876
877static void PR4230(void)
878{
879  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // no-warning
880  NSString *object = [[[NSString alloc] init] autorelease]; // no-warning
881  return;
882}
883
884static void PR4230_new(void)
885{
886  NSAutoreleasePool *pool = [NSAutoreleasePool new]; // no-warning
887  NSString *object = [[[NSString alloc] init] autorelease]; // no-warning
888  return;
889}
890
891//===----------------------------------------------------------------------===//
892// Method name that has a null IdentifierInfo* for its first selector slot.
893// This test just makes sure that we handle it.
894//===----------------------------------------------------------------------===//
895
896@interface TestNullIdentifier
897@end
898
899@implementation TestNullIdentifier
900+ (id):(int)x, ... {
901  return [[NSString alloc] init]; // expected-warning{{leak}}
902}
903@end
904
905//===----------------------------------------------------------------------===//
906// <rdar://problem/6893565> don't flag leaks for return types that cannot be
907//                          determined to be CF types
908//===----------------------------------------------------------------------===//
909
910// We don't know if 'struct s6893565' represents a Core Foundation type, so
911// we shouldn't emit an error here.
912typedef struct s6893565* TD6893565;
913
914@interface RDar6893565 {}
915-(TD6893565)newThing;
916@end
917
918@implementation RDar6893565
919-(TD6893565)newThing {
920  return (TD6893565) [[NSString alloc] init]; // no-warning
921}
922@end
923
924//===----------------------------------------------------------------------===//
925// <rdar://problem/6902710> clang: false positives w/QC and CoreImage methods
926//===----------------------------------------------------------------------===//
927
928void rdar6902710(QCView *view, QCRenderer *renderer, CIContext *context,
929                 NSString *str, CIImage *img, CGRect rect,
930                 CIFormat form, CGColorSpaceRef cs) {
931  [view createSnapshotImageOfType:str]; // expected-warning{{leak}}
932  [renderer createSnapshotImageOfType:str]; // expected-warning{{leak}}
933  [context createCGImage:img fromRect:rect]; // expected-warning{{leak}}
934  [context createCGImage:img fromRect:rect format:form colorSpace:cs]; // expected-warning{{leak}}
935}
936
937//===----------------------------------------------------------------------===//
938// <rdar://problem/6945561> -[CIContext createCGLayerWithSize:info:]
939//                           misinterpreted by clang scan-build
940//===----------------------------------------------------------------------===//
941
942void rdar6945561(CIContext *context, CGSize size, CFDictionaryRef d) {
943  [context createCGLayerWithSize:size info:d]; // expected-warning{{leak}}
944}
945
946//===----------------------------------------------------------------------===//
947// <rdar://problem/6961230> add knowledge of IOKit functions to retain/release
948//                          checker
949//===----------------------------------------------------------------------===//
950
951void IOBSDNameMatching_wrapper(mach_port_t masterPort, uint32_t options,  const char * bsdName) {
952  IOBSDNameMatching(masterPort, options, bsdName); // expected-warning{{leak}}
953}
954
955void IOServiceMatching_wrapper(const char * name) {
956  IOServiceMatching(name); // expected-warning{{leak}}
957}
958
959void IOServiceNameMatching_wrapper(const char * name) {
960  IOServiceNameMatching(name); // expected-warning{{leak}}
961}
962
963CF_RETURNS_RETAINED CFDictionaryRef CreateDict();
964
965void IOServiceAddNotification_wrapper(mach_port_t masterPort, const io_name_t notificationType,
966  mach_port_t wakePort, uintptr_t reference, io_iterator_t * notification ) {
967
968  CFDictionaryRef matching = CreateDict();
969  CFRelease(matching);
970  IOServiceAddNotification(masterPort, notificationType, matching, // expected-warning{{used after it is released}} expected-warning{{deprecated}}
971                           wakePort, reference, notification);
972}
973
974void IORegistryEntryIDMatching_wrapper(uint64_t entryID ) {
975  IORegistryEntryIDMatching(entryID); // expected-warning{{leak}}
976}
977
978void IOOpenFirmwarePathMatching_wrapper(mach_port_t masterPort, uint32_t options,
979                                        const char * path) {
980  IOOpenFirmwarePathMatching(masterPort, options, path); // expected-warning{{leak}}
981}
982
983void IOServiceGetMatchingService_wrapper(mach_port_t masterPort) {
984  CFDictionaryRef matching = CreateDict();
985  IOServiceGetMatchingService(masterPort, matching);
986  CFRelease(matching); // expected-warning{{used after it is released}}
987}
988
989void IOServiceGetMatchingServices_wrapper(mach_port_t masterPort, io_iterator_t *existing) {
990  CFDictionaryRef matching = CreateDict();
991  IOServiceGetMatchingServices(masterPort, matching, existing);
992  CFRelease(matching); // expected-warning{{used after it is released}}
993}
994
995void IOServiceAddMatchingNotification_wrapper(IONotificationPortRef notifyPort, const io_name_t notificationType,
996  IOServiceMatchingCallback callback, void * refCon, io_iterator_t * notification) {
997
998  CFDictionaryRef matching = CreateDict();
999  IOServiceAddMatchingNotification(notifyPort, notificationType, matching, callback, refCon, notification);
1000  CFRelease(matching); // expected-warning{{used after it is released}}
1001}
1002
1003//===----------------------------------------------------------------------===//
1004// Test of handling objects whose references "escape" to containers.
1005//===----------------------------------------------------------------------===//
1006
1007void CFDictionaryAddValue(CFMutableDictionaryRef, void *, void *);
1008
1009// <rdar://problem/6539791>
1010void rdar_6539791(CFMutableDictionaryRef y, void* key, void* val_key) {
1011  CFMutableDictionaryRef x = CFDictionaryCreateMutable(kCFAllocatorDefault, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
1012  CFDictionaryAddValue(y, key, x);
1013  CFRelease(x); // the dictionary keeps a reference, so the object isn't deallocated yet
1014  signed z = 1;
1015  CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z);
1016  if (value) {
1017    CFDictionaryAddValue(x, val_key, (void*)value); // no-warning
1018    CFRelease(value);
1019    CFDictionaryAddValue(y, val_key, (void*)value); // no-warning
1020  }
1021}
1022
1023// <rdar://problem/6560661>
1024// Same issue, except with "AppendValue" functions.
1025void rdar_6560661(CFMutableArrayRef x) {
1026  signed z = 1;
1027  CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z);
1028  // CFArrayAppendValue keeps a reference to value.
1029  CFArrayAppendValue(x, value);
1030  CFRelease(value);
1031  CFRetain(value);
1032  CFRelease(value); // no-warning
1033}
1034
1035// <rdar://problem/7152619>
1036// Same issue, excwept with "CFAttributeStringSetAttribute".
1037void rdar_7152619(CFStringRef str) {
1038  CFAttributedStringRef string = CFAttributedStringCreate(kCFAllocatorDefault, str, 0);
1039  CFMutableAttributedStringRef attrString = CFAttributedStringCreateMutableCopy(kCFAllocatorDefault, 100, string);
1040  CFRelease(string);
1041  NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1042  CFAttributedStringSetAttribute(attrString, CFRangeMake(0, 1), str, number);
1043  [number release];
1044  [number retain];
1045  CFRelease(attrString);
1046}
1047
1048//===----------------------------------------------------------------------===//
1049// Test of handling CGGradientXXX functions.
1050//===----------------------------------------------------------------------===//
1051
1052void rdar_7184450(CGContextRef myContext, CGFloat x, CGPoint myStartPoint,
1053                  CGPoint myEndPoint) {
1054  size_t num_locations = 6;
1055  CGFloat locations[6] = { 0.0, 0.265, 0.28, 0.31, 0.36, 1.0 };
1056  CGFloat components[28] = { 239.0/256.0, 167.0/256.0, 170.0/256.0,
1057     x,  // Start color
1058    207.0/255.0, 39.0/255.0, 39.0/255.0, x,
1059    147.0/255.0, 21.0/255.0, 22.0/255.0, x,
1060    175.0/255.0, 175.0/255.0, 175.0/255.0, x,
1061    255.0/255.0,255.0/255.0, 255.0/255.0, x,
1062    255.0/255.0,255.0/255.0, 255.0/255.0, x
1063  }; // End color
1064
1065  CGGradientRef myGradient =
1066    CGGradientCreateWithColorComponents(CGColorSpaceCreateDeviceRGB(), // expected-warning{{leak}}
1067      components, locations, num_locations);
1068
1069  CGContextDrawLinearGradient(myContext, myGradient, myStartPoint, myEndPoint,
1070                              0);
1071  CGGradientRelease(myGradient);
1072}
1073
1074void rdar_7184450_pos(CGContextRef myContext, CGFloat x, CGPoint myStartPoint,
1075                  CGPoint myEndPoint) {
1076  size_t num_locations = 6;
1077  CGFloat locations[6] = { 0.0, 0.265, 0.28, 0.31, 0.36, 1.0 };
1078  CGFloat components[28] = { 239.0/256.0, 167.0/256.0, 170.0/256.0,
1079     x,  // Start color
1080    207.0/255.0, 39.0/255.0, 39.0/255.0, x,
1081    147.0/255.0, 21.0/255.0, 22.0/255.0, x,
1082    175.0/255.0, 175.0/255.0, 175.0/255.0, x,
1083    255.0/255.0,255.0/255.0, 255.0/255.0, x,
1084    255.0/255.0,255.0/255.0, 255.0/255.0, x
1085  }; // End color
1086
1087  CGGradientRef myGradient =
1088   CGGradientCreateWithColorComponents(CGColorSpaceCreateDeviceRGB(), components, locations, num_locations); // expected-warning 2 {{leak}}
1089
1090  CGContextDrawLinearGradient(myContext, myGradient, myStartPoint, myEndPoint,
1091                              0);
1092}
1093
1094//===----------------------------------------------------------------------===//
1095// <rdar://problem/7299394> clang false positive: retained instance passed to
1096//                          thread in pthread_create marked as leak
1097//
1098// Until we have full IPA, the analyzer should stop tracking the reference
1099// count of objects passed to pthread_create.
1100//
1101//===----------------------------------------------------------------------===//
1102
1103struct _opaque_pthread_t {};
1104struct _opaque_pthread_attr_t {};
1105typedef struct _opaque_pthread_t *__darwin_pthread_t;
1106typedef struct _opaque_pthread_attr_t __darwin_pthread_attr_t;
1107typedef __darwin_pthread_t pthread_t;
1108typedef __darwin_pthread_attr_t pthread_attr_t;
1109typedef unsigned long __darwin_pthread_key_t;
1110typedef __darwin_pthread_key_t pthread_key_t;
1111
1112int pthread_create(pthread_t *, const pthread_attr_t *,
1113                   void *(*)(void *), void *);
1114
1115int pthread_setspecific(pthread_key_t key, const void *value);
1116
1117void *rdar_7299394_start_routine(void *p) {
1118  [((id) p) release];
1119  return 0;
1120}
1121void rdar_7299394(pthread_attr_t *attr, pthread_t *thread, void *args) {
1122  NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1123  pthread_create(thread, attr, rdar_7299394_start_routine, number);
1124}
1125void rdar_7299394_positive(pthread_attr_t *attr, pthread_t *thread) {
1126  NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1127}
1128
1129//===----------------------------------------------------------------------===//
1130// <rdar://problem/11282706> false positive with not understanding thread
1131// local storage
1132//===----------------------------------------------------------------------===//
1133
1134void rdar11282706(pthread_key_t key) {
1135  NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1136  pthread_setspecific(key, (void*) number);
1137}
1138
1139//===----------------------------------------------------------------------===//
1140// <rdar://problem/7283567> False leak associated with call to
1141//                          CVPixelBufferCreateWithBytes ()
1142//
1143// According to the Core Video Reference (ADC), CVPixelBufferCreateWithBytes and
1144// CVPixelBufferCreateWithPlanarBytes can release (via a callback) the
1145// pixel buffer object.  These test cases show how the analyzer stops tracking
1146// the reference count for the objects passed for this argument.  This
1147// could be made smarter.
1148//===----------------------------------------------------------------------===//
1149
1150typedef int int32_t;
1151typedef UInt32 FourCharCode;
1152typedef FourCharCode OSType;
1153typedef uint64_t CVOptionFlags;
1154typedef int32_t CVReturn;
1155typedef struct __CVBuffer *CVBufferRef;
1156typedef CVBufferRef CVImageBufferRef;
1157typedef CVImageBufferRef CVPixelBufferRef;
1158typedef void (*CVPixelBufferReleaseBytesCallback)( void *releaseRefCon, const void *baseAddress );
1159
1160extern CVReturn CVPixelBufferCreateWithBytes(CFAllocatorRef allocator,
1161            size_t width,
1162            size_t height,
1163            OSType pixelFormatType,
1164            void *baseAddress,
1165            size_t bytesPerRow,
1166            CVPixelBufferReleaseBytesCallback releaseCallback,
1167            void *releaseRefCon,
1168            CFDictionaryRef pixelBufferAttributes,
1169                   CVPixelBufferRef *pixelBufferOut) ;
1170
1171typedef void (*CVPixelBufferReleasePlanarBytesCallback)( void *releaseRefCon, const void *dataPtr, size_t dataSize, size_t numberOfPlanes, const void *planeAddresses[] );
1172
1173extern CVReturn CVPixelBufferCreateWithPlanarBytes(CFAllocatorRef allocator,
1174        size_t width,
1175        size_t height,
1176        OSType pixelFormatType,
1177        void *dataPtr,
1178        size_t dataSize,
1179        size_t numberOfPlanes,
1180        void *planeBaseAddress[],
1181        size_t planeWidth[],
1182        size_t planeHeight[],
1183        size_t planeBytesPerRow[],
1184        CVPixelBufferReleasePlanarBytesCallback releaseCallback,
1185        void *releaseRefCon,
1186        CFDictionaryRef pixelBufferAttributes,
1187        CVPixelBufferRef *pixelBufferOut) ;
1188
1189extern CVReturn CVPixelBufferCreateWithBytes(CFAllocatorRef allocator,
1190            size_t width,
1191            size_t height,
1192            OSType pixelFormatType,
1193            void *baseAddress,
1194            size_t bytesPerRow,
1195            CVPixelBufferReleaseBytesCallback releaseCallback,
1196            void *releaseRefCon,
1197            CFDictionaryRef pixelBufferAttributes,
1198                   CVPixelBufferRef *pixelBufferOut) ;
1199
1200CVReturn rdar_7283567(CFAllocatorRef allocator, size_t width, size_t height,
1201                      OSType pixelFormatType, void *baseAddress,
1202                      size_t bytesPerRow,
1203                      CVPixelBufferReleaseBytesCallback releaseCallback,
1204                      CFDictionaryRef pixelBufferAttributes,
1205                      CVPixelBufferRef *pixelBufferOut) {
1206
1207  // For the allocated object, it doesn't really matter what type it is
1208  // for the purpose of this test.  All we want to show is that
1209  // this is freed later by the callback.
1210  NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1211
1212  return CVPixelBufferCreateWithBytes(allocator, width, height, pixelFormatType,
1213                                baseAddress, bytesPerRow, releaseCallback,
1214                                number, // potentially released by callback
1215                                pixelBufferAttributes, pixelBufferOut) ;
1216}
1217
1218CVReturn rdar_7283567_2(CFAllocatorRef allocator, size_t width, size_t height,
1219        OSType pixelFormatType, void *dataPtr, size_t dataSize,
1220        size_t numberOfPlanes, void *planeBaseAddress[],
1221        size_t planeWidth[], size_t planeHeight[], size_t planeBytesPerRow[],
1222        CVPixelBufferReleasePlanarBytesCallback releaseCallback,
1223        CFDictionaryRef pixelBufferAttributes,
1224        CVPixelBufferRef *pixelBufferOut) {
1225
1226    // For the allocated object, it doesn't really matter what type it is
1227    // for the purpose of this test.  All we want to show is that
1228    // this is freed later by the callback.
1229    NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1230
1231    return CVPixelBufferCreateWithPlanarBytes(allocator,
1232              width, height, pixelFormatType, dataPtr, dataSize,
1233              numberOfPlanes, planeBaseAddress, planeWidth,
1234              planeHeight, planeBytesPerRow, releaseCallback,
1235              number, // potentially released by callback
1236              pixelBufferAttributes, pixelBufferOut) ;
1237}
1238
1239//===----------------------------------------------------------------------===//
1240// <rdar://problem/7358899> False leak associated with
1241//  CGBitmapContextCreateWithData
1242//===----------------------------------------------------------------------===//
1243typedef uint32_t CGBitmapInfo;
1244typedef void (*CGBitmapContextReleaseDataCallback)(void *releaseInfo, void *data);
1245
1246CGContextRef CGBitmapContextCreateWithData(void *data,
1247    size_t width, size_t height, size_t bitsPerComponent,
1248    size_t bytesPerRow, CGColorSpaceRef space, CGBitmapInfo bitmapInfo,
1249    CGBitmapContextReleaseDataCallback releaseCallback, void *releaseInfo);
1250
1251void rdar_7358899(void *data,
1252      size_t width, size_t height, size_t bitsPerComponent,
1253      size_t bytesPerRow, CGColorSpaceRef space, CGBitmapInfo bitmapInfo,
1254      CGBitmapContextReleaseDataCallback releaseCallback) {
1255
1256    // For the allocated object, it doesn't really matter what type it is
1257    // for the purpose of this test.  All we want to show is that
1258    // this is freed later by the callback.
1259    NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1260
1261  CGBitmapContextCreateWithData(data, width, height, bitsPerComponent, // expected-warning{{leak}}
1262    bytesPerRow, space, bitmapInfo, releaseCallback, number);
1263}
1264
1265//===----------------------------------------------------------------------===//
1266// <rdar://problem/7265711> allow 'new', 'copy', 'alloc', 'init' prefix to
1267//  start before '_' when determining Cocoa fundamental rule
1268//
1269// Previously the retain/release checker just skipped prefixes before the
1270// first '_' entirely.  Now the checker honors the prefix if it results in a
1271// recognizable naming convention (e.g., 'new', 'init').
1272//===----------------------------------------------------------------------===//
1273
1274@interface RDar7265711 {}
1275- (id) new_stuff;
1276@end
1277
1278void rdar7265711_a(RDar7265711 *x) {
1279  id y = [x new_stuff]; // expected-warning{{leak}}
1280}
1281
1282void rdar7265711_b(RDar7265711 *x) {
1283  id y = [x new_stuff]; // no-warning
1284  [y release];
1285}
1286
1287//===----------------------------------------------------------------------===//
1288// <rdar://problem/7306898> clang thinks [NSCursor dragCopyCursor] returns a
1289//                          retained reference
1290//===----------------------------------------------------------------------===//
1291
1292@interface NSCursor : NSObject
1293+ (NSCursor *)dragCopyCursor;
1294@end
1295
1296void rdar7306898(void) {
1297  // 'dragCopyCursor' does not follow Cocoa's fundamental rule.  It is a noun, not an sentence
1298  // implying a 'copy' of something.
1299  NSCursor *c =  [NSCursor dragCopyCursor]; // no-warning
1300  NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1301}
1302
1303//===----------------------------------------------------------------------===//
1304// <rdar://problem/7252064> sending 'release', 'retain', etc. to a Class
1305// directly is not likely what the user intended
1306//===----------------------------------------------------------------------===//
1307
1308@interface RDar7252064 : NSObject @end
1309void rdar7252064(void) {
1310  [RDar7252064 release]; // expected-warning{{The 'release' message should be sent to instances of class 'RDar7252064' and not the class directly}}
1311  [RDar7252064 retain]; // expected-warning{{The 'retain' message should be sent to instances of class 'RDar7252064' and not the class directly}}
1312  [RDar7252064 autorelease]; // expected-warning{{The 'autorelease' message should be sent to instances of class 'RDar7252064' and not the class directly}}
1313  [NSAutoreleasePool drain]; // expected-warning{{method '+drain' not found}} expected-warning{{The 'drain' message should be sent to instances of class 'NSAutoreleasePool' and not the class directly}}
1314}
1315
1316//===----------------------------------------------------------------------===//
1317// Tests of ownership attributes.
1318//===----------------------------------------------------------------------===//
1319
1320typedef NSString* MyStringTy;
1321
1322@protocol FooP;
1323
1324@interface TestOwnershipAttr : NSObject
1325- (NSString*) returnsAnOwnedString  NS_RETURNS_RETAINED; // no-warning
1326- (NSString*) returnsAnOwnedCFString  CF_RETURNS_RETAINED; // no-warning
1327- (MyStringTy) returnsAnOwnedTypedString NS_RETURNS_RETAINED; // no-warning
1328- (NSString*) newString NS_RETURNS_NOT_RETAINED; // no-warning
1329- (NSString*) newString_auto NS_RETURNS_AUTORELEASED; // no-warning
1330- (NSString*) newStringNoAttr;
1331- (int) returnsAnOwnedInt NS_RETURNS_RETAINED; // expected-warning{{'ns_returns_retained' attribute only applies to methods that return an Objective-C object}}
1332- (id) pseudoInit NS_CONSUMES_SELF NS_RETURNS_RETAINED;
1333+ (void) consume:(id) NS_CONSUMED x;
1334+ (void) consume2:(id) CF_CONSUMED x;
1335@end
1336
1337static int ownership_attribute_doesnt_go_here NS_RETURNS_RETAINED; // expected-warning{{'ns_returns_retained' attribute only applies to functions and methods}}
1338
1339void test_attr_1(TestOwnershipAttr *X) {
1340  NSString *str = [X returnsAnOwnedString]; // expected-warning{{leak}}
1341}
1342
1343void test_attr_1b(TestOwnershipAttr *X) {
1344  NSString *str = [X returnsAnOwnedCFString]; // expected-warning{{leak}}
1345}
1346
1347void test_attr1c(TestOwnershipAttr *X) {
1348  NSString *str = [X newString]; // no-warning
1349  NSString *str2 = [X newStringNoAttr]; // expected-warning{{leak}}
1350  NSString *str3 = [X newString_auto]; // no-warning
1351  NSString *str4 = [[X newString_auto] retain]; // expected-warning {{leak}}
1352}
1353
1354void testattr2_a() {
1355  TestOwnershipAttr *x = [TestOwnershipAttr alloc]; // expected-warning{{leak}}
1356}
1357
1358void testattr2_b() {
1359  TestOwnershipAttr *x = [[TestOwnershipAttr alloc] pseudoInit];  // expected-warning{{leak}}
1360}
1361
1362void testattr2_b_11358224_self_assign_looses_the_leak() {
1363  TestOwnershipAttr *x = [[TestOwnershipAttr alloc] pseudoInit];// expected-warning{{leak}}
1364  x = x;
1365}
1366
1367void testattr2_c() {
1368  TestOwnershipAttr *x = [[TestOwnershipAttr alloc] pseudoInit]; // no-warning
1369  [x release];
1370}
1371
1372void testattr3() {
1373  TestOwnershipAttr *x = [TestOwnershipAttr alloc]; // no-warning
1374  [TestOwnershipAttr consume:x];
1375  TestOwnershipAttr *y = [TestOwnershipAttr alloc]; // no-warning
1376  [TestOwnershipAttr consume2:y];
1377}
1378
1379void consume_ns(id NS_CONSUMED x);
1380void consume_cf(id CF_CONSUMED x);
1381
1382void testattr4() {
1383  TestOwnershipAttr *x = [TestOwnershipAttr alloc]; // no-warning
1384  consume_ns(x);
1385  TestOwnershipAttr *y = [TestOwnershipAttr alloc]; // no-warning
1386  consume_cf(y);
1387}
1388
1389@interface TestOwnershipAttr2 : NSObject
1390- (NSString*) newString NS_RETURNS_NOT_RETAINED; // no-warning
1391@end
1392
1393@implementation TestOwnershipAttr2
1394- (NSString*) newString {
1395  return [NSString alloc]; // expected-warning {{Potential leak of an object}}
1396}
1397@end
1398
1399@interface MyClassTestCFAttr : NSObject {}
1400- (NSDate*) returnsCFRetained CF_RETURNS_RETAINED;
1401- (CFDateRef) returnsCFRetainedAsCF CF_RETURNS_RETAINED;
1402- (CFDateRef) newCFRetainedAsCF CF_RETURNS_NOT_RETAINED;
1403- (CFDateRef) newCFRetainedAsCFNoAttr;
1404- (NSDate*) alsoReturnsRetained;
1405- (CFDateRef) alsoReturnsRetainedAsCF;
1406- (NSDate*) returnsNSRetained NS_RETURNS_RETAINED;
1407@end
1408
1409CF_RETURNS_RETAINED
1410CFDateRef returnsRetainedCFDate()  {
1411  return CFDateCreate(0, CFAbsoluteTimeGetCurrent());
1412}
1413
1414@implementation MyClassTestCFAttr
1415- (NSDate*) returnsCFRetained {
1416  return (NSDate*) returnsRetainedCFDate(); // No leak.
1417}
1418
1419- (CFDateRef) returnsCFRetainedAsCF {
1420  return returnsRetainedCFDate(); // No leak.
1421}
1422
1423- (CFDateRef) newCFRetainedAsCF {
1424  return (CFDateRef)[(id)[self returnsCFRetainedAsCF] autorelease];
1425}
1426
1427- (CFDateRef) newCFRetainedAsCFNoAttr {
1428  return (CFDateRef)[(id)[self returnsCFRetainedAsCF] autorelease]; // expected-warning{{Object with a +0 retain count returned to caller where a +1 (owning) retain count is expected}}
1429}
1430
1431- (NSDate*) alsoReturnsRetained {
1432  return (NSDate*) returnsRetainedCFDate(); // expected-warning{{leak}}
1433}
1434
1435- (CFDateRef) alsoReturnsRetainedAsCF {
1436  return returnsRetainedCFDate(); // expected-warning{{leak}}
1437}
1438
1439
1440- (NSDate*) returnsNSRetained {
1441  return (NSDate*) returnsRetainedCFDate(); // no-warning
1442}
1443@end
1444
1445//===----------------------------------------------------------------------===//
1446// Test that leaks post-dominated by "panic" functions are not reported.
1447//
1448// <rdar://problem/5905851> do not report a leak when post-dominated by a call
1449// to a noreturn or panic function
1450//===----------------------------------------------------------------------===//
1451
1452void panic() __attribute__((noreturn));
1453void panic_not_in_hardcoded_list() __attribute__((noreturn));
1454
1455void test_panic_negative() {
1456  signed z = 1;
1457  CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z);  // expected-warning{{leak}}
1458}
1459
1460void test_panic_positive() {
1461  signed z = 1;
1462  CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // no-warning
1463  panic();
1464}
1465
1466void test_panic_neg_2(int x) {
1467  signed z = 1;
1468  CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // expected-warning{{leak}}
1469  if (x)
1470    panic();
1471}
1472
1473void test_panic_pos_2(int x) {
1474  signed z = 1;
1475  CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // no-warning
1476  if (x)
1477    panic();
1478  if (!x) {
1479    // This showed up in <rdar://problem/7796563>, where we silently missed checking
1480    // the function type for noreturn.  "panic()" is a hard-coded known panic function
1481    // that isn't always noreturn.
1482    panic_not_in_hardcoded_list();
1483  }
1484}
1485
1486//===----------------------------------------------------------------------===//
1487// Test uses of blocks (closures)
1488//===----------------------------------------------------------------------===//
1489
1490void test_blocks_1_pos(void) {
1491  NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1492  ^{}();
1493}
1494
1495void test_blocks_1_indirect_release(void) {
1496  NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1497  ^{ [number release]; }();
1498}
1499
1500void test_blocks_1_indirect_retain(void) {
1501  // Eventually this should be reported as a leak.
1502  NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1503  ^{ [number retain]; }();
1504}
1505
1506void test_blocks_1_indirect_release_via_call(void) {
1507  NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1508  ^(NSObject *o){ [o release]; }(number);
1509}
1510
1511void test_blocks_1_indirect_retain_via_call(void) {
1512  NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning {{leak}}
1513  ^(NSObject *o){ [o retain]; }(number);
1514}
1515
1516//===--------------------------------------------------------------------===//
1517// Test sending message to super that returns an object alias.  Previously
1518// this caused a crash in the analyzer.
1519//===--------------------------------------------------------------------===//
1520
1521@interface Rdar8015556 : NSObject {} @end
1522@implementation Rdar8015556
1523- (id)retain {
1524  return [super retain];
1525}
1526@end
1527
1528// <rdar://problem/8272168> - Correcly handle Class<...> in Cocoa Conventions
1529// detector.
1530
1531@protocol Prot_R8272168 @end
1532Class <Prot_R8272168> GetAClassThatImplementsProt_R8272168();
1533void r8272168() {
1534  GetAClassThatImplementsProt_R8272168();
1535}
1536
1537// Test case for <rdar://problem/8356342>, which in the past triggered
1538// a false positive.
1539@interface RDar8356342
1540- (NSDate*) rdar8356342:(NSDate *)inValue;
1541@end
1542
1543@implementation RDar8356342
1544- (NSDate*) rdar8356342:(NSDate*)inValue {
1545  NSDate *outValue = inValue;
1546  if (outValue == 0)
1547    outValue = [[NSDate alloc] init]; // no-warning
1548
1549  if (outValue != inValue)
1550    [outValue autorelease];
1551
1552  return outValue;
1553}
1554@end
1555
1556// <rdar://problem/8724287> - This test case previously crashed because
1557// of a bug in BugReporter.
1558extern const void *CFDictionaryGetValue(CFDictionaryRef theDict, const void *key);
1559typedef struct __CFError * CFErrorRef;
1560extern const CFStringRef kCFErrorUnderlyingErrorKey;
1561extern CFDictionaryRef CFErrorCopyUserInfo(CFErrorRef err);
1562static void rdar_8724287(CFErrorRef error)
1563{
1564    CFErrorRef error_to_dump;
1565
1566    error_to_dump = error;
1567    while (error_to_dump != ((void*)0)) {
1568        CFDictionaryRef info;
1569
1570        info = CFErrorCopyUserInfo(error_to_dump); // expected-warning{{Potential leak of an object}}
1571
1572        if (info != ((void*)0)) {
1573        }
1574
1575        error_to_dump = (CFErrorRef) CFDictionaryGetValue(info, kCFErrorUnderlyingErrorKey);
1576    }
1577}
1578
1579// <rdar://problem/9234108> - Make sure the model applies cf_consumed
1580// correctly in argument positions besides the first.
1581extern void *CFStringCreate(void);
1582extern void rdar_9234108_helper(void *key, void * CF_CONSUMED value);
1583void rdar_9234108() {
1584  rdar_9234108_helper(0, CFStringCreate());
1585}
1586
1587// <rdar://problem/9726279> - Make sure that objc_method_family works
1588// to override naming conventions.
1589struct TwoDoubles {
1590  double one;
1591  double two;
1592};
1593typedef struct TwoDoubles TwoDoubles;
1594
1595@interface NSValue (Mine)
1596- (id)_prefix_initWithTwoDoubles:(TwoDoubles)twoDoubles __attribute__((objc_method_family(init)));
1597@end
1598
1599@implementation NSValue (Mine)
1600- (id)_prefix_initWithTwoDoubles:(TwoDoubles)twoDoubles
1601{
1602  return [self init];
1603}
1604@end
1605
1606void rdar9726279() {
1607  TwoDoubles twoDoubles = { 0.0, 0.0 };
1608  NSValue *value = [[NSValue alloc] _prefix_initWithTwoDoubles:twoDoubles];
1609  [value release];
1610}
1611
1612// <rdar://problem/9732321>
1613// Test camelcase support for CF conventions.  While Core Foundation APIs
1614// don't use camel casing, other code is allowed to use it.
1615CFArrayRef camelcase_create_1() {
1616  return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1617}
1618
1619CFArrayRef camelcase_createno() {
1620  return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1621}
1622
1623CFArrayRef camelcase_copy() {
1624  return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1625}
1626
1627CFArrayRef camelcase_copying() {
1628  return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1629}
1630
1631CFArrayRef copyCamelCase() {
1632  return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1633}
1634
1635CFArrayRef __copyCamelCase() {
1636  return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1637}
1638
1639CFArrayRef __createCamelCase() {
1640  return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1641}
1642
1643CFArrayRef camel_create() {
1644  return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1645}
1646
1647
1648CFArrayRef camel_creat() {
1649  return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1650}
1651
1652CFArrayRef camel_copy() {
1653  return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1654}
1655
1656CFArrayRef camel_copyMachine() {
1657  return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1658}
1659
1660CFArrayRef camel_copymachine() {
1661  return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1662}
1663
1664// rdar://problem/8024350
1665@protocol F18P
1666- (id) clone;
1667@end
1668@interface F18 : NSObject<F18P> @end
1669@interface F18(Cat)
1670- (id) clone NS_RETURNS_RETAINED;
1671@end
1672
1673@implementation F18
1674- (id) clone {
1675  return [F18 alloc];
1676}
1677@end
1678
1679// Radar 6582778.
1680void rdar6582778(void) {
1681  CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
1682  CFTypeRef vals[] = { CFDateCreate(0, t) }; // expected-warning {{leak}}
1683}
1684
1685CFTypeRef global;
1686
1687void rdar6582778_2(void) {
1688  CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
1689  global = CFDateCreate(0, t); // no-warning
1690}
1691
1692// <rdar://problem/10232019> - Test that objects passed to containers
1693// are marked "escaped".
1694
1695void rdar10232019() {
1696  NSMutableArray *array = [NSMutableArray array];
1697
1698  NSString *string = [[NSString alloc] initWithUTF8String:"foo"];
1699  [array addObject:string];
1700  [string release];
1701
1702  NSString *otherString = [string stringByAppendingString:@"bar"]; // no-warning
1703  NSLog(@"%@", otherString);
1704}
1705
1706void rdar10232019_positive() {
1707  NSMutableArray *array = [NSMutableArray array];
1708
1709  NSString *string = [[NSString alloc] initWithUTF8String:"foo"];
1710  [string release];
1711
1712  NSString *otherString = [string stringByAppendingString:@"bar"]; // expected-warning {{Reference-counted object is used after it is release}}
1713  NSLog(@"%@", otherString);
1714}
1715
1716// RetainCountChecker support for XPC.
1717// <rdar://problem/9658496>
1718typedef void * xpc_object_t;
1719xpc_object_t _CFXPCCreateXPCObjectFromCFObject(CFTypeRef cf);
1720void xpc_release(xpc_object_t object);
1721
1722void rdar9658496() {
1723  CFStringRef cf;
1724  xpc_object_t xpc;
1725  cf = CFStringCreateWithCString( ((CFAllocatorRef)0), "test", kCFStringEncodingUTF8 ); // no-warning
1726  xpc = _CFXPCCreateXPCObjectFromCFObject( cf );
1727  CFRelease(cf);
1728  xpc_release(xpc);
1729}
1730
1731// Support annotations with method families.
1732@interface RDar10824732 : NSObject
1733- (id)initWithObj:(id CF_CONSUMED)obj;
1734@end
1735
1736@implementation RDar10824732
1737- (id)initWithObj:(id)obj {
1738  [obj release];
1739  return [super init];
1740}
1741@end
1742
1743void rdar_10824732() {
1744  @autoreleasepool {
1745    NSString *obj = @"test";
1746    RDar10824732 *foo = [[RDar10824732 alloc] initWithObj:obj]; // no-warning
1747    [foo release];
1748  }
1749}
1750
1751// Stop tracking objects passed to functions, which take callbacks as parameters.
1752// radar://10973977
1753typedef int (*CloseCallback) (void *);
1754void ReaderForIO(CloseCallback ioclose, void *ioctx);
1755int IOClose(void *context);
1756
1757@protocol SInS <NSObject>
1758@end
1759
1760@interface radar10973977 : NSObject
1761- (id<SInS>)inputS;
1762- (void)reader;
1763@end
1764
1765@implementation radar10973977
1766- (void)reader
1767{
1768    id<SInS> inputS = [[self inputS] retain];
1769    ReaderForIO(IOClose, inputS);
1770}
1771- (id<SInS>)inputS
1772{
1773    return 0;
1774}
1775@end
1776
1777// Object escapes through a selector callback: radar://11398514
1778extern id NSApp;
1779@interface MySheetController
1780- (id<SInS>)inputS;
1781- (void)showDoSomethingSheetAction:(id)action;
1782- (void)sheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo;
1783@end
1784
1785@implementation MySheetController
1786- (id<SInS>)inputS {
1787    return 0;
1788}
1789- (void)showDoSomethingSheetAction:(id)action {
1790  id<SInS> inputS = [[self inputS] retain];
1791  [NSApp beginSheet:0
1792         modalForWindow:0
1793         modalDelegate:0
1794         didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:)
1795         contextInfo:(void *)inputS]; // no - warning
1796}
1797- (void)sheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo {
1798
1799      id contextObject = (id)contextInfo;
1800      [contextObject release];
1801}
1802
1803- (id)copyAutoreleaseRadar13081402 {
1804  id x = [[[NSString alloc] initWithUTF8String:"foo"] autorelease];
1805  [x retain];
1806  return x; // no warning
1807}
1808
1809@end
1810//===----------------------------------------------------------------------===//
1811// Test returning allocated memory in a struct.
1812//
1813// We currently don't have a general way to track pointers that "escape".
1814// Here we test that RetainCountChecker doesn't get excited about returning
1815// allocated CF objects in struct fields.
1816//===----------------------------------------------------------------------===//
1817void *malloc(size_t);
1818struct rdar11104566 { CFStringRef myStr; };
1819struct rdar11104566 test_rdar11104566() {
1820  CFStringRef cf = CFStringCreateWithCString( ((CFAllocatorRef)0), "test", kCFStringEncodingUTF8 ); // no-warning
1821  struct rdar11104566 V;
1822  V.myStr = cf;
1823  return V; // no-warning
1824}
1825
1826struct rdar11104566 *test_2_rdar11104566() {
1827  CFStringRef cf = CFStringCreateWithCString( ((CFAllocatorRef)0), "test", kCFStringEncodingUTF8 ); // no-warning
1828  struct rdar11104566 *V = (struct rdar11104566 *) malloc(sizeof(*V));
1829  V->myStr = cf;
1830  return V; // no-warning
1831}
1832
1833//===----------------------------------------------------------------------===//
1834// ObjC literals support.
1835//===----------------------------------------------------------------------===//
1836
1837void test_objc_arrays() {
1838    { // CASE ONE -- OBJECT IN ARRAY CREATED DIRECTLY
1839        NSObject *o = [[NSObject alloc] init];
1840        NSArray *a = [[NSArray alloc] initWithObjects:o, (void*)0]; // expected-warning {{leak}}
1841        [o release];
1842        [a description];
1843        [o description];
1844    }
1845
1846    { // CASE TWO -- OBJECT IN ARRAY CREATED BY DUPING AUTORELEASED ARRAY
1847        NSObject *o = [[NSObject alloc] init];
1848        NSArray *a1 = [NSArray arrayWithObjects:o, (void*)0];
1849        NSArray *a2 = [[NSArray alloc] initWithArray:a1]; // expected-warning {{leak}}
1850        [o release];
1851        [a2 description];
1852        [o description];
1853    }
1854
1855    { // CASE THREE -- OBJECT IN RETAINED @[]
1856        NSObject *o = [[NSObject alloc] init];
1857        NSArray *a3 = [@[o] retain]; // expected-warning {{leak}}
1858        [o release];
1859        [a3 description];
1860        [o description];
1861    }
1862
1863    { // CASE FOUR -- OBJECT IN ARRAY CREATED BY DUPING @[]
1864        NSObject *o = [[NSObject alloc] init];
1865        NSArray *a = [[NSArray alloc] initWithArray:@[o]]; // expected-warning {{leak}}
1866        [o release];
1867
1868        [a description];
1869        [o description];
1870    }
1871
1872    { // CASE FIVE -- OBJECT IN RETAINED @{}
1873        NSValue *o = [[NSValue alloc] init];
1874        NSDictionary *a = [@{o : o} retain]; // expected-warning {{leak}}
1875        [o release];
1876
1877        [a description];
1878        [o description];
1879    }
1880}
1881
1882void test_objc_integer_literals() {
1883  id value = [@1 retain]; // expected-warning {{leak}}
1884  [value description];
1885}
1886
1887void test_objc_boxed_expressions(int x, const char *y) {
1888  id value = [@(x) retain]; // expected-warning {{leak}}
1889  [value description];
1890
1891  value = [@(y) retain]; // expected-warning {{leak}}
1892  [value description];
1893}
1894
1895// Test NSLog doesn't escape tracked objects.
1896void rdar11400885(int y)
1897{
1898  @autoreleasepool {
1899    NSString *printString;
1900    if(y > 2)
1901      printString = [[NSString alloc] init];
1902    else
1903      printString = [[NSString alloc] init];
1904    NSLog(@"Once %@", printString);
1905    [printString release];
1906    NSLog(@"Again: %@", printString); // expected-warning {{Reference-counted object is used after it is released}}
1907  }
1908}
1909
1910id makeCollectableNonLeak() {
1911  extern CFTypeRef CFCreateSomething();
1912
1913  CFTypeRef object = CFCreateSomething(); // +1
1914  CFRetain(object); // +2
1915  id objCObject = NSMakeCollectable(object); // +2
1916  [objCObject release]; // +1
1917  return [objCObject autorelease]; // +0
1918}
1919
1920
1921void consumeAndStopTracking(id NS_CONSUMED obj, void (^callback)(void));
1922void CFConsumeAndStopTracking(CFTypeRef CF_CONSUMED obj, void (^callback)(void));
1923
1924void testConsumeAndStopTracking() {
1925  id retained = [@[] retain]; // +1
1926  consumeAndStopTracking(retained, ^{}); // no-warning
1927
1928  id doubleRetained = [[@[] retain] retain]; // +2
1929  consumeAndStopTracking(doubleRetained, ^{
1930    [doubleRetained release];
1931  }); // no-warning
1932
1933  id unretained = @[]; // +0
1934  consumeAndStopTracking(unretained, ^{}); // expected-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
1935}
1936
1937void testCFConsumeAndStopTracking() {
1938  id retained = [@[] retain]; // +1
1939  CFConsumeAndStopTracking((CFTypeRef)retained, ^{}); // no-warning
1940
1941  id doubleRetained = [[@[] retain] retain]; // +2
1942  CFConsumeAndStopTracking((CFTypeRef)doubleRetained, ^{
1943    [doubleRetained release];
1944  }); // no-warning
1945
1946  id unretained = @[]; // +0
1947  CFConsumeAndStopTracking((CFTypeRef)unretained, ^{}); // expected-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
1948}
1949//===----------------------------------------------------------------------===//
1950// Test 'pragma clang arc_cf_code_audited' support.
1951//===----------------------------------------------------------------------===//
1952
1953typedef void *MyCFType;
1954#pragma clang arc_cf_code_audited begin
1955MyCFType CreateMyCFType();
1956#pragma clang arc_cf_code_audited end
1957
1958void test_custom_cf() {
1959  MyCFType x = CreateMyCFType(); // expected-warning {{leak of an object stored into 'x'}}
1960}
1961
1962//===----------------------------------------------------------------------===//
1963// Test calling CFPlugInInstanceCreate, which appears in CF but doesn't
1964// return a CF object.
1965//===----------------------------------------------------------------------===//
1966
1967void test_CFPlugInInstanceCreate(CFUUIDRef factoryUUID, CFUUIDRef typeUUID) {
1968  CFPlugInInstanceCreate(kCFAllocatorDefault, factoryUUID, typeUUID); // no-warning
1969}
1970
1971//===----------------------------------------------------------------------===//
1972// PR14927: -drain only has retain-count semantics on NSAutoreleasePool.
1973//===----------------------------------------------------------------------===//
1974
1975@interface PR14927 : NSObject
1976- (void)drain;
1977@end
1978
1979void test_drain() {
1980  PR14927 *obj = [[PR14927 alloc] init];
1981  [obj drain];
1982  [obj release]; // no-warning
1983}
1984
1985//===----------------------------------------------------------------------===//
1986// Allow cf_returns_retained and cf_returns_not_retained to mark a return
1987// value as tracked, even if the object isn't a known CF type.
1988//===----------------------------------------------------------------------===//
1989
1990MyCFType getCustom() __attribute__((cf_returns_not_retained));
1991MyCFType makeCustom() __attribute__((cf_returns_retained));
1992
1993void testCustomReturnsRetained() {
1994  MyCFType obj = makeCustom(); // expected-warning {{leak of an object stored into 'obj'}}
1995}
1996
1997void testCustomReturnsNotRetained() {
1998  CFRelease(getCustom()); // expected-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
1999}
2000
2001//===----------------------------------------------------------------------===//
2002// Don't print variables which are out of the current scope.
2003//===----------------------------------------------------------------------===//
2004@interface MyObj12706177 : NSObject
2005-(id)initX;
2006+(void)test12706177;
2007@end
2008static int Cond;
2009@implementation MyObj12706177
2010-(id)initX {
2011  if (Cond)
2012    return 0;
2013  self = [super init];
2014  return self;
2015}
2016+(void)test12706177 {
2017  id x = [[MyObj12706177 alloc] initX]; //expected-warning {{Potential leak of an object}}
2018  [x release];
2019}
2020@end
2021
2022//===----------------------------------------------------------------------===//
2023// <rdar://problem/13783514> xpc_connection_set_finalizer_f
2024//===----------------------------------------------------------------------===//
2025
2026typedef xpc_object_t xpc_connection_t;
2027typedef void (*xpc_finalizer_t)(void *value);
2028void xpc_connection_set_context(xpc_connection_t connection, void *ctx);
2029void xpc_connection_set_finalizer_f(xpc_connection_t connection,
2030                                    xpc_finalizer_t finalizer);
2031void releaseAfterXPC(void *context) {
2032  [(NSArray *)context release];
2033}
2034
2035void rdar13783514(xpc_connection_t connection) {
2036  xpc_connection_set_context(connection, [[NSMutableArray alloc] init]);
2037  xpc_connection_set_finalizer_f(connection, releaseAfterXPC);
2038} // no-warning
2039
2040CFAttributedStringRef CFAttributedCreate(void *CFObj CF_CONSUMED) CF_RETURNS_RETAINED;
2041
2042@interface Action
2043- (SEL)action;
2044- (void)setAction:(SEL)aSelector;
2045- (id) target;
2046- (void)setTarget:(id)aTarget;
2047@end
2048