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