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