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