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