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