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