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