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