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