retain-release.m revision c484381467789938b06872bb1b270db1b6ec164c
1// RUN: clang-cc -triple x86_64-apple-darwin10 -analyze -checker-cfref -analyzer-store=basic -verify %s && 2// RUN: clang-cc -triple x86_64-apple-darwin10 -analyze -checker-cfref -analyzer-store=region -verify %s 3 4#if __has_feature(attribute_ns_returns_retained) 5#define NS_RETURNS_RETAINED __attribute__((ns_returns_retained)) 6#endif 7#if __has_feature(attribute_cf_returns_retained) 8#define CF_RETURNS_RETAINED __attribute__((cf_returns_retained)) 9#endif 10 11//===----------------------------------------------------------------------===// 12// The following code is reduced using delta-debugging from Mac OS X headers: 13// 14// #include <Cocoa/Cocoa.h> 15// #include <CoreFoundation/CoreFoundation.h> 16// #include <DiskArbitration/DiskArbitration.h> 17// #include <QuartzCore/QuartzCore.h> 18// #include <Quartz/Quartz.h> 19// #include <IOKit/IOKitLib.h> 20// 21// It includes the basic definitions for the test cases below. 22//===----------------------------------------------------------------------===// 23 24typedef unsigned int __darwin_natural_t; 25typedef unsigned long uintptr_t; 26typedef unsigned int uint32_t; 27typedef unsigned long long uint64_t; 28typedef unsigned int UInt32; 29typedef signed long CFIndex; 30typedef struct { 31 CFIndex location; 32 CFIndex length; 33} CFRange; 34static __inline__ __attribute__((always_inline)) CFRange CFRangeMake(CFIndex loc, CFIndex len) { 35 CFRange range; 36 range.location = loc; 37 range.length = len; 38 return range; 39} 40typedef const void * CFTypeRef; 41typedef const struct __CFString * CFStringRef; 42typedef const struct __CFAllocator * CFAllocatorRef; 43extern const CFAllocatorRef kCFAllocatorDefault; 44extern CFTypeRef CFRetain(CFTypeRef cf); 45extern void CFRelease(CFTypeRef cf); 46typedef struct { 47} 48CFArrayCallBacks; 49extern const CFArrayCallBacks kCFTypeArrayCallBacks; 50typedef const struct __CFArray * CFArrayRef; 51typedef struct __CFArray * CFMutableArrayRef; 52extern CFMutableArrayRef CFArrayCreateMutable(CFAllocatorRef allocator, CFIndex capacity, const CFArrayCallBacks *callBacks); 53extern const void *CFArrayGetValueAtIndex(CFArrayRef theArray, CFIndex idx); 54extern void CFArrayAppendValue(CFMutableArrayRef theArray, const void *value); 55typedef struct { 56} 57CFDictionaryKeyCallBacks; 58extern const CFDictionaryKeyCallBacks kCFTypeDictionaryKeyCallBacks; 59typedef struct { 60} 61CFDictionaryValueCallBacks; 62extern const CFDictionaryValueCallBacks kCFTypeDictionaryValueCallBacks; 63typedef const struct __CFDictionary * CFDictionaryRef; 64typedef struct __CFDictionary * CFMutableDictionaryRef; 65extern CFMutableDictionaryRef CFDictionaryCreateMutable(CFAllocatorRef allocator, CFIndex capacity, const CFDictionaryKeyCallBacks *keyCallBacks, const CFDictionaryValueCallBacks *valueCallBacks); 66typedef UInt32 CFStringEncoding; 67enum { 68kCFStringEncodingMacRoman = 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 }; 69extern CFStringRef CFStringCreateWithCString(CFAllocatorRef alloc, const char *cStr, CFStringEncoding encoding); 70typedef double CFTimeInterval; 71typedef CFTimeInterval CFAbsoluteTime; 72extern CFAbsoluteTime CFAbsoluteTimeGetCurrent(void); 73typedef const struct __CFDate * CFDateRef; 74extern CFDateRef CFDateCreate(CFAllocatorRef allocator, CFAbsoluteTime at); 75extern CFAbsoluteTime CFDateGetAbsoluteTime(CFDateRef theDate); 76typedef __darwin_natural_t natural_t; 77typedef natural_t mach_port_name_t; 78typedef mach_port_name_t mach_port_t; 79typedef int kern_return_t; 80typedef kern_return_t mach_error_t; 81enum { 82kCFNumberSInt8Type = 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 }; 83typedef CFIndex CFNumberType; 84typedef const struct __CFNumber * CFNumberRef; 85extern CFNumberRef CFNumberCreate(CFAllocatorRef allocator, CFNumberType theType, const void *valuePtr); 86typedef const struct __CFAttributedString *CFAttributedStringRef; 87typedef struct __CFAttributedString *CFMutableAttributedStringRef; 88extern CFAttributedStringRef CFAttributedStringCreate(CFAllocatorRef alloc, CFStringRef str, CFDictionaryRef attributes) ; 89extern CFMutableAttributedStringRef CFAttributedStringCreateMutableCopy(CFAllocatorRef alloc, CFIndex maxLength, CFAttributedStringRef aStr) ; 90extern void CFAttributedStringSetAttribute(CFMutableAttributedStringRef aStr, CFRange range, CFStringRef attrName, CFTypeRef value) ; 91typedef signed char BOOL; 92typedef unsigned long NSUInteger; 93@class NSString, Protocol; 94extern void NSLog(NSString *format, ...) __attribute__((format(__NSString__, 1, 2))); 95typedef struct _NSZone NSZone; 96@class NSInvocation, NSMethodSignature, NSCoder, NSString, NSEnumerator; 97@protocol NSObject - (BOOL)isEqual:(id)object; 98- (id)retain; 99- (oneway void)release; 100- (id)autorelease; 101@end @protocol NSCopying - (id)copyWithZone:(NSZone *)zone; 102@end @protocol NSMutableCopying - (id)mutableCopyWithZone:(NSZone *)zone; 103@end @protocol NSCoding - (void)encodeWithCoder:(NSCoder *)aCoder; 104@end @interface NSObject <NSObject> { 105} 106+ (id)allocWithZone:(NSZone *)zone; 107+ (id)alloc; 108- (void)dealloc; 109@end extern id NSAllocateObject(Class aClass, NSUInteger extraBytes, NSZone *zone); 110typedef struct { 111} 112NSFastEnumerationState; 113@protocol NSFastEnumeration - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len; 114@end @class NSString, NSDictionary; 115@interface NSValue : NSObject <NSCopying, NSCoding> - (void)getValue:(void *)value; 116@end @interface NSNumber : NSValue - (char)charValue; 117- (id)initWithInt:(int)value; 118@end @class NSString; 119@interface NSArray : NSObject <NSCopying, NSMutableCopying, NSCoding, NSFastEnumeration> - (NSUInteger)count; 120@end @interface NSArray (NSArrayCreation) + (id)array; 121@end @interface NSAutoreleasePool : NSObject { 122} 123- (void)drain; 124@end extern NSString * const NSBundleDidLoadNotification; 125typedef double NSTimeInterval; 126@interface NSDate : NSObject <NSCopying, NSCoding> - (NSTimeInterval)timeIntervalSinceReferenceDate; 127@end typedef unsigned short unichar; 128@interface NSString : NSObject <NSCopying, NSMutableCopying, NSCoding> - (NSUInteger)length; 129- ( const char *)UTF8String; 130- (id)initWithUTF8String:(const char *)nullTerminatedCString; 131+ (id)stringWithUTF8String:(const char *)nullTerminatedCString; 132@end @class NSString, NSURL, NSError; 133@interface NSData : NSObject <NSCopying, NSMutableCopying, NSCoding> - (NSUInteger)length; 134+ (id)dataWithBytesNoCopy:(void *)bytes length:(NSUInteger)length; 135+ (id)dataWithBytesNoCopy:(void *)bytes length:(NSUInteger)length freeWhenDone:(BOOL)b; 136@end @class NSLocale, NSDate, NSCalendar, NSTimeZone, NSError, NSArray, NSMutableDictionary; 137@interface NSDictionary : NSObject <NSCopying, NSMutableCopying, NSCoding, NSFastEnumeration> - (NSUInteger)count; 138@end @interface NSMutableDictionary : NSDictionary - (void)removeObjectForKey:(id)aKey; 139- (void)setObject:(id)anObject forKey:(id)aKey; 140@end @interface NSMutableDictionary (NSMutableDictionaryCreation) + (id)dictionaryWithCapacity:(NSUInteger)numItems; 141@end typedef double CGFloat; 142struct CGSize { 143}; 144typedef struct CGSize CGSize; 145struct CGRect { 146}; 147typedef struct CGRect CGRect; 148typedef mach_port_t io_object_t; 149typedef char io_name_t[128]; 150typedef io_object_t io_iterator_t; 151typedef io_object_t io_service_t; 152typedef struct IONotificationPort * IONotificationPortRef; 153typedef void (*IOServiceMatchingCallback)( void * refcon, io_iterator_t iterator ); 154io_service_t IOServiceGetMatchingService( mach_port_t masterPort, CFDictionaryRef matching ); 155kern_return_t IOServiceGetMatchingServices( mach_port_t masterPort, CFDictionaryRef matching, io_iterator_t * existing ); 156kern_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)); 157kern_return_t IOServiceAddMatchingNotification( IONotificationPortRef notifyPort, const io_name_t notificationType, CFDictionaryRef matching, IOServiceMatchingCallback callback, void * refCon, io_iterator_t * notification ); 158CFMutableDictionaryRef IOServiceMatching( const char * name ); 159CFMutableDictionaryRef IOServiceNameMatching( const char * name ); 160CFMutableDictionaryRef IOBSDNameMatching( mach_port_t masterPort, uint32_t options, const char * bsdName ); 161CFMutableDictionaryRef IOOpenFirmwarePathMatching( mach_port_t masterPort, uint32_t options, const char * path ); 162CFMutableDictionaryRef IORegistryEntryIDMatching( uint64_t entryID ); 163typedef struct __DASession * DASessionRef; 164extern DASessionRef DASessionCreate( CFAllocatorRef allocator ); 165typedef struct __DADisk * DADiskRef; 166extern DADiskRef DADiskCreateFromBSDName( CFAllocatorRef allocator, DASessionRef session, const char * name ); 167extern DADiskRef DADiskCreateFromIOMedia( CFAllocatorRef allocator, DASessionRef session, io_service_t media ); 168extern CFDictionaryRef DADiskCopyDescription( DADiskRef disk ); 169extern DADiskRef DADiskCopyWholeDisk( DADiskRef disk ); 170@interface NSTask : NSObject - (id)init; 171@end typedef struct CGColorSpace *CGColorSpaceRef; 172typedef struct CGImage *CGImageRef; 173typedef struct CGLayer *CGLayerRef; 174@interface NSResponder : NSObject <NSCoding> { 175} 176@end @protocol NSAnimatablePropertyContainer - (id)animator; 177@end extern NSString *NSAnimationTriggerOrderIn ; 178@interface NSView : NSResponder <NSAnimatablePropertyContainer> { 179} 180@end @protocol NSValidatedUserInterfaceItem - (SEL)action; 181@end @protocol NSUserInterfaceValidations - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)anItem; 182@end @class NSDate, NSDictionary, NSError, NSException, NSNotification; 183@interface NSApplication : NSResponder <NSUserInterfaceValidations> { 184} 185@end enum { 186NSTerminateCancel = 0, NSTerminateNow = 1, NSTerminateLater = 2 }; 187typedef NSUInteger NSApplicationTerminateReply; 188@protocol NSApplicationDelegate <NSObject> @optional - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender; 189@end @class NSAttributedString, NSEvent, NSFont, NSFormatter, NSImage, NSMenu, NSText, NSView, NSTextView; 190@interface NSCell : NSObject <NSCopying, NSCoding> { 191} 192@end @class NSTextField, NSPanel, NSArray, NSWindow, NSImage, NSButton, NSError; 193typedef struct { 194} 195CVTimeStamp; 196@interface CIImage : NSObject <NSCoding, NSCopying> { 197} 198typedef int CIFormat; 199@end enum { 200kDAReturnSuccess = 0, kDAReturnError = (((0x3e)&0x3f)<<26) | (((0x368)&0xfff)<<14) | 0x01, kDAReturnBusy = (((0x3e)&0x3f)<<26) | (((0x368)&0xfff)<<14) | 0x02, kDAReturnBadArgument = (((0x3e)&0x3f)<<26) | (((0x368)&0xfff)<<14) | 0x03, kDAReturnExclusiveAccess = (((0x3e)&0x3f)<<26) | (((0x368)&0xfff)<<14) | 0x04, kDAReturnNoResources = (((0x3e)&0x3f)<<26) | (((0x368)&0xfff)<<14) | 0x05, kDAReturnNotFound = (((0x3e)&0x3f)<<26) | (((0x368)&0xfff)<<14) | 0x06, kDAReturnNotMounted = (((0x3e)&0x3f)<<26) | (((0x368)&0xfff)<<14) | 0x07, kDAReturnNotPermitted = (((0x3e)&0x3f)<<26) | (((0x368)&0xfff)<<14) | 0x08, kDAReturnNotPrivileged = (((0x3e)&0x3f)<<26) | (((0x368)&0xfff)<<14) | 0x09, kDAReturnNotReady = (((0x3e)&0x3f)<<26) | (((0x368)&0xfff)<<14) | 0x0A, kDAReturnNotWritable = (((0x3e)&0x3f)<<26) | (((0x368)&0xfff)<<14) | 0x0B, kDAReturnUnsupported = (((0x3e)&0x3f)<<26) | (((0x368)&0xfff)<<14) | 0x0C }; 201typedef mach_error_t DAReturn; 202typedef const struct __DADissenter * DADissenterRef; 203extern DADissenterRef DADissenterCreate( CFAllocatorRef allocator, DAReturn status, CFStringRef string ); 204@interface CIContext: NSObject { 205} 206- (CGImageRef)createCGImage:(CIImage *)im fromRect:(CGRect)r; 207- (CGImageRef)createCGImage:(CIImage *)im fromRect:(CGRect)r format:(CIFormat)f colorSpace:(CGColorSpaceRef)cs; 208- (CGLayerRef)createCGLayerWithSize:(CGSize)size info:(CFDictionaryRef)d; 209@end extern NSString* const QCRendererEventKey; 210@protocol QCCompositionRenderer - (NSDictionary*) attributes; 211@end @interface QCRenderer : NSObject <QCCompositionRenderer> { 212} 213- (id) createSnapshotImageOfType:(NSString*)type; 214@end extern NSString* const QCViewDidStartRenderingNotification; 215@interface QCView : NSView <QCCompositionRenderer> { 216} 217- (id) createSnapshotImageOfType:(NSString*)type; 218@end enum { 219ICEXIFOrientation1 = 1, ICEXIFOrientation2 = 2, ICEXIFOrientation3 = 3, ICEXIFOrientation4 = 4, ICEXIFOrientation5 = 5, ICEXIFOrientation6 = 6, ICEXIFOrientation7 = 7, ICEXIFOrientation8 = 8, }; 220@class ICDevice; 221@protocol ICDeviceDelegate <NSObject> @required - (void)didRemoveDevice:(ICDevice*)device; 222@end extern NSString *const ICScannerStatusWarmingUp; 223@class ICScannerDevice; 224@protocol ICScannerDeviceDelegate <ICDeviceDelegate> @optional - (void)scannerDeviceDidBecomeAvailable:(ICScannerDevice*)scanner; 225@end 226 227//===----------------------------------------------------------------------===// 228// Test cases. 229//===----------------------------------------------------------------------===// 230 231CFAbsoluteTime f1() { 232 CFAbsoluteTime t = CFAbsoluteTimeGetCurrent(); 233 CFDateRef date = CFDateCreate(0, t); 234 CFRetain(date); 235 CFRelease(date); 236 CFDateGetAbsoluteTime(date); // no-warning 237 CFRelease(date); 238 t = CFDateGetAbsoluteTime(date); // expected-warning{{Reference-counted object is used after it is released.}} 239 return t; 240} 241 242CFAbsoluteTime f2() { 243 CFAbsoluteTime t = CFAbsoluteTimeGetCurrent(); 244 CFDateRef date = CFDateCreate(0, t); 245 [((NSDate*) date) retain]; 246 CFRelease(date); 247 CFDateGetAbsoluteTime(date); // no-warning 248 [((NSDate*) date) release]; 249 t = CFDateGetAbsoluteTime(date); // expected-warning{{Reference-counted object is used after it is released.}} 250 return t; 251} 252 253 254NSDate* global_x; 255 256// Test to see if we supresss an error when we store the pointer 257// to a global. 258 259CFAbsoluteTime f3() { 260 CFAbsoluteTime t = CFAbsoluteTimeGetCurrent(); 261 CFDateRef date = CFDateCreate(0, t); 262 [((NSDate*) date) retain]; 263 CFRelease(date); 264 CFDateGetAbsoluteTime(date); // no-warning 265 global_x = (NSDate*) date; 266 [((NSDate*) date) release]; 267 t = CFDateGetAbsoluteTime(date); // no-warning 268 return t; 269} 270 271//--------------------------------------------------------------------------- 272// Test case 'f4' differs for region store and basic store. See 273// retain-release-region-store.m and retain-release-basic-store.m. 274//--------------------------------------------------------------------------- 275 276// Test a leak. 277 278CFAbsoluteTime f5(int x) { 279 CFAbsoluteTime t = CFAbsoluteTimeGetCurrent(); 280 CFDateRef date = CFDateCreate(0, t); // expected-warning{{leak}} 281 282 if (x) 283 CFRelease(date); 284 285 return t; 286} 287 288// Test a leak involving the return. 289 290CFDateRef f6(int x) { 291 CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent()); // expected-warning{{leak}} 292 CFRetain(date); 293 return date; 294} 295 296// Test a leak involving an overwrite. 297 298CFDateRef f7() { 299 CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent()); //expected-warning{{leak}} 300 CFRetain(date); 301 date = CFDateCreate(0, CFAbsoluteTimeGetCurrent()); 302 return date; 303} 304 305// Generalization of Create rule. MyDateCreate returns a CFXXXTypeRef, and 306// has the word create. 307CFDateRef MyDateCreate(); 308 309CFDateRef f8() { 310 CFDateRef date = MyDateCreate(); // expected-warning{{leak}} 311 CFRetain(date); 312 return date; 313} 314 315CFDateRef f9() { 316 CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent()); 317 int *p = 0; 318 // When allocations fail, CFDateCreate can return null. 319 if (!date) *p = 1; // expected-warning{{null}} 320 return date; 321} 322 323// Handle DiskArbitration API: 324// 325// http://developer.apple.com/DOCUMENTATION/DARWIN/Reference/DiscArbitrationFramework/ 326// 327void f10(io_service_t media, DADiskRef d, CFStringRef s) { 328 DADiskRef disk = DADiskCreateFromBSDName(kCFAllocatorDefault, 0, "hello"); // expected-warning{{leak}} 329 if (disk) NSLog(@"ok"); 330 331 disk = DADiskCreateFromIOMedia(kCFAllocatorDefault, 0, media); // expected-warning{{leak}} 332 if (disk) NSLog(@"ok"); 333 334 CFDictionaryRef dict = DADiskCopyDescription(d); // expected-warning{{leak}} 335 if (dict) NSLog(@"ok"); 336 337 disk = DADiskCopyWholeDisk(d); // expected-warning{{leak}} 338 if (disk) NSLog(@"ok"); 339 340 DADissenterRef dissenter = DADissenterCreate(kCFAllocatorDefault, // expected-warning{{leak}} 341 kDAReturnSuccess, s); 342 if (dissenter) NSLog(@"ok"); 343 344 DASessionRef session = DASessionCreate(kCFAllocatorDefault); // expected-warning{{leak}} 345 if (session) NSLog(@"ok"); 346} 347 348// Test retain/release checker with CFString and CFMutableArray. 349void f11() { 350 // Create the array. 351 CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); 352 353 // Create a string. 354 CFStringRef s1 = CFStringCreateWithCString(0, "hello world", 355 kCFStringEncodingUTF8); 356 357 // Add the string to the array. 358 CFArrayAppendValue(A, s1); 359 360 // Decrement the reference count. 361 CFRelease(s1); // no-warning 362 363 // Get the string. We don't own it. 364 s1 = (CFStringRef) CFArrayGetValueAtIndex(A, 0); 365 366 // Release the array. 367 CFRelease(A); // no-warning 368 369 // Release the string. This is a bug. 370 CFRelease(s1); // expected-warning{{Incorrect decrement of the reference count}} 371} 372 373// PR 3337: Handle functions declared using typedefs. 374typedef CFTypeRef CREATEFUN(); 375CREATEFUN MyCreateFun; 376 377void f12() { 378 CFTypeRef o = MyCreateFun(); // expected-warning {{leak}} 379} 380 381void f13_autorelease() { 382 CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning 383 [(id) A autorelease]; // no-warning 384} 385 386void f13_autorelease_b() { 387 CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); 388 [(id) A autorelease]; 389 [(id) A autorelease]; // expected-warning{{Object sent -autorelease too many times}} 390} 391 392CFMutableArrayRef f13_autorelease_c() { 393 CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); 394 [(id) A autorelease]; 395 [(id) A autorelease]; 396 return A; // expected-warning{{Object sent -autorelease too many times}} 397} 398 399CFMutableArrayRef f13_autorelease_d() { 400 CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); 401 [(id) A autorelease]; 402 [(id) A autorelease]; 403 CFMutableArrayRef B = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning{{Object sent -autorelease too many times}} 404 CFRelease(B); // no-warning 405 while (1) {} 406} 407 408 409// This case exercises the logic where the leak site is the same as the allocation site. 410void f14_leakimmediately() { 411 CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning{{leak}} 412} 413 414// Test that we track an allocated object beyond the point where the *name* 415// of the variable storing the reference is no longer live. 416void f15() { 417 // Create the array. 418 CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); 419 CFMutableArrayRef *B = &A; 420 // At this point, the name 'A' is no longer live. 421 CFRelease(*B); // no-warning 422} 423 424// Test when we pass NULL to CFRetain/CFRelease. 425void f16(int x, CFTypeRef p) { 426 if (p) 427 return; 428 429 if (x) { 430 CFRelease(p); // expected-warning{{Null pointer argument in call to CFRelease}} 431 } 432 else { 433 CFRetain(p); // expected-warning{{Null pointer argument in call to CFRetain}} 434 } 435} 436 437// Test basic tracking of ivars associated with 'self'. For the retain/release 438// checker we currently do not want to flag leaks associated with stores 439// of tracked objects to ivars. 440@interface SelfIvarTest : NSObject { 441 id myObj; 442} 443- (void)test_self_tracking; 444@end 445 446@implementation SelfIvarTest 447- (void)test_self_tracking { 448 myObj = (id) CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning 449} 450@end 451 452// Test return of non-owned objects in contexts where an owned object 453// is expected. 454@interface TestReturnNotOwnedWhenExpectedOwned 455- (NSString*)newString; 456@end 457 458@implementation TestReturnNotOwnedWhenExpectedOwned 459- (NSString*)newString { 460 NSString *s = [NSString stringWithUTF8String:"hello"]; 461 return s; // expected-warning{{Object with +0 retain counts returned to caller where a +1 (owning) retain count is expected}} 462} 463@end 464 465// <rdar://problem/6659160> 466int isFoo(char c); 467 468static void rdar_6659160(char *inkind, char *inname) 469{ 470 // We currently expect that [NSObject alloc] cannot fail. This 471 // will be a toggled flag in the future. It can indeed return null, but 472 // Cocoa programmers generally aren't expected to reason about out-of-memory 473 // conditions. 474 NSString *kind = [[NSString alloc] initWithUTF8String:inkind]; // expected-warning{{leak}} 475 476 // We do allow stringWithUTF8String to fail. This isn't really correct, as 477 // far as returning 0. In most error conditions it will throw an exception. 478 // If allocation fails it could return 0, but again this 479 // isn't expected. 480 NSString *name = [NSString stringWithUTF8String:inname]; 481 if(!name) 482 return; 483 484 const char *kindC = 0; 485 const char *nameC = 0; 486 487 // In both cases, we cannot reach a point down below where we 488 // dereference kindC or nameC with either being null. This is because 489 // we assume that [NSObject alloc] doesn't fail and that we have the guard 490 // up above. 491 492 if(kind) 493 kindC = [kind UTF8String]; 494 if(name) 495 nameC = [name UTF8String]; 496 if(!isFoo(kindC[0])) // expected-warning{{null}} 497 return; 498 if(!isFoo(nameC[0])) // no-warning 499 return; 500 501 [kind release]; 502 [name release]; // expected-warning{{Incorrect decrement of the reference count}} 503} 504 505// PR 3677 - 'allocWithZone' should be treated as following the Cocoa naming 506// conventions with respect to 'return'ing ownership. 507@interface PR3677: NSObject @end 508@implementation PR3677 509+ (id)allocWithZone:(NSZone *)inZone { 510 return [super allocWithZone:inZone]; // no-warning 511} 512@end 513 514// PR 3820 - Reason about calls to -dealloc 515void pr3820_DeallocInsteadOfRelease(void) 516{ 517 id foo = [[NSString alloc] init]; // no-warning 518 [foo dealloc]; 519 // foo is not leaked, since it has been deallocated. 520} 521 522void pr3820_ReleaseAfterDealloc(void) 523{ 524 id foo = [[NSString alloc] init]; 525 [foo dealloc]; 526 [foo release]; // expected-warning{{used after it is release}} 527 // NSInternalInconsistencyException: message sent to deallocated object 528} 529 530void pr3820_DeallocAfterRelease(void) 531{ 532 NSLog(@"\n\n[%s]", __FUNCTION__); 533 id foo = [[NSString alloc] init]; 534 [foo release]; 535 [foo dealloc]; // expected-warning{{used after it is released}} 536 // message sent to released object 537} 538 539// From <rdar://problem/6704930>. The problem here is that 'length' binds to 540// '($0 - 1)' after '--length', but SimpleConstraintManager doesn't know how to 541// reason about '($0 - 1) > constant'. As a temporary hack, we drop the value 542// of '($0 - 1)' and conjure a new symbol. 543void rdar6704930(unsigned char *s, unsigned int length) { 544 NSString* name = 0; 545 if (s != 0) { 546 if (length > 0) { 547 while (length > 0) { 548 if (*s == ':') { 549 ++s; 550 --length; 551 name = [[NSString alloc] init]; // no-warning 552 break; 553 } 554 ++s; 555 --length; 556 } 557 if ((length == 0) && (name != 0)) { 558 [name release]; 559 name = 0; 560 } 561 if (length == 0) { // no ':' found -> use it all as name 562 name = [[NSString alloc] init]; // no-warning 563 } 564 } 565 } 566 567 if (name != 0) { 568 [name release]; 569 } 570} 571 572//===----------------------------------------------------------------------===// 573// <rdar://problem/6833332> 574// One build of the analyzer accidentally stopped tracking the allocated 575// object after the 'retain'. 576//===----------------------------------------------------------------------===// 577 578@interface rdar_6833332 : NSObject <NSApplicationDelegate> { 579 NSWindow *window; 580} 581@property (nonatomic, retain) NSWindow *window; 582@end 583 584@implementation rdar_6833332 585@synthesize window; 586- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { 587 NSMutableDictionary *dict = [[NSMutableDictionary dictionaryWithCapacity:4] retain]; // expected-warning{{leak}} 588 589 [dict setObject:@"foo" forKey:@"bar"]; 590 591 NSLog(@"%@", dict); 592} 593- (void)dealloc { 594 [window release]; 595 [super dealloc]; 596} 597@end 598 599//===----------------------------------------------------------------------===// 600// <rdar://problem/6257780> clang checker fails to catch use-after-release 601//===----------------------------------------------------------------------===// 602 603int rdar_6257780_Case1() { 604 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 605 NSArray *array = [NSArray array]; 606 [array release]; // expected-warning{{Incorrect decrement of the reference count of an object is not owned at this point by the caller}} 607 [pool drain]; 608 return 0; 609} 610 611//===----------------------------------------------------------------------===// 612// <rdar://problem/6866843> Checker should understand new/setObject:/release constructs 613//===----------------------------------------------------------------------===// 614 615void rdar_6866843() { 616 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 617 NSMutableDictionary* dictionary = [[NSMutableDictionary alloc] init]; 618 NSArray* array = [[NSArray alloc] init]; 619 [dictionary setObject:array forKey:@"key"]; 620 [array release]; 621 // Using 'array' here should be fine 622 NSLog(@"array = %@\n", array); // no-warning 623 // Now the array is released 624 [dictionary release]; 625 [pool drain]; 626} 627 628 629//===----------------------------------------------------------------------===// 630// <rdar://problem/6877235> Classes typedef-ed to CF objects should get the same treatment as CF objects 631//===----------------------------------------------------------------------===// 632 633typedef CFTypeRef OtherRef; 634 635@interface RDar6877235 : NSObject {} 636- (CFTypeRef)_copyCFTypeRef; 637- (OtherRef)_copyOtherRef; 638@end 639 640@implementation RDar6877235 641- (CFTypeRef)_copyCFTypeRef { 642 return [[NSString alloc] init]; // no-warning 643} 644- (OtherRef)_copyOtherRef { 645 return [[NSString alloc] init]; // no-warning 646} 647@end 648 649//===----------------------------------------------------------------------===// 650//<rdar://problem/6320065> false positive - init method returns an object owned by caller 651//===----------------------------------------------------------------------===// 652 653@interface RDar6320065 : NSObject { 654 NSString *_foo; 655} 656- (id)initReturningNewClass; 657- (id)initReturningNewClassBad; 658- (id)initReturningNewClassBad2; 659@end 660 661@interface RDar6320065Subclass : RDar6320065 662@end 663 664@implementation RDar6320065 665- (id)initReturningNewClass { 666 [self release]; 667 self = [[RDar6320065Subclass alloc] init]; // no-warning 668 return self; 669} 670- (id)initReturningNewClassBad { 671 [self release]; 672 [[RDar6320065Subclass alloc] init]; // expected-warning {{leak}} 673 return self; 674} 675- (id)initReturningNewClassBad2 { 676 [self release]; 677 self = [[RDar6320065Subclass alloc] init]; 678 return [self autorelease]; // expected-warning{{Object with +0 retain counts returned to caller where a +1 (owning) retain count is expected}} 679} 680 681@end 682 683@implementation RDar6320065Subclass 684@end 685 686int RDar6320065_test() { 687 RDar6320065 *test = [[RDar6320065 alloc] init]; // no-warning 688 [test release]; 689 return 0; 690} 691 692//===----------------------------------------------------------------------===// 693// <rdar://problem/6859457> [NSData dataWithBytesNoCopy] does not return a retained object 694//===----------------------------------------------------------------------===// 695 696@interface RDar6859457 : NSObject {} 697- (NSString*) NoCopyString; 698- (NSString*) noCopyString; 699@end 700 701@implementation RDar6859457 702- (NSString*) NoCopyString { return [[NSString alloc] init]; } // no-warning 703- (NSString*) noCopyString { return [[NSString alloc] init]; } // no-warning 704@end 705 706void test_RDar6859457(RDar6859457 *x, void *bytes, NSUInteger dataLength) { 707 [x NoCopyString]; // expected-warning{{leak}} 708 [x noCopyString]; // expected-warning{{leak}} 709 [NSData dataWithBytesNoCopy:bytes length:dataLength]; // no-warning 710 [NSData dataWithBytesNoCopy:bytes length:dataLength freeWhenDone:1]; // no-warning 711} 712 713//===----------------------------------------------------------------------===// 714// PR 4230 - an autorelease pool is not necessarily leaked during a premature 715// return 716//===----------------------------------------------------------------------===// 717 718static void PR4230(void) 719{ 720 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // no-warning 721 NSString *object = [[[NSString alloc] init] autorelease]; // no-warning 722 return; 723} 724 725//===----------------------------------------------------------------------===// 726// Method name that has a null IdentifierInfo* for its first selector slot. 727// This test just makes sure that we handle it. 728//===----------------------------------------------------------------------===// 729 730@interface TestNullIdentifier 731@end 732 733@implementation TestNullIdentifier 734+ (id):(int)x, ... { 735 return [[NSString alloc] init]; // expected-warning{{leak}} 736} 737@end 738 739//===----------------------------------------------------------------------===// 740// <rdar://problem/6893565> don't flag leaks for return types that cannot be 741// determined to be CF types 742//===----------------------------------------------------------------------===// 743 744// We don't know if 'struct s6893565' represents a Core Foundation type, so 745// we shouldn't emit an error here. 746typedef struct s6893565* TD6893565; 747 748@interface RDar6893565 {} 749-(TD6893565)newThing; 750@end 751 752@implementation RDar6893565 753-(TD6893565)newThing { 754 return (TD6893565) [[NSString alloc] init]; // no-warning 755} 756@end 757 758//===----------------------------------------------------------------------===// 759// <rdar://problem/6902710> clang: false positives w/QC and CoreImage methods 760//===----------------------------------------------------------------------===// 761 762void rdar6902710(QCView *view, QCRenderer *renderer, CIContext *context, 763 NSString *str, CIImage *img, CGRect rect, 764 CIFormat form, CGColorSpaceRef cs) { 765 [view createSnapshotImageOfType:str]; // expected-warning{{leak}} 766 [renderer createSnapshotImageOfType:str]; // expected-warning{{leak}} 767 [context createCGImage:img fromRect:rect]; // expected-warning{{leak}} 768 [context createCGImage:img fromRect:rect format:form colorSpace:cs]; // expected-warning{{leak}} 769} 770 771//===----------------------------------------------------------------------===// 772// <rdar://problem/6945561> -[CIContext createCGLayerWithSize:info:] 773// misinterpreted by clang scan-build 774//===----------------------------------------------------------------------===// 775 776void rdar6945561(CIContext *context, CGSize size, CFDictionaryRef d) { 777 [context createCGLayerWithSize:size info:d]; // expected-warning{{leak}} 778} 779 780//===----------------------------------------------------------------------===// 781// <rdar://problem/6961230> add knowledge of IOKit functions to retain/release 782// checker 783//===----------------------------------------------------------------------===// 784 785void IOBSDNameMatching_wrapper(mach_port_t masterPort, uint32_t options, const char * bsdName) { 786 IOBSDNameMatching(masterPort, options, bsdName); // expected-warning{{leak}} 787} 788 789void IOServiceMatching_wrapper(const char * name) { 790 IOServiceMatching(name); // expected-warning{{leak}} 791} 792 793void IOServiceNameMatching_wrapper(const char * name) { 794 IOServiceNameMatching(name); // expected-warning{{leak}} 795} 796 797CF_RETURNS_RETAINED CFDictionaryRef CreateDict(); 798 799void IOServiceAddNotification_wrapper(mach_port_t masterPort, const io_name_t notificationType, 800 mach_port_t wakePort, uintptr_t reference, io_iterator_t * notification ) { 801 802 CFDictionaryRef matching = CreateDict(); 803 CFRelease(matching); 804 IOServiceAddNotification(masterPort, notificationType, matching, // expected-warning{{used after it is released}} expected-warning{{deprecated}} 805 wakePort, reference, notification); 806} 807 808void IORegistryEntryIDMatching_wrapper(uint64_t entryID ) { 809 IORegistryEntryIDMatching(entryID); // expected-warning{{leak}} 810} 811 812void IOOpenFirmwarePathMatching_wrapper(mach_port_t masterPort, uint32_t options, 813 const char * path) { 814 IOOpenFirmwarePathMatching(masterPort, options, path); // expected-warning{{leak}} 815} 816 817void IOServiceGetMatchingService_wrapper(mach_port_t masterPort) { 818 CFDictionaryRef matching = CreateDict(); 819 IOServiceGetMatchingService(masterPort, matching); 820 CFRelease(matching); // expected-warning{{used after it is released}} 821} 822 823void IOServiceGetMatchingServices_wrapper(mach_port_t masterPort, io_iterator_t *existing) { 824 CFDictionaryRef matching = CreateDict(); 825 IOServiceGetMatchingServices(masterPort, matching, existing); 826 CFRelease(matching); // expected-warning{{used after it is released}} 827} 828 829void IOServiceAddMatchingNotification_wrapper(IONotificationPortRef notifyPort, const io_name_t notificationType, 830 IOServiceMatchingCallback callback, void * refCon, io_iterator_t * notification) { 831 832 CFDictionaryRef matching = CreateDict(); 833 IOServiceAddMatchingNotification(notifyPort, notificationType, matching, callback, refCon, notification); 834 CFRelease(matching); // expected-warning{{used after it is released}} 835} 836 837//===----------------------------------------------------------------------===// 838// Test of handling objects whose references "escape" to containers. 839//===----------------------------------------------------------------------===// 840 841// <rdar://problem/6539791> 842void rdar_6539791(CFMutableDictionaryRef y, void* key, void* val_key) { 843 CFMutableDictionaryRef x = CFDictionaryCreateMutable(kCFAllocatorDefault, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); 844 CFDictionaryAddValue(y, key, x); 845 CFRelease(x); // the dictionary keeps a reference, so the object isn't deallocated yet 846 signed z = 1; 847 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); 848 if (value) { 849 CFDictionaryAddValue(x, val_key, value); // no-warning 850 CFRelease(value); 851 CFDictionaryAddValue(y, val_key, value); // no-warning 852 } 853} 854 855// <rdar://problem/6560661> 856// Same issue, except with "AppendValue" functions. 857void rdar_6560661(CFMutableArrayRef x) { 858 signed z = 1; 859 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); 860 // CFArrayAppendValue keeps a reference to value. 861 CFArrayAppendValue(x, value); 862 CFRelease(value); 863 CFRetain(value); 864 CFRelease(value); // no-warning 865} 866 867// <rdar://problem/7152619> 868// Same issue, excwept with "CFAttributeStringSetAttribute". 869void rdar_7152619(CFStringRef str) { 870 CFAttributedStringRef string = CFAttributedStringCreate(kCFAllocatorDefault, str, 0); 871 CFMutableAttributedStringRef attrString = CFAttributedStringCreateMutableCopy(kCFAllocatorDefault, 100, string); 872 CFRelease(string); 873 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}} 874 CFAttributedStringSetAttribute(attrString, CFRangeMake(0, 1), str, number); 875 [number release]; 876 [number retain]; 877 CFRelease(attrString); 878} 879 880//===----------------------------------------------------------------------===// 881// Tests of ownership attributes. 882//===----------------------------------------------------------------------===// 883 884typedef NSString* MyStringTy; 885 886@protocol FooP; 887 888@interface TestOwnershipAttr : NSObject 889- (NSString*) returnsAnOwnedString NS_RETURNS_RETAINED; // no-warning 890- (NSString*) returnsAnOwnedCFString CF_RETURNS_RETAINED; // no-warning 891- (MyStringTy) returnsAnOwnedTypedString NS_RETURNS_RETAINED; // no-warning 892- (int) returnsAnOwnedInt NS_RETURNS_RETAINED; // expected-warning{{'ns_returns_retained' attribute only applies to functions or methods that return a pointer or Objective-C object}} 893@end 894 895static int ownership_attribute_doesnt_go_here NS_RETURNS_RETAINED; // expected-warning{{'ns_returns_retained' attribute only applies to function or method types}} 896 897void test_attr_1(TestOwnershipAttr *X) { 898 NSString *str = [X returnsAnOwnedString]; // expected-warning{{leak}} 899} 900 901void test_attr_1b(TestOwnershipAttr *X) { 902 NSString *str = [X returnsAnOwnedCFString]; // expected-warning{{leak}} 903} 904 905@interface MyClassTestCFAttr : NSObject {} 906- (NSDate*) returnsCFRetained CF_RETURNS_RETAINED; 907- (CFDateRef) returnsCFRetainedAsCF CF_RETURNS_RETAINED; 908- (NSDate*) alsoReturnsRetained; 909- (CFDateRef) alsoReturnsRetainedAsCF; 910- (NSDate*) returnsNSRetained NS_RETURNS_RETAINED; 911@end 912 913CF_RETURNS_RETAINED 914CFDateRef returnsRetainedCFDate() { 915 return CFDateCreate(0, CFAbsoluteTimeGetCurrent()); 916} 917 918@implementation MyClassTestCFAttr 919- (NSDate*) returnsCFRetained { 920 return (NSDate*) returnsRetainedCFDate(); // No leak. 921} 922 923- (CFDateRef) returnsCFRetainedAsCF { 924 return returnsRetainedCFDate(); // No leak. 925} 926 927 928- (NSDate*) alsoReturnsRetained { 929 return (NSDate*) returnsRetainedCFDate(); // expected-warning{{leak}} 930} 931 932- (CFDateRef) alsoReturnsRetainedAsCF { 933 return returnsRetainedCFDate(); // expected-warning{{leak}} 934} 935 936 937- (NSDate*) returnsNSRetained { 938 return (NSDate*) returnsRetainedCFDate(); // no-warning 939} 940@end 941 942