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