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