retain-release.m revision 09ca9ef5f92cf4375a19bf7a80d571779c9f370f
1// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -analyze -analyzer-checker=core,osx.coreFoundation.CFRetainRelease,osx.cocoa.ClassRelease,osx.cocoa.RetainCount -analyzer-store=region -fblocks -verify %s
2// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -analyze -analyzer-checker=core,osx.coreFoundation.CFRetainRelease,osx.cocoa.ClassRelease,osx.cocoa.RetainCount -analyzer-store=region -fblocks -verify -x objective-c++ %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
656- (void)radar10102244 {
657 NSMutableDictionary *dict = [[NSMutableDictionary dictionaryWithCapacity:4] retain]; // expected-warning{{leak}} 
658 if (window) 
659   NSLog(@"%@", window);    
660}
661@end
662
663//===----------------------------------------------------------------------===//
664// <rdar://problem/6257780> clang checker fails to catch use-after-release
665//===----------------------------------------------------------------------===//
666                                 
667int rdar_6257780_Case1() {
668  NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
669  NSArray *array = [NSArray array];
670  [array release]; // expected-warning{{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
671  [pool drain];
672  return 0;
673}
674
675//===----------------------------------------------------------------------===//
676// <rdar://problem/6866843> Checker should understand new/setObject:/release constructs
677//===----------------------------------------------------------------------===//
678
679void rdar_6866843() {
680 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
681 NSMutableDictionary* dictionary = [[NSMutableDictionary alloc] init];
682 NSArray* array = [[NSArray alloc] init];
683 [dictionary setObject:array forKey:@"key"];
684 [array release];
685 // Using 'array' here should be fine
686 NSLog(@"array = %@\n", array); // no-warning
687 // Now the array is released
688 [dictionary release];
689 [pool drain];
690}
691
692
693//===----------------------------------------------------------------------===//
694// <rdar://problem/6877235> Classes typedef-ed to CF objects should get the same treatment as CF objects
695//===----------------------------------------------------------------------===//
696
697typedef CFTypeRef OtherRef;
698
699@interface RDar6877235 : NSObject {}
700- (CFTypeRef)_copyCFTypeRef;
701- (OtherRef)_copyOtherRef;
702@end
703
704@implementation RDar6877235
705- (CFTypeRef)_copyCFTypeRef {
706  return [[NSString alloc] init]; // no-warning
707}
708- (OtherRef)_copyOtherRef {
709  return [[NSString alloc] init]; // no-warning
710}
711@end
712
713//===----------------------------------------------------------------------===//
714//<rdar://problem/6320065> false positive - init method returns an object
715// owned by caller
716//===----------------------------------------------------------------------===//
717
718@interface RDar6320065 : NSObject {
719  NSString *_foo;
720}
721- (id)initReturningNewClass;
722- (id)_initReturningNewClassBad;
723- (id)initReturningNewClassBad2;
724@end
725
726@interface RDar6320065Subclass : RDar6320065
727@end
728
729@implementation RDar6320065
730- (id)initReturningNewClass {
731  [self release];
732  self = [[RDar6320065Subclass alloc] init]; // no-warning
733  return self;
734}
735- (id)_initReturningNewClassBad {
736  [self release];
737  [[RDar6320065Subclass alloc] init]; // expected-warning {{leak}}
738  return self;
739}
740- (id)initReturningNewClassBad2 {
741  [self release];
742  self = [[RDar6320065Subclass alloc] init];
743  return [self autorelease]; // expected-warning{{Object with a +0 retain count returned to caller where a +1 (owning) retain count is expected}}
744}
745
746@end
747
748@implementation RDar6320065Subclass
749@end
750
751int RDar6320065_test() {
752  RDar6320065 *test = [[RDar6320065 alloc] init]; // no-warning
753  [test release];
754  return 0;
755}
756
757//===----------------------------------------------------------------------===//
758// <rdar://problem/7129086> -awakeAfterUsingCoder: returns an owned object 
759//  and claims the receiver
760//===----------------------------------------------------------------------===//
761
762@interface RDar7129086 : NSObject {} @end
763@implementation RDar7129086
764- (id)awakeAfterUsingCoder:(NSCoder *)aDecoder {
765  [self release]; // no-warning
766  return [NSString alloc];  // no-warning
767}
768@end
769
770//===----------------------------------------------------------------------===//
771// <rdar://problem/6859457> [NSData dataWithBytesNoCopy] does not return a
772//  retained object
773//===----------------------------------------------------------------------===//
774
775@interface RDar6859457 : NSObject {}
776- (NSString*) NoCopyString;
777- (NSString*) noCopyString;
778@end
779
780@implementation RDar6859457 
781- (NSString*) NoCopyString { return [[NSString alloc] init]; } // expected-warning{{leak}}
782- (NSString*) noCopyString { return [[NSString alloc] init]; } // expected-warning{{leak}}
783@end
784
785void test_RDar6859457(RDar6859457 *x, void *bytes, NSUInteger dataLength) {
786  [x NoCopyString]; // no-warning
787  [x noCopyString]; // no-warning
788  [NSData dataWithBytesNoCopy:bytes length:dataLength];  // no-warning
789  [NSData dataWithBytesNoCopy:bytes length:dataLength freeWhenDone:1]; // no-warning
790}
791
792//===----------------------------------------------------------------------===//
793// PR 4230 - an autorelease pool is not necessarily leaked during a premature
794//  return
795//===----------------------------------------------------------------------===//
796
797static void PR4230(void)
798{
799  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // no-warning
800  NSString *object = [[[NSString alloc] init] autorelease]; // no-warning
801  return;
802}
803
804//===----------------------------------------------------------------------===//
805// Method name that has a null IdentifierInfo* for its first selector slot.
806// This test just makes sure that we handle it.
807//===----------------------------------------------------------------------===//
808
809@interface TestNullIdentifier
810@end
811
812@implementation TestNullIdentifier
813+ (id):(int)x, ... {
814  return [[NSString alloc] init]; // expected-warning{{leak}}
815}
816@end
817
818//===----------------------------------------------------------------------===//
819// <rdar://problem/6893565> don't flag leaks for return types that cannot be 
820//                          determined to be CF types
821//===----------------------------------------------------------------------===//
822
823// We don't know if 'struct s6893565' represents a Core Foundation type, so
824// we shouldn't emit an error here.
825typedef struct s6893565* TD6893565;
826
827@interface RDar6893565 {}
828-(TD6893565)newThing;
829@end
830
831@implementation RDar6893565
832-(TD6893565)newThing {  
833  return (TD6893565) [[NSString alloc] init]; // no-warning
834}
835@end
836
837//===----------------------------------------------------------------------===//
838// <rdar://problem/6902710> clang: false positives w/QC and CoreImage methods
839//===----------------------------------------------------------------------===//
840
841void rdar6902710(QCView *view, QCRenderer *renderer, CIContext *context,
842                 NSString *str, CIImage *img, CGRect rect,
843                 CIFormat form, CGColorSpaceRef cs) {
844  [view createSnapshotImageOfType:str]; // expected-warning{{leak}}
845  [renderer createSnapshotImageOfType:str]; // expected-warning{{leak}}
846  [context createCGImage:img fromRect:rect]; // expected-warning{{leak}}
847  [context createCGImage:img fromRect:rect format:form colorSpace:cs]; // expected-warning{{leak}}
848}
849
850//===----------------------------------------------------------------------===//
851// <rdar://problem/6945561> -[CIContext createCGLayerWithSize:info:]
852//                           misinterpreted by clang scan-build
853//===----------------------------------------------------------------------===//
854
855void rdar6945561(CIContext *context, CGSize size, CFDictionaryRef d) {
856  [context createCGLayerWithSize:size info:d]; // expected-warning{{leak}}
857}
858
859//===----------------------------------------------------------------------===//
860// <rdar://problem/6961230> add knowledge of IOKit functions to retain/release 
861//                          checker
862//===----------------------------------------------------------------------===//
863
864void IOBSDNameMatching_wrapper(mach_port_t masterPort, uint32_t options,  const char * bsdName) {  
865  IOBSDNameMatching(masterPort, options, bsdName); // expected-warning{{leak}}
866}
867
868void IOServiceMatching_wrapper(const char * name) {
869  IOServiceMatching(name); // expected-warning{{leak}}
870}
871
872void IOServiceNameMatching_wrapper(const char * name) {
873  IOServiceNameMatching(name); // expected-warning{{leak}}
874}
875
876CF_RETURNS_RETAINED CFDictionaryRef CreateDict();
877
878void IOServiceAddNotification_wrapper(mach_port_t masterPort, const io_name_t notificationType,
879  mach_port_t wakePort, uintptr_t reference, io_iterator_t * notification ) {
880
881  CFDictionaryRef matching = CreateDict();
882  CFRelease(matching);
883  IOServiceAddNotification(masterPort, notificationType, matching, // expected-warning{{used after it is released}} expected-warning{{deprecated}}
884                           wakePort, reference, notification);
885}
886
887void IORegistryEntryIDMatching_wrapper(uint64_t entryID ) {
888  IORegistryEntryIDMatching(entryID); // expected-warning{{leak}}
889}
890
891void IOOpenFirmwarePathMatching_wrapper(mach_port_t masterPort, uint32_t options,
892                                        const char * path) {
893  IOOpenFirmwarePathMatching(masterPort, options, path); // expected-warning{{leak}}
894}
895
896void IOServiceGetMatchingService_wrapper(mach_port_t masterPort) {
897  CFDictionaryRef matching = CreateDict();
898  IOServiceGetMatchingService(masterPort, matching);
899  CFRelease(matching); // expected-warning{{used after it is released}}
900}
901
902void IOServiceGetMatchingServices_wrapper(mach_port_t masterPort, io_iterator_t *existing) {
903  CFDictionaryRef matching = CreateDict();
904  IOServiceGetMatchingServices(masterPort, matching, existing);
905  CFRelease(matching); // expected-warning{{used after it is released}}
906}
907
908void IOServiceAddMatchingNotification_wrapper(IONotificationPortRef notifyPort, const io_name_t notificationType, 
909  IOServiceMatchingCallback callback, void * refCon, io_iterator_t * notification) {
910    
911  CFDictionaryRef matching = CreateDict();
912  IOServiceAddMatchingNotification(notifyPort, notificationType, matching, callback, refCon, notification);
913  CFRelease(matching); // expected-warning{{used after it is released}}
914}
915
916//===----------------------------------------------------------------------===//
917// Test of handling objects whose references "escape" to containers.
918//===----------------------------------------------------------------------===//
919
920void CFDictionaryAddValue(CFMutableDictionaryRef, void *, void *);
921
922// <rdar://problem/6539791>
923void rdar_6539791(CFMutableDictionaryRef y, void* key, void* val_key) {
924  CFMutableDictionaryRef x = CFDictionaryCreateMutable(kCFAllocatorDefault, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
925  CFDictionaryAddValue(y, key, x);
926  CFRelease(x); // the dictionary keeps a reference, so the object isn't deallocated yet
927  signed z = 1;
928  CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z);
929  if (value) {
930    CFDictionaryAddValue(x, val_key, (void*)value); // no-warning
931    CFRelease(value);
932    CFDictionaryAddValue(y, val_key, (void*)value); // no-warning
933  }
934}
935
936// <rdar://problem/6560661>
937// Same issue, except with "AppendValue" functions.
938void rdar_6560661(CFMutableArrayRef x) {
939  signed z = 1;
940  CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z);
941  // CFArrayAppendValue keeps a reference to value.
942  CFArrayAppendValue(x, value);
943  CFRelease(value);
944  CFRetain(value);
945  CFRelease(value); // no-warning
946}
947
948// <rdar://problem/7152619>
949// Same issue, excwept with "CFAttributeStringSetAttribute".
950void rdar_7152619(CFStringRef str) {
951  CFAttributedStringRef string = CFAttributedStringCreate(kCFAllocatorDefault, str, 0);
952  CFMutableAttributedStringRef attrString = CFAttributedStringCreateMutableCopy(kCFAllocatorDefault, 100, string);
953  CFRelease(string);
954  NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
955  CFAttributedStringSetAttribute(attrString, CFRangeMake(0, 1), str, number);
956  [number release];
957  [number retain];
958  CFRelease(attrString);  
959}
960
961//===----------------------------------------------------------------------===//
962// Test of handling CGGradientXXX functions.
963//===----------------------------------------------------------------------===//
964
965void rdar_7184450(CGContextRef myContext, CGFloat x, CGPoint myStartPoint,
966                  CGPoint myEndPoint) {
967  size_t num_locations = 6;
968  CGFloat locations[6] = { 0.0, 0.265, 0.28, 0.31, 0.36, 1.0 };
969  CGFloat components[28] = { 239.0/256.0, 167.0/256.0, 170.0/256.0,
970     x,  // Start color
971    207.0/255.0, 39.0/255.0, 39.0/255.0, x,
972    147.0/255.0, 21.0/255.0, 22.0/255.0, x,
973    175.0/255.0, 175.0/255.0, 175.0/255.0, x,
974    255.0/255.0,255.0/255.0, 255.0/255.0, x,
975    255.0/255.0,255.0/255.0, 255.0/255.0, x
976  }; // End color
977  
978  CGGradientRef myGradient =
979    CGGradientCreateWithColorComponents(CGColorSpaceCreateDeviceRGB(), // expected-warning{{leak}}
980      components, locations, num_locations);
981
982  CGContextDrawLinearGradient(myContext, myGradient, myStartPoint, myEndPoint,
983                              0);
984  CGGradientRelease(myGradient);
985}
986
987void rdar_7184450_pos(CGContextRef myContext, CGFloat x, CGPoint myStartPoint,
988                  CGPoint myEndPoint) {
989  size_t num_locations = 6;
990  CGFloat locations[6] = { 0.0, 0.265, 0.28, 0.31, 0.36, 1.0 };
991  CGFloat components[28] = { 239.0/256.0, 167.0/256.0, 170.0/256.0,
992     x,  // Start color
993    207.0/255.0, 39.0/255.0, 39.0/255.0, x,
994    147.0/255.0, 21.0/255.0, 22.0/255.0, x,
995    175.0/255.0, 175.0/255.0, 175.0/255.0, x,
996    255.0/255.0,255.0/255.0, 255.0/255.0, x,
997    255.0/255.0,255.0/255.0, 255.0/255.0, x
998  }; // End color
999  
1000  CGGradientRef myGradient =
1001   CGGradientCreateWithColorComponents(CGColorSpaceCreateDeviceRGB(), components, locations, num_locations); // expected-warning 2 {{leak}}
1002
1003  CGContextDrawLinearGradient(myContext, myGradient, myStartPoint, myEndPoint,
1004                              0);
1005}
1006
1007//===----------------------------------------------------------------------===//
1008// <rdar://problem/7299394> clang false positive: retained instance passed to
1009//                          thread in pthread_create marked as leak
1010//
1011// Until we have full IPA, the analyzer should stop tracking the reference
1012// count of objects passed to pthread_create.
1013//
1014//===----------------------------------------------------------------------===//
1015
1016struct _opaque_pthread_t {};
1017struct _opaque_pthread_attr_t {};
1018typedef struct _opaque_pthread_t *__darwin_pthread_t;
1019typedef struct _opaque_pthread_attr_t __darwin_pthread_attr_t;
1020typedef __darwin_pthread_t pthread_t;
1021typedef __darwin_pthread_attr_t pthread_attr_t;
1022
1023int pthread_create(pthread_t *, const pthread_attr_t *,
1024                   void *(*)(void *), void *);
1025
1026void *rdar_7299394_start_routine(void *p) {
1027  [((id) p) release];
1028  return 0;
1029}
1030void rdar_7299394(pthread_attr_t *attr, pthread_t *thread, void *args) {
1031  NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1032  pthread_create(thread, attr, rdar_7299394_start_routine, number);
1033}
1034void rdar_7299394_positive(pthread_attr_t *attr, pthread_t *thread) {
1035  NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1036}
1037
1038//===----------------------------------------------------------------------===//
1039// <rdar://problem/7283567> False leak associated with call to 
1040//                          CVPixelBufferCreateWithBytes ()
1041//
1042// According to the Core Video Reference (ADC), CVPixelBufferCreateWithBytes and
1043// CVPixelBufferCreateWithPlanarBytes can release (via a callback) the
1044// pixel buffer object.  These test cases show how the analyzer stops tracking
1045// the reference count for the objects passed for this argument.  This
1046// could be made smarter.
1047//===----------------------------------------------------------------------===//
1048
1049typedef int int32_t;
1050typedef UInt32 FourCharCode;
1051typedef FourCharCode OSType;
1052typedef uint64_t CVOptionFlags;
1053typedef int32_t CVReturn;
1054typedef struct __CVBuffer *CVBufferRef;
1055typedef CVBufferRef CVImageBufferRef;
1056typedef CVImageBufferRef CVPixelBufferRef;
1057typedef void (*CVPixelBufferReleaseBytesCallback)( void *releaseRefCon, const void *baseAddress );
1058
1059extern CVReturn CVPixelBufferCreateWithBytes(CFAllocatorRef allocator,
1060            size_t width,
1061            size_t height,
1062            OSType pixelFormatType,
1063            void *baseAddress,
1064            size_t bytesPerRow,
1065            CVPixelBufferReleaseBytesCallback releaseCallback,
1066            void *releaseRefCon,
1067            CFDictionaryRef pixelBufferAttributes,
1068                   CVPixelBufferRef *pixelBufferOut) ;
1069
1070typedef void (*CVPixelBufferReleasePlanarBytesCallback)( void *releaseRefCon, const void *dataPtr, size_t dataSize, size_t numberOfPlanes, const void *planeAddresses[] );
1071
1072extern CVReturn CVPixelBufferCreateWithPlanarBytes(CFAllocatorRef allocator,
1073        size_t width,
1074        size_t height,
1075        OSType pixelFormatType,
1076        void *dataPtr,
1077        size_t dataSize,
1078        size_t numberOfPlanes,
1079        void *planeBaseAddress[],
1080        size_t planeWidth[],
1081        size_t planeHeight[],
1082        size_t planeBytesPerRow[],
1083        CVPixelBufferReleasePlanarBytesCallback releaseCallback,
1084        void *releaseRefCon,
1085        CFDictionaryRef pixelBufferAttributes,
1086        CVPixelBufferRef *pixelBufferOut) ;
1087
1088extern CVReturn CVPixelBufferCreateWithBytes(CFAllocatorRef allocator,
1089            size_t width,
1090            size_t height,
1091            OSType pixelFormatType,
1092            void *baseAddress,
1093            size_t bytesPerRow,
1094            CVPixelBufferReleaseBytesCallback releaseCallback,
1095            void *releaseRefCon,
1096            CFDictionaryRef pixelBufferAttributes,
1097                   CVPixelBufferRef *pixelBufferOut) ;
1098
1099CVReturn rdar_7283567(CFAllocatorRef allocator, size_t width, size_t height,
1100                      OSType pixelFormatType, void *baseAddress,
1101                      size_t bytesPerRow,
1102                      CVPixelBufferReleaseBytesCallback releaseCallback,
1103                      CFDictionaryRef pixelBufferAttributes,
1104                      CVPixelBufferRef *pixelBufferOut) {
1105
1106  // For the allocated object, it doesn't really matter what type it is
1107  // for the purpose of this test.  All we want to show is that
1108  // this is freed later by the callback.
1109  NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1110  
1111  return CVPixelBufferCreateWithBytes(allocator, width, height, pixelFormatType,
1112                                baseAddress, bytesPerRow, releaseCallback,
1113                                number, // potentially released by callback
1114                                pixelBufferAttributes, pixelBufferOut) ;
1115}
1116
1117CVReturn rdar_7283567_2(CFAllocatorRef allocator, size_t width, size_t height,
1118        OSType pixelFormatType, void *dataPtr, size_t dataSize,
1119        size_t numberOfPlanes, void *planeBaseAddress[],
1120        size_t planeWidth[], size_t planeHeight[], size_t planeBytesPerRow[],
1121        CVPixelBufferReleasePlanarBytesCallback releaseCallback,
1122        CFDictionaryRef pixelBufferAttributes,
1123        CVPixelBufferRef *pixelBufferOut) {
1124    
1125    // For the allocated object, it doesn't really matter what type it is
1126    // for the purpose of this test.  All we want to show is that
1127    // this is freed later by the callback.
1128    NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1129
1130    return CVPixelBufferCreateWithPlanarBytes(allocator,
1131              width, height, pixelFormatType, dataPtr, dataSize,
1132              numberOfPlanes, planeBaseAddress, planeWidth,
1133              planeHeight, planeBytesPerRow, releaseCallback,
1134              number, // potentially released by callback
1135              pixelBufferAttributes, pixelBufferOut) ;
1136}
1137
1138//===----------------------------------------------------------------------===//
1139// <rdar://problem/7358899> False leak associated with 
1140//  CGBitmapContextCreateWithData
1141//===----------------------------------------------------------------------===//
1142typedef uint32_t CGBitmapInfo;
1143typedef void (*CGBitmapContextReleaseDataCallback)(void *releaseInfo, void *data);
1144    
1145CGContextRef CGBitmapContextCreateWithData(void *data,
1146    size_t width, size_t height, size_t bitsPerComponent,
1147    size_t bytesPerRow, CGColorSpaceRef space, CGBitmapInfo bitmapInfo,
1148    CGBitmapContextReleaseDataCallback releaseCallback, void *releaseInfo);
1149
1150void rdar_7358899(void *data,
1151      size_t width, size_t height, size_t bitsPerComponent,
1152      size_t bytesPerRow, CGColorSpaceRef space, CGBitmapInfo bitmapInfo,
1153      CGBitmapContextReleaseDataCallback releaseCallback) {
1154
1155    // For the allocated object, it doesn't really matter what type it is
1156    // for the purpose of this test.  All we want to show is that
1157    // this is freed later by the callback.
1158    NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1159
1160  CGBitmapContextCreateWithData(data, width, height, bitsPerComponent, // expected-warning{{leak}}
1161    bytesPerRow, space, bitmapInfo, releaseCallback, number);
1162}
1163
1164//===----------------------------------------------------------------------===//
1165// <rdar://problem/7265711> allow 'new', 'copy', 'alloc', 'init' prefix to
1166//  start before '_' when determining Cocoa fundamental rule
1167//
1168// Previously the retain/release checker just skipped prefixes before the
1169// first '_' entirely.  Now the checker honors the prefix if it results in a
1170// recognizable naming convention (e.g., 'new', 'init').
1171//===----------------------------------------------------------------------===//
1172
1173@interface RDar7265711 {}
1174- (id) new_stuff;
1175@end
1176
1177void rdar7265711_a(RDar7265711 *x) {
1178  id y = [x new_stuff]; // expected-warning{{leak}}
1179}
1180
1181void rdar7265711_b(RDar7265711 *x) {
1182  id y = [x new_stuff]; // no-warning
1183  [y release];
1184}
1185
1186//===----------------------------------------------------------------------===//
1187// <rdar://problem/7306898> clang thinks [NSCursor dragCopyCursor] returns a
1188//                          retained reference
1189//===----------------------------------------------------------------------===//
1190
1191@interface NSCursor : NSObject
1192+ (NSCursor *)dragCopyCursor;
1193@end
1194
1195void rdar7306898(void) {
1196  // 'dragCopyCursor' does not follow Cocoa's fundamental rule.  It is a noun, not an sentence
1197  // implying a 'copy' of something.
1198  NSCursor *c =  [NSCursor dragCopyCursor]; // no-warning
1199  NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1200}
1201
1202//===----------------------------------------------------------------------===//
1203// <rdar://problem/7252064> sending 'release', 'retain', etc. to a Class
1204// directly is not likely what the user intended
1205//===----------------------------------------------------------------------===//
1206
1207@interface RDar7252064 : NSObject @end
1208void rdar7252064(void) {
1209  [RDar7252064 release]; // expected-warning{{The 'release' message should be sent to instances of class 'RDar7252064' and not the class directly}}
1210  [RDar7252064 retain]; // expected-warning{{The 'retain' message should be sent to instances of class 'RDar7252064' and not the class directly}}
1211  [RDar7252064 autorelease]; // expected-warning{{The 'autorelease' message should be sent to instances of class 'RDar7252064' and not the class directly}}
1212  [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}}
1213}
1214
1215//===----------------------------------------------------------------------===//
1216// Tests of ownership attributes.
1217//===----------------------------------------------------------------------===//
1218
1219typedef NSString* MyStringTy;
1220
1221@protocol FooP;
1222
1223@interface TestOwnershipAttr : NSObject
1224- (NSString*) returnsAnOwnedString  NS_RETURNS_RETAINED; // no-warning
1225- (NSString*) returnsAnOwnedCFString  CF_RETURNS_RETAINED; // no-warning
1226- (MyStringTy) returnsAnOwnedTypedString NS_RETURNS_RETAINED; // no-warning
1227- (NSString*) newString NS_RETURNS_NOT_RETAINED; // no-warning
1228- (NSString*) newStringNoAttr;
1229- (int) returnsAnOwnedInt NS_RETURNS_RETAINED; // expected-warning{{'ns_returns_retained' attribute only applies to methods that return an Objective-C object}}
1230- (id) pseudoInit NS_CONSUMES_SELF NS_RETURNS_RETAINED;
1231+ (void) consume:(id) NS_CONSUMED x;
1232+ (void) consume2:(id) CF_CONSUMED x;
1233@end
1234
1235static int ownership_attribute_doesnt_go_here NS_RETURNS_RETAINED; // expected-warning{{'ns_returns_retained' attribute only applies to functions and methods}}
1236
1237void test_attr_1(TestOwnershipAttr *X) {
1238  NSString *str = [X returnsAnOwnedString]; // expected-warning{{leak}}
1239}
1240
1241void test_attr_1b(TestOwnershipAttr *X) {
1242  NSString *str = [X returnsAnOwnedCFString]; // expected-warning{{leak}}
1243}
1244
1245void test_attr1c(TestOwnershipAttr *X) {
1246  NSString *str = [X newString]; // no-warning
1247  NSString *str2 = [X newStringNoAttr]; // expected-warning{{leak}}
1248}
1249
1250void testattr2_a() {
1251  TestOwnershipAttr *x = [TestOwnershipAttr alloc]; // expected-warning{{leak}}
1252}
1253
1254void testattr2_b() {
1255  TestOwnershipAttr *x = [[TestOwnershipAttr alloc] pseudoInit];  // expected-warning{{leak}}
1256}
1257
1258void testattr2_c() {
1259  TestOwnershipAttr *x = [[TestOwnershipAttr alloc] pseudoInit]; // no-warning
1260  [x release];
1261}
1262
1263void testattr3() {
1264  TestOwnershipAttr *x = [TestOwnershipAttr alloc]; // no-warning
1265  [TestOwnershipAttr consume:x];
1266  TestOwnershipAttr *y = [TestOwnershipAttr alloc]; // no-warning
1267  [TestOwnershipAttr consume2:y];
1268}
1269
1270void consume_ns(id NS_CONSUMED x);
1271void consume_cf(id CF_CONSUMED x);
1272
1273void testattr4() {
1274  TestOwnershipAttr *x = [TestOwnershipAttr alloc]; // no-warning
1275  consume_ns(x);
1276  TestOwnershipAttr *y = [TestOwnershipAttr alloc]; // no-warning
1277  consume_cf(y);
1278}
1279
1280
1281@interface MyClassTestCFAttr : NSObject {}
1282- (NSDate*) returnsCFRetained CF_RETURNS_RETAINED;
1283- (CFDateRef) returnsCFRetainedAsCF CF_RETURNS_RETAINED;
1284- (CFDateRef) newCFRetainedAsCF CF_RETURNS_NOT_RETAINED;
1285- (CFDateRef) newCFRetainedAsCFNoAttr;
1286- (NSDate*) alsoReturnsRetained;
1287- (CFDateRef) alsoReturnsRetainedAsCF;
1288- (NSDate*) returnsNSRetained NS_RETURNS_RETAINED;
1289@end
1290
1291CF_RETURNS_RETAINED
1292CFDateRef returnsRetainedCFDate()  {
1293  return CFDateCreate(0, CFAbsoluteTimeGetCurrent());
1294}
1295
1296@implementation MyClassTestCFAttr
1297- (NSDate*) returnsCFRetained {
1298  return (NSDate*) returnsRetainedCFDate(); // No leak.
1299}
1300
1301- (CFDateRef) returnsCFRetainedAsCF {
1302  return returnsRetainedCFDate(); // No leak.
1303}
1304
1305- (CFDateRef) newCFRetainedAsCF {
1306  return (CFDateRef)[(id)[self returnsCFRetainedAsCF] autorelease];
1307}
1308
1309- (CFDateRef) newCFRetainedAsCFNoAttr {
1310  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}}
1311}
1312
1313- (NSDate*) alsoReturnsRetained {
1314  return (NSDate*) returnsRetainedCFDate(); // expected-warning{{leak}}
1315}
1316
1317- (CFDateRef) alsoReturnsRetainedAsCF {
1318  return returnsRetainedCFDate(); // expected-warning{{leak}}
1319}
1320
1321
1322- (NSDate*) returnsNSRetained {
1323  return (NSDate*) returnsRetainedCFDate(); // no-warning
1324}
1325@end
1326
1327//===----------------------------------------------------------------------===//
1328// Test that leaks post-dominated by "panic" functions are not reported.
1329//
1330// <rdar://problem/5905851> do not report a leak when post-dominated by a call
1331// to a noreturn or panic function
1332//===----------------------------------------------------------------------===//
1333
1334void panic() __attribute__((noreturn));
1335void panic_not_in_hardcoded_list() __attribute__((noreturn));
1336
1337void test_panic_negative() {
1338  signed z = 1;
1339  CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z);  // expected-warning{{leak}}
1340}
1341
1342void test_panic_positive() {
1343  signed z = 1;
1344  CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // no-warning
1345  panic();
1346}
1347
1348void test_panic_neg_2(int x) {
1349  signed z = 1;
1350  CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // expected-warning{{leak}}
1351  if (x)
1352    panic();
1353}
1354
1355void test_panic_pos_2(int x) {
1356  signed z = 1;
1357  CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // no-warning
1358  if (x)
1359    panic();
1360  if (!x) {
1361    // This showed up in <rdar://problem/7796563>, where we silently missed checking
1362    // the function type for noreturn.  "panic()" is a hard-coded known panic function
1363    // that isn't always noreturn.
1364    panic_not_in_hardcoded_list();
1365  }
1366}
1367
1368//===----------------------------------------------------------------------===//
1369// Test uses of blocks (closures)
1370//===----------------------------------------------------------------------===//
1371
1372void test_blocks_1_pos(void) {
1373  NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1374  ^{}();
1375}
1376
1377void test_blocks_1_indirect_release(void) {
1378  NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1379  ^{ [number release]; }();
1380}
1381
1382void test_blocks_1_indirect_retain(void) {
1383  // Eventually this should be reported as a leak.
1384  NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1385  ^{ [number retain]; }();
1386}
1387
1388void test_blocks_1_indirect_release_via_call(void) {
1389  NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1390  ^(NSObject *o){ [o release]; }(number);
1391}
1392
1393void test_blocks_1_indirect_retain_via_call(void) {
1394  // Eventually this should be reported as a leak.
1395  NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1396  ^(NSObject *o){ [o retain]; }(number);
1397}
1398
1399//===--------------------------------------------------------------------===//
1400// Test sending message to super that returns an object alias.  Previously
1401// this caused a crash in the analyzer.
1402//===--------------------------------------------------------------------===//
1403
1404@interface Rdar8015556 : NSObject {} @end
1405@implementation Rdar8015556
1406- (id)retain {
1407  return [super retain];
1408}
1409@end
1410
1411// <rdar://problem/8272168> - Correcly handle Class<...> in Cocoa Conventions
1412// detector.
1413
1414@protocol Prot_R8272168 @end
1415Class <Prot_R8272168> GetAClassThatImplementsProt_R8272168();
1416void r8272168() {
1417  GetAClassThatImplementsProt_R8272168();
1418}
1419
1420// Test case for <rdar://problem/8356342>, which in the past triggered
1421// a false positive.
1422@interface RDar8356342
1423- (NSDate*) rdar8356342:(NSDate *)inValue;
1424@end
1425
1426@implementation RDar8356342
1427- (NSDate*) rdar8356342:(NSDate*)inValue {
1428  NSDate *outValue = inValue;
1429  if (outValue == 0)
1430    outValue = [[NSDate alloc] init]; // no-warning
1431
1432  if (outValue != inValue)
1433    [outValue autorelease];
1434
1435  return outValue;
1436}
1437@end
1438
1439// <rdar://problem/8724287> - This test case previously crashed because
1440// of a bug in BugReporter.
1441extern const void *CFDictionaryGetValue(CFDictionaryRef theDict, const void *key);
1442typedef struct __CFError * CFErrorRef;
1443extern const CFStringRef kCFErrorUnderlyingErrorKey;
1444extern CFDictionaryRef CFErrorCopyUserInfo(CFErrorRef err);
1445static void rdar_8724287(CFErrorRef error)
1446{
1447    CFErrorRef error_to_dump;
1448
1449    error_to_dump = error;
1450    while (error_to_dump != ((void*)0)) {
1451        CFDictionaryRef info;
1452
1453        info = CFErrorCopyUserInfo(error_to_dump); // expected-warning{{Potential leak of an object allocated on line}}
1454
1455        if (info != ((void*)0)) {
1456        }
1457
1458        error_to_dump = (CFErrorRef) CFDictionaryGetValue(info, kCFErrorUnderlyingErrorKey);
1459    }
1460}
1461
1462// <rdar://problem/9234108> - Make sure the model applies cf_consumed
1463// correctly in argument positions besides the first.
1464extern void *CFStringCreate(void);
1465extern void rdar_9234108_helper(void *key, void * CF_CONSUMED value);
1466void rdar_9234108() {
1467  rdar_9234108_helper(0, CFStringCreate());
1468}
1469
1470// <rdar://problem/9726279> - Make sure that objc_method_family works
1471// to override naming conventions.
1472struct TwoDoubles {
1473  double one;
1474  double two;
1475};
1476typedef struct TwoDoubles TwoDoubles;
1477
1478@interface NSValue (Mine)
1479- (id)_prefix_initWithTwoDoubles:(TwoDoubles)twoDoubles __attribute__((objc_method_family(init)));
1480@end
1481
1482@implementation NSValue (Mine)
1483- (id)_prefix_initWithTwoDoubles:(TwoDoubles)twoDoubles
1484{
1485  return [self init];
1486}
1487@end
1488
1489void rdar9726279() {
1490  TwoDoubles twoDoubles = { 0.0, 0.0 };
1491  NSValue *value = [[NSValue alloc] _prefix_initWithTwoDoubles:twoDoubles];
1492  [value release];
1493}
1494
1495// <rdar://problem/9732321>
1496// Test camelcase support for CF conventions.  While Core Foundation APIs
1497// don't use camel casing, other code is allowed to use it.
1498CFArrayRef camelcase_create_1() {
1499  return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1500}
1501
1502CFArrayRef camelcase_createno() {
1503  return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1504}
1505
1506CFArrayRef camelcase_copy() {
1507  return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1508}
1509
1510CFArrayRef camelcase_copying() {
1511  return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1512}
1513
1514CFArrayRef copyCamelCase() {
1515  return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1516}
1517
1518CFArrayRef __copyCamelCase() {
1519  return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1520}
1521
1522CFArrayRef __createCamelCase() {
1523  return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1524}
1525
1526CFArrayRef camel_create() {
1527  return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1528}
1529
1530
1531CFArrayRef camel_creat() {
1532  return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1533}
1534
1535CFArrayRef camel_copy() {
1536  return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1537}
1538
1539CFArrayRef camel_copyMachine() {
1540  return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1541}
1542
1543CFArrayRef camel_copymachine() {
1544  return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1545}
1546
1547// rdar://problem/8024350
1548@protocol F18P
1549- (id) clone;
1550@end
1551@interface F18 : NSObject<F18P> @end
1552@interface F18(Cat)
1553- (id) clone NS_RETURNS_RETAINED;
1554@end
1555
1556@implementation F18
1557- (id) clone {
1558  return [F18 alloc];
1559}
1560@end
1561
1562// Radar 6582778.
1563void rdar6582778(void) {
1564  CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
1565  CFTypeRef vals[] = { CFDateCreate(0, t) }; // expected-warning {{leak}}
1566}
1567
1568CFTypeRef global;
1569
1570void rdar6582778_2(void) {
1571  CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
1572  global = CFDateCreate(0, t); // no-warning
1573}
1574