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