retain-release.m revision 38c8fe705ec4a8efa8992b99ab6d264fff14ca36
1// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -analyze -analyzer-checker=macosx.CFRetainRelease,cocoa.ClassRelease -analyzer-check-objc-mem -analyzer-store=basic -fblocks -verify %s
2// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -analyze -analyzer-checker=macosx.CFRetainRelease,cocoa.ClassRelease -analyzer-check-objc-mem -analyzer-store=region -fblocks -verify %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 struct {
46    CFIndex location;
47    CFIndex length;
48} CFRange;
49static __inline__ __attribute__((always_inline)) CFRange CFRangeMake(CFIndex loc, CFIndex len) {
50    CFRange range;
51    range.location = loc;
52    range.length = len;
53    return range;
54}
55typedef const void * CFTypeRef;
56typedef const struct __CFString * CFStringRef;
57typedef const struct __CFAllocator * CFAllocatorRef;
58extern const CFAllocatorRef kCFAllocatorDefault;
59extern CFTypeRef CFRetain(CFTypeRef cf);
60extern void CFRelease(CFTypeRef cf);
61typedef struct {
62}
63CFArrayCallBacks;
64extern const CFArrayCallBacks kCFTypeArrayCallBacks;
65typedef const struct __CFArray * CFArrayRef;
66typedef struct __CFArray * CFMutableArrayRef;
67extern CFMutableArrayRef CFArrayCreateMutable(CFAllocatorRef allocator, CFIndex capacity, const CFArrayCallBacks *callBacks);
68extern const void *CFArrayGetValueAtIndex(CFArrayRef theArray, CFIndex idx);
69extern void CFArrayAppendValue(CFMutableArrayRef theArray, const void *value);
70typedef struct {
71}
72CFDictionaryKeyCallBacks;
73extern const CFDictionaryKeyCallBacks kCFTypeDictionaryKeyCallBacks;
74typedef struct {
75}
76CFDictionaryValueCallBacks;
77extern const CFDictionaryValueCallBacks kCFTypeDictionaryValueCallBacks;
78typedef const struct __CFDictionary * CFDictionaryRef;
79typedef struct __CFDictionary * CFMutableDictionaryRef;
80extern CFMutableDictionaryRef CFDictionaryCreateMutable(CFAllocatorRef allocator, CFIndex capacity, const CFDictionaryKeyCallBacks *keyCallBacks, const CFDictionaryValueCallBacks *valueCallBacks);
81typedef UInt32 CFStringEncoding;
82enum {
83kCFStringEncodingMacRoman = 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  };
84extern CFStringRef CFStringCreateWithCString(CFAllocatorRef alloc, const char *cStr, CFStringEncoding encoding);
85typedef double CFTimeInterval;
86typedef CFTimeInterval CFAbsoluteTime;
87extern CFAbsoluteTime CFAbsoluteTimeGetCurrent(void);
88typedef const struct __CFDate * CFDateRef;
89extern CFDateRef CFDateCreate(CFAllocatorRef allocator, CFAbsoluteTime at);
90extern CFAbsoluteTime CFDateGetAbsoluteTime(CFDateRef theDate);
91typedef __darwin_natural_t natural_t;
92typedef natural_t mach_port_name_t;
93typedef mach_port_name_t mach_port_t;
94typedef int kern_return_t;
95typedef kern_return_t mach_error_t;
96enum {
97kCFNumberSInt8Type = 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    };
98typedef CFIndex CFNumberType;
99typedef const struct __CFNumber * CFNumberRef;
100extern CFNumberRef CFNumberCreate(CFAllocatorRef allocator, CFNumberType theType, const void *valuePtr);
101typedef const struct __CFAttributedString *CFAttributedStringRef;
102typedef struct __CFAttributedString *CFMutableAttributedStringRef;
103extern CFAttributedStringRef CFAttributedStringCreate(CFAllocatorRef alloc, CFStringRef str, CFDictionaryRef attributes) ;
104extern CFMutableAttributedStringRef CFAttributedStringCreateMutableCopy(CFAllocatorRef alloc, CFIndex maxLength, CFAttributedStringRef aStr) ;
105extern void CFAttributedStringSetAttribute(CFMutableAttributedStringRef aStr, CFRange range, CFStringRef attrName, CFTypeRef value) ;
106typedef signed char BOOL;
107typedef unsigned long NSUInteger;
108@class NSString, Protocol;
109extern void NSLog(NSString *format, ...) __attribute__((format(__NSString__, 1, 2)));
110typedef struct _NSZone NSZone;
111@class NSInvocation, NSMethodSignature, NSCoder, NSString, NSEnumerator;
112@protocol NSObject
113- (BOOL)isEqual:(id)object;
114- (id)retain;
115- (oneway void)release;
116- (id)autorelease;
117@end  @protocol NSCopying  - (id)copyWithZone:(NSZone *)zone;
118@end  @protocol NSMutableCopying  - (id)mutableCopyWithZone:(NSZone *)zone;
119@end  @protocol NSCoding  - (void)encodeWithCoder:(NSCoder *)aCoder;
120@end
121@interface NSObject <NSObject> {}
122+ (id)allocWithZone:(NSZone *)zone;
123+ (id)alloc;
124- (void)dealloc;
125@end
126@interface NSObject (NSCoderMethods)
127- (id)awakeAfterUsingCoder:(NSCoder *)aDecoder;
128@end
129extern id NSAllocateObject(Class aClass, NSUInteger extraBytes, NSZone *zone);
130typedef struct {
131}
132NSFastEnumerationState;
133@protocol NSFastEnumeration  - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len;
134@end           @class NSString, NSDictionary;
135@interface NSValue : NSObject <NSCopying, NSCoding>  - (void)getValue:(void *)value;
136@end  @interface NSNumber : NSValue  - (char)charValue;
137- (id)initWithInt:(int)value;
138@end   @class NSString;
139@interface NSArray : NSObject <NSCopying, NSMutableCopying, NSCoding, NSFastEnumeration>  - (NSUInteger)count;
140@end  @interface NSArray (NSArrayCreation)  + (id)array;
141@end       @interface NSAutoreleasePool : NSObject {
142}
143- (void)drain;
144@end extern NSString * const NSBundleDidLoadNotification;
145typedef double NSTimeInterval;
146@interface NSDate : NSObject <NSCopying, NSCoding>  - (NSTimeInterval)timeIntervalSinceReferenceDate;
147@end            typedef unsigned short unichar;
148@interface NSString : NSObject <NSCopying, NSMutableCopying, NSCoding>    - (NSUInteger)length;
149- ( const char *)UTF8String;
150- (id)initWithUTF8String:(const char *)nullTerminatedCString;
151+ (id)stringWithUTF8String:(const char *)nullTerminatedCString;
152@end        @class NSString, NSURL, NSError;
153@interface NSData : NSObject <NSCopying, NSMutableCopying, NSCoding>  - (NSUInteger)length;
154+ (id)dataWithBytesNoCopy:(void *)bytes length:(NSUInteger)length;
155+ (id)dataWithBytesNoCopy:(void *)bytes length:(NSUInteger)length freeWhenDone:(BOOL)b;
156@end   @class NSLocale, NSDate, NSCalendar, NSTimeZone, NSError, NSArray, NSMutableDictionary;
157@interface NSDictionary : NSObject <NSCopying, NSMutableCopying, NSCoding, NSFastEnumeration>  - (NSUInteger)count;
158@end    @interface NSMutableDictionary : NSDictionary  - (void)removeObjectForKey:(id)aKey;
159- (void)setObject:(id)anObject forKey:(id)aKey;
160@end  @interface NSMutableDictionary (NSMutableDictionaryCreation)  + (id)dictionaryWithCapacity:(NSUInteger)numItems;
161@end  typedef double CGFloat;
162struct CGSize {
163};
164typedef struct CGSize CGSize;
165struct CGRect {
166};
167typedef struct CGRect CGRect;
168typedef mach_port_t io_object_t;
169typedef char io_name_t[128];
170typedef io_object_t io_iterator_t;
171typedef io_object_t io_service_t;
172typedef struct IONotificationPort * IONotificationPortRef;
173typedef void (*IOServiceMatchingCallback)(  void * refcon,  io_iterator_t iterator );
174io_service_t IOServiceGetMatchingService(  mach_port_t masterPort,  CFDictionaryRef matching );
175kern_return_t IOServiceGetMatchingServices(  mach_port_t masterPort,  CFDictionaryRef matching,  io_iterator_t * existing );
176kern_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));
177kern_return_t IOServiceAddMatchingNotification(  IONotificationPortRef notifyPort,  const io_name_t notificationType,  CFDictionaryRef matching,         IOServiceMatchingCallback callback,         void * refCon,  io_iterator_t * notification );
178CFMutableDictionaryRef IOServiceMatching(  const char * name );
179CFMutableDictionaryRef IOServiceNameMatching(  const char * name );
180CFMutableDictionaryRef IOBSDNameMatching(  mach_port_t masterPort,  uint32_t options,  const char * bsdName );
181CFMutableDictionaryRef IOOpenFirmwarePathMatching(  mach_port_t masterPort,  uint32_t options,  const char * path );
182CFMutableDictionaryRef IORegistryEntryIDMatching(  uint64_t entryID );
183typedef struct __DASession * DASessionRef;
184extern DASessionRef DASessionCreate( CFAllocatorRef allocator );
185typedef struct __DADisk * DADiskRef;
186extern DADiskRef DADiskCreateFromBSDName( CFAllocatorRef allocator, DASessionRef session, const char * name );
187extern DADiskRef DADiskCreateFromIOMedia( CFAllocatorRef allocator, DASessionRef session, io_service_t media );
188extern CFDictionaryRef DADiskCopyDescription( DADiskRef disk );
189extern DADiskRef DADiskCopyWholeDisk( DADiskRef disk );
190@interface NSTask : NSObject - (id)init;
191@end                    typedef struct CGColorSpace *CGColorSpaceRef;
192typedef struct CGImage *CGImageRef;
193typedef struct CGLayer *CGLayerRef;
194@interface NSResponder : NSObject <NSCoding> {
195}
196@end    @protocol NSAnimatablePropertyContainer      - (id)animator;
197@end  extern NSString *NSAnimationTriggerOrderIn ;
198@interface NSView : NSResponder  <NSAnimatablePropertyContainer>  {
199}
200@end @protocol NSValidatedUserInterfaceItem - (SEL)action;
201@end   @protocol NSUserInterfaceValidations - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)anItem;
202@end  @class NSDate, NSDictionary, NSError, NSException, NSNotification;
203@interface NSApplication : NSResponder <NSUserInterfaceValidations> {
204}
205@end   enum {
206NSTerminateCancel = 0,         NSTerminateNow = 1,         NSTerminateLater = 2 };
207typedef NSUInteger NSApplicationTerminateReply;
208@protocol NSApplicationDelegate <NSObject> @optional        - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender;
209@end  @class NSAttributedString, NSEvent, NSFont, NSFormatter, NSImage, NSMenu, NSText, NSView, NSTextView;
210@interface NSCell : NSObject <NSCopying, NSCoding> {
211}
212@end @class NSTextField, NSPanel, NSArray, NSWindow, NSImage, NSButton, NSError;
213typedef struct {
214}
215CVTimeStamp;
216@interface CIImage : NSObject <NSCoding, NSCopying> {
217}
218typedef int CIFormat;
219@end  enum {
220kDAReturnSuccess = 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 };
221typedef mach_error_t DAReturn;
222typedef const struct __DADissenter * DADissenterRef;
223extern DADissenterRef DADissenterCreate( CFAllocatorRef allocator, DAReturn status, CFStringRef string );
224@interface CIContext: NSObject {
225}
226- (CGImageRef)createCGImage:(CIImage *)im fromRect:(CGRect)r;
227- (CGImageRef)createCGImage:(CIImage *)im fromRect:(CGRect)r     format:(CIFormat)f colorSpace:(CGColorSpaceRef)cs;
228- (CGLayerRef)createCGLayerWithSize:(CGSize)size info:(CFDictionaryRef)d;
229@end extern NSString* const QCRendererEventKey;
230@protocol QCCompositionRenderer - (NSDictionary*) attributes;
231@end   @interface QCRenderer : NSObject <QCCompositionRenderer> {
232}
233- (id) createSnapshotImageOfType:(NSString*)type;
234@end  extern NSString* const QCViewDidStartRenderingNotification;
235@interface QCView : NSView <QCCompositionRenderer> {
236}
237- (id) createSnapshotImageOfType:(NSString*)type;
238@end    enum {
239ICEXIFOrientation1 = 1,     ICEXIFOrientation2 = 2,     ICEXIFOrientation3 = 3,     ICEXIFOrientation4 = 4,     ICEXIFOrientation5 = 5,     ICEXIFOrientation6 = 6,     ICEXIFOrientation7 = 7,     ICEXIFOrientation8 = 8, };
240@class ICDevice;
241@protocol ICDeviceDelegate <NSObject>  @required      - (void)didRemoveDevice:(ICDevice*)device;
242@end extern NSString *const ICScannerStatusWarmingUp;
243@class ICScannerDevice;
244@protocol ICScannerDeviceDelegate <ICDeviceDelegate>  @optional       - (void)scannerDeviceDidBecomeAvailable:(ICScannerDevice*)scanner;
245@end
246
247typedef long unsigned int __darwin_size_t;
248typedef __darwin_size_t size_t;
249typedef unsigned long CFTypeID;
250struct CGPoint {
251  CGFloat x;
252  CGFloat y;
253};
254typedef struct CGPoint CGPoint;
255typedef struct CGGradient *CGGradientRef;
256typedef uint32_t CGGradientDrawingOptions;
257extern CFTypeID CGGradientGetTypeID(void);
258extern CGGradientRef CGGradientCreateWithColorComponents(CGColorSpaceRef
259  space, const CGFloat components[], const CGFloat locations[], size_t count);
260extern CGGradientRef CGGradientCreateWithColors(CGColorSpaceRef space,
261  CFArrayRef colors, const CGFloat locations[]);
262extern CGGradientRef CGGradientRetain(CGGradientRef gradient);
263extern void CGGradientRelease(CGGradientRef gradient);
264typedef struct CGContext *CGContextRef;
265extern void CGContextDrawLinearGradient(CGContextRef context,
266    CGGradientRef gradient, CGPoint startPoint, CGPoint endPoint,
267    CGGradientDrawingOptions options);
268extern CGColorSpaceRef CGColorSpaceCreateDeviceRGB(void);
269
270//===----------------------------------------------------------------------===//
271// Test cases.
272//===----------------------------------------------------------------------===//
273
274CFAbsoluteTime f1() {
275  CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
276  CFDateRef date = CFDateCreate(0, t);
277  CFRetain(date);
278  CFRelease(date);
279  CFDateGetAbsoluteTime(date); // no-warning
280  CFRelease(date);
281  t = CFDateGetAbsoluteTime(date);   // expected-warning{{Reference-counted object is used after it is released.}}
282  return t;
283}
284
285CFAbsoluteTime f2() {
286  CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
287  CFDateRef date = CFDateCreate(0, t);  
288  [((NSDate*) date) retain];
289  CFRelease(date);
290  CFDateGetAbsoluteTime(date); // no-warning
291  [((NSDate*) date) release];
292  t = CFDateGetAbsoluteTime(date);   // expected-warning{{Reference-counted object is used after it is released.}}
293  return t;
294}
295
296
297NSDate* global_x;
298
299// Test to see if we supresss an error when we store the pointer
300// to a global.
301
302CFAbsoluteTime f3() {
303  CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
304  CFDateRef date = CFDateCreate(0, t);  
305  [((NSDate*) date) retain];
306  CFRelease(date);
307  CFDateGetAbsoluteTime(date); // no-warning
308  global_x = (NSDate*) date;  
309  [((NSDate*) date) release];
310  t = CFDateGetAbsoluteTime(date);   // no-warning
311  return t;
312}
313
314//---------------------------------------------------------------------------
315// Test case 'f4' differs for region store and basic store.  See
316// retain-release-region-store.m and retain-release-basic-store.m.
317//---------------------------------------------------------------------------
318
319// Test a leak.
320
321CFAbsoluteTime f5(int x) {  
322  CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
323  CFDateRef date = CFDateCreate(0, t); // expected-warning{{leak}}
324  
325  if (x)
326    CFRelease(date);
327  
328  return t;
329}
330
331// Test a leak involving the return.
332
333CFDateRef f6(int x) {  
334  CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent());  // expected-warning{{leak}}
335  CFRetain(date);
336  return date;
337}
338
339// Test a leak involving an overwrite.
340
341CFDateRef f7() {
342  CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent());  //expected-warning{{leak}}
343  CFRetain(date);
344  date = CFDateCreate(0, CFAbsoluteTimeGetCurrent());
345  return date;
346}
347
348// Generalization of Create rule.  MyDateCreate returns a CFXXXTypeRef, and
349// has the word create.
350CFDateRef MyDateCreate();
351
352CFDateRef f8() {
353  CFDateRef date = MyDateCreate(); // expected-warning{{leak}}
354  CFRetain(date);  
355  return date;
356}
357
358CFDateRef f9() {
359  CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent());
360  int *p = 0;
361  // When allocations fail, CFDateCreate can return null.
362  if (!date) *p = 1; // expected-warning{{null}}
363  return date;
364}
365
366// Handle DiskArbitration API:
367//
368// http://developer.apple.com/DOCUMENTATION/DARWIN/Reference/DiscArbitrationFramework/
369//
370void f10(io_service_t media, DADiskRef d, CFStringRef s) {
371  DADiskRef disk = DADiskCreateFromBSDName(kCFAllocatorDefault, 0, "hello"); // expected-warning{{leak}}
372  if (disk) NSLog(@"ok");
373  
374  disk = DADiskCreateFromIOMedia(kCFAllocatorDefault, 0, media); // expected-warning{{leak}}
375  if (disk) NSLog(@"ok");
376
377  CFDictionaryRef dict = DADiskCopyDescription(d);  // expected-warning{{leak}}
378  if (dict) NSLog(@"ok"); 
379  
380  disk = DADiskCopyWholeDisk(d); // expected-warning{{leak}}
381  if (disk) NSLog(@"ok");
382    
383  DADissenterRef dissenter = DADissenterCreate(kCFAllocatorDefault,   // expected-warning{{leak}}
384                                                kDAReturnSuccess, s);
385  if (dissenter) NSLog(@"ok");
386  
387  DASessionRef session = DASessionCreate(kCFAllocatorDefault);  // expected-warning{{leak}}
388  if (session) NSLog(@"ok");
389}
390
391// Test retain/release checker with CFString and CFMutableArray.
392void f11() {
393  // Create the array.
394  CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
395
396  // Create a string.
397  CFStringRef s1 = CFStringCreateWithCString(0, "hello world",
398                                             kCFStringEncodingUTF8);
399
400  // Add the string to the array.
401  CFArrayAppendValue(A, s1);
402  
403  // Decrement the reference count.
404  CFRelease(s1); // no-warning
405  
406  // Get the string.  We don't own it.
407  s1 = (CFStringRef) CFArrayGetValueAtIndex(A, 0);
408  
409  // Release the array.
410  CFRelease(A); // no-warning
411  
412  // Release the string.  This is a bug.
413  CFRelease(s1); // expected-warning{{Incorrect decrement of the reference count}}
414}
415
416// PR 3337: Handle functions declared using typedefs.
417typedef CFTypeRef CREATEFUN();
418CREATEFUN MyCreateFun;
419
420void f12() {
421  CFTypeRef o = MyCreateFun(); // expected-warning {{leak}}
422}
423
424void f13_autorelease() {
425  CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
426  [(id) A autorelease]; // no-warning
427}
428
429void f13_autorelease_b() {
430  CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
431  [(id) A autorelease];
432  [(id) A autorelease]; // expected-warning{{Object sent -autorelease too many times}}
433}
434
435CFMutableArrayRef f13_autorelease_c() {
436  CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
437  [(id) A autorelease];
438  [(id) A autorelease]; 
439  return A; // expected-warning{{Object sent -autorelease too many times}}
440}
441
442CFMutableArrayRef f13_autorelease_d() {
443  CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
444  [(id) A autorelease];
445  [(id) A autorelease]; 
446  CFMutableArrayRef B = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning{{Object sent -autorelease too many times}}
447  CFRelease(B); // no-warning
448  while (1) {}
449}
450
451
452// This case exercises the logic where the leak site is the same as the allocation site.
453void f14_leakimmediately() {
454  CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning{{leak}}
455}
456
457// Test that we track an allocated object beyond the point where the *name*
458// of the variable storing the reference is no longer live.
459void f15() {
460  // Create the array.
461  CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
462  CFMutableArrayRef *B = &A;
463  // At this point, the name 'A' is no longer live.
464  CFRelease(*B);  // no-warning
465}
466
467// Test when we pass NULL to CFRetain/CFRelease.
468void f16(int x, CFTypeRef p) {
469  if (p)
470    return;
471
472  if (x) {
473    CFRelease(p); // expected-warning{{Null pointer argument in call to CFRelease}}
474  }
475  else {
476    CFRetain(p); // expected-warning{{Null pointer argument in call to CFRetain}}
477  }
478}
479
480// Test that an object is non-null after being CFRetained/CFReleased.
481void f17(int x, CFTypeRef p) {
482  if (x) {
483    CFRelease(p);
484    if (!p)
485      CFRelease(0); // no-warning
486  }
487  else {
488    CFRetain(p);
489    if (!p)
490      CFRetain(0); // no-warning
491  }
492}
493
494// Test basic tracking of ivars associated with 'self'.  For the retain/release
495// checker we currently do not want to flag leaks associated with stores
496// of tracked objects to ivars.
497@interface SelfIvarTest : NSObject {
498  id myObj;
499}
500- (void)test_self_tracking;
501@end
502
503@implementation SelfIvarTest
504- (void)test_self_tracking {
505  myObj = (id) CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
506}
507@end
508
509// Test return of non-owned objects in contexts where an owned object
510// is expected.
511@interface TestReturnNotOwnedWhenExpectedOwned
512- (NSString*)newString;
513@end
514
515@implementation TestReturnNotOwnedWhenExpectedOwned
516- (NSString*)newString {
517  NSString *s = [NSString stringWithUTF8String:"hello"];
518  return s; // expected-warning{{Object with +0 retain counts returned to caller where a +1 (owning) retain count is expected}}
519}
520@end
521
522// <rdar://problem/6659160>
523int isFoo(char c);
524
525static void rdar_6659160(char *inkind, char *inname)
526{
527  // We currently expect that [NSObject alloc] cannot fail.  This
528  // will be a toggled flag in the future.  It can indeed return null, but
529  // Cocoa programmers generally aren't expected to reason about out-of-memory
530  // conditions.
531  NSString *kind = [[NSString alloc] initWithUTF8String:inkind];  // expected-warning{{leak}}
532  
533  // We do allow stringWithUTF8String to fail.  This isn't really correct, as
534  // far as returning 0.  In most error conditions it will throw an exception.
535  // If allocation fails it could return 0, but again this
536  // isn't expected.
537  NSString *name = [NSString stringWithUTF8String:inname];
538  if(!name)
539    return;
540
541  const char *kindC = 0;
542  const char *nameC = 0;
543  
544  // In both cases, we cannot reach a point down below where we
545  // dereference kindC or nameC with either being null.  This is because
546  // we assume that [NSObject alloc] doesn't fail and that we have the guard
547  // up above.
548  
549  if(kind)
550    kindC = [kind UTF8String];
551  if(name)
552    nameC = [name UTF8String];
553  if(!isFoo(kindC[0])) // expected-warning{{null}}
554    return;
555  if(!isFoo(nameC[0])) // no-warning
556    return;
557
558  [kind release];
559  [name release]; // expected-warning{{Incorrect decrement of the reference count}}
560}
561
562// PR 3677 - 'allocWithZone' should be treated as following the Cocoa naming
563//  conventions with respect to 'return'ing ownership.
564@interface PR3677: NSObject @end
565@implementation PR3677
566+ (id)allocWithZone:(NSZone *)inZone {
567  return [super allocWithZone:inZone];  // no-warning
568}
569@end
570
571// PR 3820 - Reason about calls to -dealloc
572void pr3820_DeallocInsteadOfRelease(void)
573{
574  id foo = [[NSString alloc] init]; // no-warning
575  [foo dealloc];
576  // foo is not leaked, since it has been deallocated.
577}
578
579void pr3820_ReleaseAfterDealloc(void)
580{
581  id foo = [[NSString alloc] init];
582  [foo dealloc];
583  [foo release];  // expected-warning{{used after it is release}}
584  // NSInternalInconsistencyException: message sent to deallocated object
585}
586
587void pr3820_DeallocAfterRelease(void)
588{
589  NSLog(@"\n\n[%s]", __FUNCTION__);
590  id foo = [[NSString alloc] init];
591  [foo release];
592  [foo dealloc]; // expected-warning{{used after it is released}}
593  // message sent to released object
594}
595
596// From <rdar://problem/6704930>.  The problem here is that 'length' binds to
597// '($0 - 1)' after '--length', but SimpleConstraintManager doesn't know how to
598// reason about '($0 - 1) > constant'.  As a temporary hack, we drop the value
599// of '($0 - 1)' and conjure a new symbol.
600void rdar6704930(unsigned char *s, unsigned int length) {
601  NSString* name = 0;
602  if (s != 0) {
603    if (length > 0) {
604      while (length > 0) {
605        if (*s == ':') {
606          ++s;
607          --length;
608          name = [[NSString alloc] init]; // no-warning
609          break;
610        }
611        ++s;
612        --length;
613      }
614      if ((length == 0) && (name != 0)) {
615        [name release];
616        name = 0;
617      }
618      if (length == 0) { // no ':' found -> use it all as name
619        name = [[NSString alloc] init]; // no-warning
620      }
621    }
622  }
623
624  if (name != 0) {
625    [name release];
626  }
627}
628
629//===----------------------------------------------------------------------===//
630// <rdar://problem/6833332>
631// One build of the analyzer accidentally stopped tracking the allocated
632// object after the 'retain'.
633//===----------------------------------------------------------------------===//
634
635@interface rdar_6833332 : NSObject <NSApplicationDelegate> {
636    NSWindow *window;
637}
638@property (nonatomic, retain) NSWindow *window;
639@end
640
641@implementation rdar_6833332
642@synthesize window;
643- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
644 NSMutableDictionary *dict = [[NSMutableDictionary dictionaryWithCapacity:4] retain]; // expected-warning{{leak}}
645
646 [dict setObject:@"foo" forKey:@"bar"];
647
648 NSLog(@"%@", dict);
649}
650- (void)dealloc {
651    [window release];
652    [super dealloc];
653}
654@end
655
656//===----------------------------------------------------------------------===//
657// <rdar://problem/6257780> clang checker fails to catch use-after-release
658//===----------------------------------------------------------------------===//
659                                 
660int rdar_6257780_Case1() {
661  NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
662  NSArray *array = [NSArray array];
663  [array release]; // expected-warning{{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
664  [pool drain];
665  return 0;
666}
667
668//===----------------------------------------------------------------------===//
669// <rdar://problem/6866843> Checker should understand new/setObject:/release constructs
670//===----------------------------------------------------------------------===//
671
672void rdar_6866843() {
673 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
674 NSMutableDictionary* dictionary = [[NSMutableDictionary alloc] init];
675 NSArray* array = [[NSArray alloc] init];
676 [dictionary setObject:array forKey:@"key"];
677 [array release];
678 // Using 'array' here should be fine
679 NSLog(@"array = %@\n", array); // no-warning
680 // Now the array is released
681 [dictionary release];
682 [pool drain];
683}
684
685
686//===----------------------------------------------------------------------===//
687// <rdar://problem/6877235> Classes typedef-ed to CF objects should get the same treatment as CF objects
688//===----------------------------------------------------------------------===//
689
690typedef CFTypeRef OtherRef;
691
692@interface RDar6877235 : NSObject {}
693- (CFTypeRef)_copyCFTypeRef;
694- (OtherRef)_copyOtherRef;
695@end
696
697@implementation RDar6877235
698- (CFTypeRef)_copyCFTypeRef {
699  return [[NSString alloc] init]; // no-warning
700}
701- (OtherRef)_copyOtherRef {
702  return [[NSString alloc] init]; // no-warning
703}
704@end
705
706//===----------------------------------------------------------------------===//
707//<rdar://problem/6320065> false positive - init method returns an object
708// owned by caller
709//===----------------------------------------------------------------------===//
710
711@interface RDar6320065 : NSObject {
712  NSString *_foo;
713}
714- (id)initReturningNewClass;
715- (id)_initReturningNewClassBad;
716- (id)initReturningNewClassBad2;
717@end
718
719@interface RDar6320065Subclass : RDar6320065
720@end
721
722@implementation RDar6320065
723- (id)initReturningNewClass {
724  [self release];
725  self = [[RDar6320065Subclass alloc] init]; // no-warning
726  return self;
727}
728- (id)_initReturningNewClassBad {
729  [self release];
730  [[RDar6320065Subclass alloc] init]; // expected-warning {{leak}}
731  return self;
732}
733- (id)initReturningNewClassBad2 {
734  [self release];
735  self = [[RDar6320065Subclass alloc] init];
736  return [self autorelease]; // expected-warning{{Object with +0 retain counts returned to caller where a +1 (owning) retain count is expected}}
737}
738
739@end
740
741@implementation RDar6320065Subclass
742@end
743
744int RDar6320065_test() {
745  RDar6320065 *test = [[RDar6320065 alloc] init]; // no-warning
746  [test release];
747  return 0;
748}
749
750//===----------------------------------------------------------------------===//
751// <rdar://problem/7129086> -awakeAfterUsingCoder: returns an owned object 
752//  and claims the receiver
753//===----------------------------------------------------------------------===//
754
755@interface RDar7129086 : NSObject {} @end
756@implementation RDar7129086
757- (id)awakeAfterUsingCoder:(NSCoder *)aDecoder {
758  [self release]; // no-warning
759  return [NSString alloc];  // no-warning
760}
761@end
762
763//===----------------------------------------------------------------------===//
764// <rdar://problem/6859457> [NSData dataWithBytesNoCopy] does not return a
765//  retained object
766//===----------------------------------------------------------------------===//
767
768@interface RDar6859457 : NSObject {}
769- (NSString*) NoCopyString;
770- (NSString*) noCopyString;
771@end
772
773@implementation RDar6859457 
774- (NSString*) NoCopyString { return [[NSString alloc] init]; } // expected-warning{{leak}}
775- (NSString*) noCopyString { return [[NSString alloc] init]; } // expected-warning{{leak}}
776@end
777
778void test_RDar6859457(RDar6859457 *x, void *bytes, NSUInteger dataLength) {
779  [x NoCopyString]; // no-warning
780  [x noCopyString]; // no-warning
781  [NSData dataWithBytesNoCopy:bytes length:dataLength];  // no-warning
782  [NSData dataWithBytesNoCopy:bytes length:dataLength freeWhenDone:1]; // no-warning
783}
784
785//===----------------------------------------------------------------------===//
786// PR 4230 - an autorelease pool is not necessarily leaked during a premature
787//  return
788//===----------------------------------------------------------------------===//
789
790static void PR4230(void)
791{
792  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // no-warning
793  NSString *object = [[[NSString alloc] init] autorelease]; // no-warning
794  return;
795}
796
797//===----------------------------------------------------------------------===//
798// Method name that has a null IdentifierInfo* for its first selector slot.
799// This test just makes sure that we handle it.
800//===----------------------------------------------------------------------===//
801
802@interface TestNullIdentifier
803@end
804
805@implementation TestNullIdentifier
806+ (id):(int)x, ... {
807  return [[NSString alloc] init]; // expected-warning{{leak}}
808}
809@end
810
811//===----------------------------------------------------------------------===//
812// <rdar://problem/6893565> don't flag leaks for return types that cannot be 
813//                          determined to be CF types
814//===----------------------------------------------------------------------===//
815
816// We don't know if 'struct s6893565' represents a Core Foundation type, so
817// we shouldn't emit an error here.
818typedef struct s6893565* TD6893565;
819
820@interface RDar6893565 {}
821-(TD6893565)newThing;
822@end
823
824@implementation RDar6893565
825-(TD6893565)newThing {  
826  return (TD6893565) [[NSString alloc] init]; // no-warning
827}
828@end
829
830//===----------------------------------------------------------------------===//
831// <rdar://problem/6902710> clang: false positives w/QC and CoreImage methods
832//===----------------------------------------------------------------------===//
833
834void rdar6902710(QCView *view, QCRenderer *renderer, CIContext *context,
835                 NSString *str, CIImage *img, CGRect rect,
836                 CIFormat form, CGColorSpaceRef cs) {
837  [view createSnapshotImageOfType:str]; // expected-warning{{leak}}
838  [renderer createSnapshotImageOfType:str]; // expected-warning{{leak}}
839  [context createCGImage:img fromRect:rect]; // expected-warning{{leak}}
840  [context createCGImage:img fromRect:rect format:form colorSpace:cs]; // expected-warning{{leak}}
841}
842
843//===----------------------------------------------------------------------===//
844// <rdar://problem/6945561> -[CIContext createCGLayerWithSize:info:]
845//                           misinterpreted by clang scan-build
846//===----------------------------------------------------------------------===//
847
848void rdar6945561(CIContext *context, CGSize size, CFDictionaryRef d) {
849  [context createCGLayerWithSize:size info:d]; // expected-warning{{leak}}
850}
851
852//===----------------------------------------------------------------------===//
853// <rdar://problem/6961230> add knowledge of IOKit functions to retain/release 
854//                          checker
855//===----------------------------------------------------------------------===//
856
857void IOBSDNameMatching_wrapper(mach_port_t masterPort, uint32_t options,  const char * bsdName) {  
858  IOBSDNameMatching(masterPort, options, bsdName); // expected-warning{{leak}}
859}
860
861void IOServiceMatching_wrapper(const char * name) {
862  IOServiceMatching(name); // expected-warning{{leak}}
863}
864
865void IOServiceNameMatching_wrapper(const char * name) {
866  IOServiceNameMatching(name); // expected-warning{{leak}}
867}
868
869CF_RETURNS_RETAINED CFDictionaryRef CreateDict();
870
871void IOServiceAddNotification_wrapper(mach_port_t masterPort, const io_name_t notificationType,
872  mach_port_t wakePort, uintptr_t reference, io_iterator_t * notification ) {
873
874  CFDictionaryRef matching = CreateDict();
875  CFRelease(matching);
876  IOServiceAddNotification(masterPort, notificationType, matching, // expected-warning{{used after it is released}} expected-warning{{deprecated}}
877                           wakePort, reference, notification);
878}
879
880void IORegistryEntryIDMatching_wrapper(uint64_t entryID ) {
881  IORegistryEntryIDMatching(entryID); // expected-warning{{leak}}
882}
883
884void IOOpenFirmwarePathMatching_wrapper(mach_port_t masterPort, uint32_t options,
885                                        const char * path) {
886  IOOpenFirmwarePathMatching(masterPort, options, path); // expected-warning{{leak}}
887}
888
889void IOServiceGetMatchingService_wrapper(mach_port_t masterPort) {
890  CFDictionaryRef matching = CreateDict();
891  IOServiceGetMatchingService(masterPort, matching);
892  CFRelease(matching); // expected-warning{{used after it is released}}
893}
894
895void IOServiceGetMatchingServices_wrapper(mach_port_t masterPort, io_iterator_t *existing) {
896  CFDictionaryRef matching = CreateDict();
897  IOServiceGetMatchingServices(masterPort, matching, existing);
898  CFRelease(matching); // expected-warning{{used after it is released}}
899}
900
901void IOServiceAddMatchingNotification_wrapper(IONotificationPortRef notifyPort, const io_name_t notificationType, 
902  IOServiceMatchingCallback callback, void * refCon, io_iterator_t * notification) {
903    
904  CFDictionaryRef matching = CreateDict();
905  IOServiceAddMatchingNotification(notifyPort, notificationType, matching, callback, refCon, notification);
906  CFRelease(matching); // expected-warning{{used after it is released}}
907}
908
909//===----------------------------------------------------------------------===//
910// Test of handling objects whose references "escape" to containers.
911//===----------------------------------------------------------------------===//
912
913void CFDictionaryAddValue();
914
915// <rdar://problem/6539791>
916void rdar_6539791(CFMutableDictionaryRef y, void* key, void* val_key) {
917  CFMutableDictionaryRef x = CFDictionaryCreateMutable(kCFAllocatorDefault, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
918  CFDictionaryAddValue(y, key, x);
919  CFRelease(x); // the dictionary keeps a reference, so the object isn't deallocated yet
920  signed z = 1;
921  CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z);
922  if (value) {
923    CFDictionaryAddValue(x, val_key, value); // no-warning
924    CFRelease(value);
925    CFDictionaryAddValue(y, val_key, value); // no-warning
926  }
927}
928
929// <rdar://problem/6560661>
930// Same issue, except with "AppendValue" functions.
931void rdar_6560661(CFMutableArrayRef x) {
932  signed z = 1;
933  CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z);
934  // CFArrayAppendValue keeps a reference to value.
935  CFArrayAppendValue(x, value);
936  CFRelease(value);
937  CFRetain(value);
938  CFRelease(value); // no-warning
939}
940
941// <rdar://problem/7152619>
942// Same issue, excwept with "CFAttributeStringSetAttribute".
943void rdar_7152619(CFStringRef str) {
944  CFAttributedStringRef string = CFAttributedStringCreate(kCFAllocatorDefault, str, 0);
945  CFMutableAttributedStringRef attrString = CFAttributedStringCreateMutableCopy(kCFAllocatorDefault, 100, string);
946  CFRelease(string);
947  NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
948  CFAttributedStringSetAttribute(attrString, CFRangeMake(0, 1), str, number);
949  [number release];
950  [number retain];
951  CFRelease(attrString);  
952}
953
954//===----------------------------------------------------------------------===//
955// Test of handling CGGradientXXX functions.
956//===----------------------------------------------------------------------===//
957
958void rdar_7184450(CGContextRef myContext, CGFloat x, CGPoint myStartPoint,
959                  CGPoint myEndPoint) {
960  size_t num_locations = 6;
961  CGFloat locations[6] = { 0.0, 0.265, 0.28, 0.31, 0.36, 1.0 };
962  CGFloat components[28] = { 239.0/256.0, 167.0/256.0, 170.0/256.0,
963     x,  // Start color
964    207.0/255.0, 39.0/255.0, 39.0/255.0, x,
965    147.0/255.0, 21.0/255.0, 22.0/255.0, x,
966    175.0/255.0, 175.0/255.0, 175.0/255.0, x,
967    255.0/255.0,255.0/255.0, 255.0/255.0, x,
968    255.0/255.0,255.0/255.0, 255.0/255.0, x
969  }; // End color
970  
971  CGGradientRef myGradient =
972    CGGradientCreateWithColorComponents(CGColorSpaceCreateDeviceRGB(), // expected-warning{{leak}}
973      components, locations, num_locations);
974
975  CGContextDrawLinearGradient(myContext, myGradient, myStartPoint, myEndPoint,
976                              0);
977  CGGradientRelease(myGradient);
978}
979
980void rdar_7184450_pos(CGContextRef myContext, CGFloat x, CGPoint myStartPoint,
981                  CGPoint myEndPoint) {
982  size_t num_locations = 6;
983  CGFloat locations[6] = { 0.0, 0.265, 0.28, 0.31, 0.36, 1.0 };
984  CGFloat components[28] = { 239.0/256.0, 167.0/256.0, 170.0/256.0,
985     x,  // Start color
986    207.0/255.0, 39.0/255.0, 39.0/255.0, x,
987    147.0/255.0, 21.0/255.0, 22.0/255.0, x,
988    175.0/255.0, 175.0/255.0, 175.0/255.0, x,
989    255.0/255.0,255.0/255.0, 255.0/255.0, x,
990    255.0/255.0,255.0/255.0, 255.0/255.0, x
991  }; // End color
992  
993  CGGradientRef myGradient =
994   CGGradientCreateWithColorComponents(CGColorSpaceCreateDeviceRGB(), components, locations, num_locations); // expected-warning 2 {{leak}}
995
996  CGContextDrawLinearGradient(myContext, myGradient, myStartPoint, myEndPoint,
997                              0);
998}
999
1000//===----------------------------------------------------------------------===//
1001// <rdar://problem/7299394> clang false positive: retained instance passed to
1002//                          thread in pthread_create marked as leak
1003//
1004// Until we have full IPA, the analyzer should stop tracking the reference
1005// count of objects passed to pthread_create.
1006//
1007//===----------------------------------------------------------------------===//
1008
1009struct _opaque_pthread_t {};
1010struct _opaque_pthread_attr_t {};
1011typedef struct _opaque_pthread_t *__darwin_pthread_t;
1012typedef struct _opaque_pthread_attr_t __darwin_pthread_attr_t;
1013typedef __darwin_pthread_t pthread_t;
1014typedef __darwin_pthread_attr_t pthread_attr_t;
1015
1016int pthread_create(pthread_t * restrict, const pthread_attr_t * restrict,
1017                   void *(*)(void *), void * restrict);
1018
1019void *rdar_7299394_start_routine(void *p) {
1020  [((id) p) release];
1021  return 0;
1022}
1023void rdar_7299394(pthread_attr_t *attr, pthread_t *thread, void *args) {
1024  NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1025  pthread_create(thread, attr, rdar_7299394_start_routine, number);
1026}
1027void rdar_7299394_positive(pthread_attr_t *attr, pthread_t *thread) {
1028  NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1029}
1030
1031//===----------------------------------------------------------------------===//
1032// <rdar://problem/7283567> False leak associated with call to 
1033//                          CVPixelBufferCreateWithBytes ()
1034//
1035// According to the Core Video Reference (ADC), CVPixelBufferCreateWithBytes and
1036// CVPixelBufferCreateWithPlanarBytes can release (via a callback) the
1037// pixel buffer object.  These test cases show how the analyzer stops tracking
1038// the reference count for the objects passed for this argument.  This
1039// could be made smarter.
1040//===----------------------------------------------------------------------===//
1041
1042typedef int int32_t;
1043typedef UInt32 FourCharCode;
1044typedef FourCharCode OSType;
1045typedef uint64_t CVOptionFlags;
1046typedef int32_t CVReturn;
1047typedef struct __CVBuffer *CVBufferRef;
1048typedef CVBufferRef CVImageBufferRef;
1049typedef CVImageBufferRef CVPixelBufferRef;
1050typedef void (*CVPixelBufferReleaseBytesCallback)( void *releaseRefCon, const void *baseAddress );
1051
1052extern CVReturn CVPixelBufferCreateWithBytes(CFAllocatorRef allocator,
1053            size_t width,
1054            size_t height,
1055            OSType pixelFormatType,
1056            void *baseAddress,
1057            size_t bytesPerRow,
1058            CVPixelBufferReleaseBytesCallback releaseCallback,
1059            void *releaseRefCon,
1060            CFDictionaryRef pixelBufferAttributes,
1061                   CVPixelBufferRef *pixelBufferOut) ;
1062
1063typedef void (*CVPixelBufferReleasePlanarBytesCallback)( void *releaseRefCon, const void *dataPtr, size_t dataSize, size_t numberOfPlanes, const void *planeAddresses[] );
1064
1065extern CVReturn CVPixelBufferCreateWithPlanarBytes(CFAllocatorRef allocator,
1066        size_t width,
1067        size_t height,
1068        OSType pixelFormatType,
1069        void *dataPtr,
1070        size_t dataSize,
1071        size_t numberOfPlanes,
1072        void *planeBaseAddress[],
1073        size_t planeWidth[],
1074        size_t planeHeight[],
1075        size_t planeBytesPerRow[],
1076        CVPixelBufferReleasePlanarBytesCallback releaseCallback,
1077        void *releaseRefCon,
1078        CFDictionaryRef pixelBufferAttributes,
1079        CVPixelBufferRef *pixelBufferOut) ;
1080
1081extern CVReturn CVPixelBufferCreateWithBytes(CFAllocatorRef allocator,
1082            size_t width,
1083            size_t height,
1084            OSType pixelFormatType,
1085            void *baseAddress,
1086            size_t bytesPerRow,
1087            CVPixelBufferReleaseBytesCallback releaseCallback,
1088            void *releaseRefCon,
1089            CFDictionaryRef pixelBufferAttributes,
1090                   CVPixelBufferRef *pixelBufferOut) ;
1091
1092CVReturn rdar_7283567(CFAllocatorRef allocator, size_t width, size_t height,
1093                      OSType pixelFormatType, void *baseAddress,
1094                      size_t bytesPerRow,
1095                      CVPixelBufferReleaseBytesCallback releaseCallback,
1096                      CFDictionaryRef pixelBufferAttributes,
1097                      CVPixelBufferRef *pixelBufferOut) {
1098
1099  // For the allocated object, it doesn't really matter what type it is
1100  // for the purpose of this test.  All we want to show is that
1101  // this is freed later by the callback.
1102  NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1103  
1104  return CVPixelBufferCreateWithBytes(allocator, width, height, pixelFormatType,
1105                                baseAddress, bytesPerRow, releaseCallback,
1106                                number, // potentially released by callback
1107                                pixelBufferAttributes, pixelBufferOut) ;
1108}
1109
1110CVReturn rdar_7283567_2(CFAllocatorRef allocator, size_t width, size_t height,
1111        OSType pixelFormatType, void *dataPtr, size_t dataSize,
1112        size_t numberOfPlanes, void *planeBaseAddress[],
1113        size_t planeWidth[], size_t planeHeight[], size_t planeBytesPerRow[],
1114        CVPixelBufferReleasePlanarBytesCallback releaseCallback,
1115        CFDictionaryRef pixelBufferAttributes,
1116        CVPixelBufferRef *pixelBufferOut) {
1117    
1118    // For the allocated object, it doesn't really matter what type it is
1119    // for the purpose of this test.  All we want to show is that
1120    // this is freed later by the callback.
1121    NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1122
1123    return CVPixelBufferCreateWithPlanarBytes(allocator,
1124              width, height, pixelFormatType, dataPtr, dataSize,
1125              numberOfPlanes, planeBaseAddress, planeWidth,
1126              planeHeight, planeBytesPerRow, releaseCallback,
1127              number, // potentially released by callback
1128              pixelBufferAttributes, pixelBufferOut) ;
1129}
1130
1131//===----------------------------------------------------------------------===//
1132// <rdar://problem/7358899> False leak associated with 
1133//  CGBitmapContextCreateWithData
1134//===----------------------------------------------------------------------===//
1135typedef uint32_t CGBitmapInfo;
1136typedef void (*CGBitmapContextReleaseDataCallback)(void *releaseInfo, void *data);
1137    
1138CGContextRef CGBitmapContextCreateWithData(void *data,
1139    size_t width, size_t height, size_t bitsPerComponent,
1140    size_t bytesPerRow, CGColorSpaceRef space, CGBitmapInfo bitmapInfo,
1141    CGBitmapContextReleaseDataCallback releaseCallback, void *releaseInfo);
1142
1143void rdar_7358899(void *data,
1144      size_t width, size_t height, size_t bitsPerComponent,
1145      size_t bytesPerRow, CGColorSpaceRef space, CGBitmapInfo bitmapInfo,
1146      CGBitmapContextReleaseDataCallback releaseCallback) {
1147
1148    // For the allocated object, it doesn't really matter what type it is
1149    // for the purpose of this test.  All we want to show is that
1150    // this is freed later by the callback.
1151    NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1152
1153  CGBitmapContextCreateWithData(data, width, height, bitsPerComponent, // expected-warning{{leak}}
1154    bytesPerRow, space, bitmapInfo, releaseCallback, number);
1155}
1156
1157//===----------------------------------------------------------------------===//
1158// <rdar://problem/7265711> allow 'new', 'copy', 'alloc', 'init' prefix to
1159//  start before '_' when determining Cocoa fundamental rule
1160//
1161// Previously the retain/release checker just skipped prefixes before the
1162// first '_' entirely.  Now the checker honors the prefix if it results in a
1163// recognizable naming convention (e.g., 'new', 'init').
1164//===----------------------------------------------------------------------===//
1165
1166@interface RDar7265711 {}
1167- (id) new_stuff;
1168@end
1169
1170void rdar7265711_a(RDar7265711 *x) {
1171  id y = [x new_stuff]; // expected-warning{{leak}}
1172}
1173
1174void rdar7265711_b(RDar7265711 *x) {
1175  id y = [x new_stuff]; // no-warning
1176  [y release];
1177}
1178
1179//===----------------------------------------------------------------------===//
1180// <rdar://problem/7306898> clang thinks [NSCursor dragCopyCursor] returns a
1181//                          retained reference
1182//===----------------------------------------------------------------------===//
1183
1184@interface NSCursor : NSObject
1185+ (NSCursor *)dragCopyCursor;
1186@end
1187
1188void rdar7306898(void) {
1189  // 'dragCopyCursor' does not follow Cocoa's fundamental rule.  It is a noun, not an sentence
1190  // implying a 'copy' of something.
1191  NSCursor *c =  [NSCursor dragCopyCursor]; // no-warning
1192  NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1193}
1194
1195//===----------------------------------------------------------------------===//
1196// <rdar://problem/7252064> sending 'release', 'retain', etc. to a Class
1197// directly is not likely what the user intended
1198//===----------------------------------------------------------------------===//
1199
1200@interface RDar7252064 : NSObject @end
1201void rdar7252064(void) {
1202  [RDar7252064 release]; // expected-warning{{The 'release' message should be sent to instances of class 'RDar7252064' and not the class directly}}
1203  [RDar7252064 retain]; // expected-warning{{The 'retain' message should be sent to instances of class 'RDar7252064' and not the class directly}}
1204  [RDar7252064 autorelease]; // expected-warning{{The 'autorelease' message should be sent to instances of class 'RDar7252064' and not the class directly}}
1205  [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}}
1206}
1207
1208//===----------------------------------------------------------------------===//
1209// Tests of ownership attributes.
1210//===----------------------------------------------------------------------===//
1211
1212typedef NSString* MyStringTy;
1213
1214@protocol FooP;
1215
1216@interface TestOwnershipAttr : NSObject
1217- (NSString*) returnsAnOwnedString  NS_RETURNS_RETAINED; // no-warning
1218- (NSString*) returnsAnOwnedCFString  CF_RETURNS_RETAINED; // no-warning
1219- (MyStringTy) returnsAnOwnedTypedString NS_RETURNS_RETAINED; // no-warning
1220- (NSString*) newString NS_RETURNS_NOT_RETAINED; // no-warning
1221- (NSString*) newStringNoAttr;
1222- (int) returnsAnOwnedInt NS_RETURNS_RETAINED; // expected-warning{{'ns_returns_retained' attribute only applies to methods that return an Objective-C object}}
1223- (id) pseudoInit NS_CONSUMES_SELF NS_RETURNS_RETAINED;
1224+ (void) consume:(id) NS_CONSUMED x;
1225+ (void) consume2:(id) CF_CONSUMED x;
1226@end
1227
1228static int ownership_attribute_doesnt_go_here NS_RETURNS_RETAINED; // expected-warning{{'ns_returns_retained' attribute only applies to functions and methods}}
1229
1230void test_attr_1(TestOwnershipAttr *X) {
1231  NSString *str = [X returnsAnOwnedString]; // expected-warning{{leak}}
1232}
1233
1234void test_attr_1b(TestOwnershipAttr *X) {
1235  NSString *str = [X returnsAnOwnedCFString]; // expected-warning{{leak}}
1236}
1237
1238void test_attr1c(TestOwnershipAttr *X) {
1239  NSString *str = [X newString]; // no-warning
1240  NSString *str2 = [X newStringNoAttr]; // expected-warning{{leak}}
1241}
1242
1243void testattr2_a() {
1244  TestOwnershipAttr *x = [TestOwnershipAttr alloc]; // expected-warning{{leak}}
1245}
1246
1247void testattr2_b() {
1248  TestOwnershipAttr *x = [[TestOwnershipAttr alloc] pseudoInit];  // expected-warning{{leak}}
1249}
1250
1251void testattr2_c() {
1252  TestOwnershipAttr *x = [[TestOwnershipAttr alloc] pseudoInit]; // no-warning
1253  [x release];
1254}
1255
1256void testattr3() {
1257  TestOwnershipAttr *x = [TestOwnershipAttr alloc]; // no-warning
1258  [TestOwnershipAttr consume:x];
1259  TestOwnershipAttr *y = [TestOwnershipAttr alloc]; // no-warning
1260  [TestOwnershipAttr consume2:y];
1261}
1262
1263void consume_ns(id NS_CONSUMED x);
1264void consume_cf(id CF_CONSUMED x);
1265
1266void testattr4() {
1267  TestOwnershipAttr *x = [TestOwnershipAttr alloc]; // no-warning
1268  consume_ns(x);
1269  TestOwnershipAttr *y = [TestOwnershipAttr alloc]; // no-warning
1270  consume_cf(y);
1271}
1272
1273
1274@interface MyClassTestCFAttr : NSObject {}
1275- (NSDate*) returnsCFRetained CF_RETURNS_RETAINED;
1276- (CFDateRef) returnsCFRetainedAsCF CF_RETURNS_RETAINED;
1277- (CFDateRef) newCFRetainedAsCF CF_RETURNS_NOT_RETAINED;
1278- (CFDateRef) newCFRetainedAsCFNoAttr;
1279- (NSDate*) alsoReturnsRetained;
1280- (CFDateRef) alsoReturnsRetainedAsCF;
1281- (NSDate*) returnsNSRetained NS_RETURNS_RETAINED;
1282@end
1283
1284CF_RETURNS_RETAINED
1285CFDateRef returnsRetainedCFDate()  {
1286  return CFDateCreate(0, CFAbsoluteTimeGetCurrent());
1287}
1288
1289@implementation MyClassTestCFAttr
1290- (NSDate*) returnsCFRetained {
1291  return (NSDate*) returnsRetainedCFDate(); // No leak.
1292}
1293
1294- (CFDateRef) returnsCFRetainedAsCF {
1295  return returnsRetainedCFDate(); // No leak.
1296}
1297
1298- (CFDateRef) newCFRetainedAsCF {
1299  return (CFDateRef)[(id)[self returnsCFRetainedAsCF] autorelease];
1300}
1301
1302- (CFDateRef) newCFRetainedAsCFNoAttr {
1303  return (CFDateRef)[(id)[self returnsCFRetainedAsCF] autorelease]; // expected-warning{{Object with +0 retain counts returned to caller where a +1 (owning) retain count is expected}}
1304}
1305
1306- (NSDate*) alsoReturnsRetained {
1307  return (NSDate*) returnsRetainedCFDate(); // expected-warning{{leak}}
1308}
1309
1310- (CFDateRef) alsoReturnsRetainedAsCF {
1311  return returnsRetainedCFDate(); // expected-warning{{leak}}
1312}
1313
1314
1315- (NSDate*) returnsNSRetained {
1316  return (NSDate*) returnsRetainedCFDate(); // no-warning
1317}
1318@end
1319
1320//===----------------------------------------------------------------------===//
1321// Test that leaks post-dominated by "panic" functions are not reported.
1322//
1323// <rdar://problem/5905851> do not report a leak when post-dominated by a call
1324// to a noreturn or panic function
1325//===----------------------------------------------------------------------===//
1326
1327void panic() __attribute__((noreturn));
1328void panic_not_in_hardcoded_list() __attribute__((noreturn));
1329
1330void test_panic_negative() {
1331  signed z = 1;
1332  CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z);  // expected-warning{{leak}}
1333}
1334
1335void test_panic_positive() {
1336  signed z = 1;
1337  CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // no-warning
1338  panic();
1339}
1340
1341void test_panic_neg_2(int x) {
1342  signed z = 1;
1343  CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // expected-warning{{leak}}
1344  if (x)
1345    panic();
1346}
1347
1348void test_panic_pos_2(int x) {
1349  signed z = 1;
1350  CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // no-warning
1351  if (x)
1352    panic();
1353  if (!x) {
1354    // This showed up in <rdar://problem/7796563>, where we silently missed checking
1355    // the function type for noreturn.  "panic()" is a hard-coded known panic function
1356    // that isn't always noreturn.
1357    panic_not_in_hardcoded_list();
1358  }
1359}
1360
1361//===----------------------------------------------------------------------===//
1362// Test uses of blocks (closures)
1363//===----------------------------------------------------------------------===//
1364
1365void test_blocks_1_pos(void) {
1366  NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1367  ^{}();
1368}
1369
1370void test_blocks_1_indirect_release(void) {
1371  NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1372  ^{ [number release]; }();
1373}
1374
1375void test_blocks_1_indirect_retain(void) {
1376  // Eventually this should be reported as a leak.
1377  NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1378  ^{ [number retain]; }();
1379}
1380
1381void test_blocks_1_indirect_release_via_call(void) {
1382  NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1383  ^(NSObject *o){ [o release]; }(number);
1384}
1385
1386void test_blocks_1_indirect_retain_via_call(void) {
1387  // Eventually this should be reported as a leak.
1388  NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1389  ^(NSObject *o){ [o retain]; }(number);
1390}
1391
1392//===--------------------------------------------------------------------===//
1393// Test sending message to super that returns an object alias.  Previously
1394// this caused a crash in the analyzer.
1395//===--------------------------------------------------------------------===//
1396
1397@interface Rdar8015556 : NSObject {} @end
1398@implementation Rdar8015556
1399- (id)retain {
1400  return [super retain];
1401}
1402@end
1403
1404// <rdar://problem/8272168> - Correcly handle Class<...> in Cocoa Conventions
1405// detector.
1406
1407@protocol Prot_R8272168 @end
1408Class <Prot_R8272168> GetAClassThatImplementsProt_R8272168();
1409void r8272168() {
1410  GetAClassThatImplementsProt_R8272168();
1411}
1412
1413// Test case for <rdar://problem/8356342>, which in the past triggered
1414// a false positive.
1415@interface RDar8356342
1416- (NSDate*) rdar8356342:(NSDate *)inValue;
1417@end
1418
1419@implementation RDar8356342
1420- (NSDate*) rdar8356342:(NSDate*)inValue {
1421  NSDate *outValue = inValue;
1422  if (outValue == 0)
1423    outValue = [[NSDate alloc] init]; // no-warning
1424
1425  if (outValue != inValue)
1426    [outValue autorelease];
1427
1428  return outValue;
1429}
1430@end
1431
1432// <rdar://problem/8724287> - This test case previously crashed because
1433// of a bug in BugReporter.
1434extern const void *CFDictionaryGetValue(CFDictionaryRef theDict, const void *key);
1435typedef struct __CFError * CFErrorRef;
1436extern const CFStringRef kCFErrorUnderlyingErrorKey;
1437extern CFDictionaryRef CFErrorCopyUserInfo(CFErrorRef err);
1438
1439static void rdar_8724287(CFErrorRef error)
1440{
1441    CFErrorRef error_to_dump;
1442
1443    error_to_dump = error;
1444    while (error_to_dump != ((void*)0)) {
1445        CFDictionaryRef info;
1446
1447        info = CFErrorCopyUserInfo(error_to_dump); // expected-warning{{Potential leak of an object allocated on line 1447 and stored into 'info'}}
1448
1449        if (info != ((void*)0)) {
1450        }
1451
1452        error_to_dump = (CFErrorRef) CFDictionaryGetValue(info, kCFErrorUnderlyingErrorKey);
1453    }
1454}
1455
1456