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