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