1 // RUN: rm -f %t.objc.plist %t.objcpp.plist
2 // RUN: %clang_analyze_cc1 -triple x86_64-apple-darwin10\
3 // RUN: -analyzer-checker=core,osx.coreFoundation.CFRetainRelease\
4 // RUN: -analyzer-checker=osx.cocoa.ClassRelease,osx.cocoa.RetainCount\
5 // RUN: -analyzer-checker=debug.ExprInspection -fblocks -verify %s\
6 // RUN: -Wno-objc-root-class -analyzer-output=plist -o %t.objc.plist
7 // RUN: %clang_analyze_cc1 -triple x86_64-apple-darwin10\
8 // RUN: -analyzer-checker=core,osx.coreFoundation.CFRetainRelease\
9 // RUN: -analyzer-checker=osx.cocoa.ClassRelease,osx.cocoa.RetainCount\
10 // RUN: -analyzer-checker=debug.ExprInspection -fblocks -verify %s\
11 // RUN: -Wno-objc-root-class -analyzer-output=plist -o %t.objcpp.plist\
12 // RUN: -x objective-c++ -std=gnu++98
13 // RUN: %clang_analyze_cc1 -triple x86_64-apple-darwin10\
14 // RUN: -analyzer-checker=core,osx.coreFoundation.CFRetainRelease\
15 // RUN: -analyzer-checker=osx.cocoa.ClassRelease,osx.cocoa.RetainCount\
16 // RUN: -analyzer-checker=debug.ExprInspection -fblocks -verify %s\
17 // RUN: -Wno-objc-root-class -x objective-c++ -std=gnu++98\
18 // RUN: -analyzer-config osx.cocoa.RetainCount:TrackNSCFStartParam=true\
19 // RUN: -DTRACK_START_PARAM
20 // RUN: %normalize_plist <%t.objcpp.plist | diff -ub %S/Inputs/expected-plists/retain-release.m.objcpp.plist -
21 // RUN: %normalize_plist <%t.objc.plist | diff -ub %S/Inputs/expected-plists/retain-release.m.objc.plist -
23 void clang_analyzer_eval(int);
25 #if __has_feature(attribute_ns_returns_retained)
26 #define NS_RETURNS_RETAINED __attribute__((ns_returns_retained))
28 #if __has_feature(attribute_cf_returns_retained)
29 #define CF_RETURNS_RETAINED __attribute__((cf_returns_retained))
31 #if __has_feature(attribute_ns_returns_not_retained)
32 #define NS_RETURNS_NOT_RETAINED __attribute__((ns_returns_not_retained))
34 #if __has_feature(attribute_cf_returns_not_retained)
35 #define CF_RETURNS_NOT_RETAINED __attribute__((cf_returns_not_retained))
37 #if __has_feature(attribute_ns_consumes_self)
38 #define NS_CONSUMES_SELF __attribute__((ns_consumes_self))
40 #if __has_feature(attribute_ns_consumed)
41 #define NS_CONSUMED __attribute__((ns_consumed))
43 #if __has_feature(attribute_cf_consumed)
44 #define CF_CONSUMED __attribute__((cf_consumed))
46 #if __has_attribute(ns_returns_autoreleased)
47 #define NS_RETURNS_AUTORELEASED __attribute__((ns_returns_autoreleased))
50 //===----------------------------------------------------------------------===//
51 // The following code is reduced using delta-debugging from Mac OS X headers:
53 // #include <Cocoa/Cocoa.h>
54 // #include <CoreFoundation/CoreFoundation.h>
55 // #include <DiskArbitration/DiskArbitration.h>
56 // #include <QuartzCore/QuartzCore.h>
57 // #include <Quartz/Quartz.h>
58 // #include <IOKit/IOKitLib.h>
60 // It includes the basic definitions for the test cases below.
61 //===----------------------------------------------------------------------===//
63 typedef unsigned int __darwin_natural_t;
64 typedef unsigned long uintptr_t;
65 typedef unsigned int uint32_t;
66 typedef unsigned long long uint64_t;
67 typedef unsigned int UInt32;
68 typedef signed long CFIndex;
69 typedef CFIndex CFByteOrder;
74 static __inline__ __attribute__((always_inline)) CFRange CFRangeMake(CFIndex loc, CFIndex len) {
80 typedef const void * CFTypeRef;
81 typedef const struct __CFString * CFStringRef;
82 typedef const struct __CFAllocator * CFAllocatorRef;
83 extern const CFAllocatorRef kCFAllocatorDefault;
85 extern CFTypeRef CFRetain(CFTypeRef cf);
86 extern void CFRelease(CFTypeRef cf);
87 extern CFTypeRef CFMakeCollectable(CFTypeRef cf);
88 extern CFTypeRef CFAutorelease(CFTypeRef CF_CONSUMED cf);
93 extern const CFArrayCallBacks kCFTypeArrayCallBacks;
94 typedef const struct __CFArray * CFArrayRef;
95 typedef struct __CFArray * CFMutableArrayRef;
96 extern CFMutableArrayRef CFArrayCreateMutable(CFAllocatorRef allocator, CFIndex capacity, const CFArrayCallBacks *callBacks);
97 extern const void *CFArrayGetValueAtIndex(CFArrayRef theArray, CFIndex idx);
98 extern void CFArrayAppendValue(CFMutableArrayRef theArray, const void *value);
101 CFDictionaryKeyCallBacks;
102 extern const CFDictionaryKeyCallBacks kCFTypeDictionaryKeyCallBacks;
105 CFDictionaryValueCallBacks;
106 extern const CFDictionaryValueCallBacks kCFTypeDictionaryValueCallBacks;
107 typedef const struct __CFDictionary * CFDictionaryRef;
108 typedef struct __CFDictionary * CFMutableDictionaryRef;
109 extern CFMutableDictionaryRef CFDictionaryCreateMutable(CFAllocatorRef allocator, CFIndex capacity, const CFDictionaryKeyCallBacks *keyCallBacks, const CFDictionaryValueCallBacks *valueCallBacks);
110 typedef UInt32 CFStringEncoding;
112 kCFStringEncodingMacRoman = 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 };
113 extern CFStringRef CFStringCreateWithCString(CFAllocatorRef alloc, const char *cStr, CFStringEncoding encoding);
114 typedef double CFTimeInterval;
115 typedef CFTimeInterval CFAbsoluteTime;
116 extern CFAbsoluteTime CFAbsoluteTimeGetCurrent(void);
117 typedef const struct __CFDate * CFDateRef;
118 extern CFDateRef CFDateCreate(CFAllocatorRef allocator, CFAbsoluteTime at);
119 extern CFAbsoluteTime CFDateGetAbsoluteTime(CFDateRef theDate);
120 typedef __darwin_natural_t natural_t;
121 typedef natural_t mach_port_name_t;
122 typedef mach_port_name_t mach_port_t;
123 typedef int kern_return_t;
124 typedef kern_return_t mach_error_t;
126 kCFNumberSInt8Type = 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 };
127 typedef CFIndex CFNumberType;
128 typedef const struct __CFNumber * CFNumberRef;
129 extern CFNumberRef CFNumberCreate(CFAllocatorRef allocator, CFNumberType theType, const void *valuePtr);
130 typedef const struct __CFAttributedString *CFAttributedStringRef;
131 typedef struct __CFAttributedString *CFMutableAttributedStringRef;
132 extern CFAttributedStringRef CFAttributedStringCreate(CFAllocatorRef alloc, CFStringRef str, CFDictionaryRef attributes) ;
133 extern CFMutableAttributedStringRef CFAttributedStringCreateMutableCopy(CFAllocatorRef alloc, CFIndex maxLength, CFAttributedStringRef aStr) ;
134 extern void CFAttributedStringSetAttribute(CFMutableAttributedStringRef aStr, CFRange range, CFStringRef attrName, CFTypeRef value) ;
135 typedef signed char BOOL;
136 typedef unsigned long NSUInteger;
137 @class NSString, Protocol;
138 extern void NSLog(NSString *format, ...) __attribute__((format(__NSString__, 1, 2)));
139 typedef struct _NSZone NSZone;
140 @class NSInvocation, NSMethodSignature, NSCoder, NSString, NSEnumerator;
142 - (BOOL)isEqual:(id)object;
144 - (oneway void)release;
146 - (NSString *)description;
150 - (id)copyWithZone:(NSZone *)zone;
152 @protocol NSMutableCopying - (id)mutableCopyWithZone:(NSZone *)zone;
154 @protocol NSCoding - (void)encodeWithCoder:(NSCoder *)aCoder;
156 @interface NSObject <NSObject> {}
157 + (id)allocWithZone:(NSZone *)zone;
162 @interface NSObject (NSCoderMethods)
163 - (id)awakeAfterUsingCoder:(NSCoder *)aDecoder;
165 extern id NSAllocateObject(Class aClass, NSUInteger extraBytes, NSZone *zone);
168 NSFastEnumerationState;
169 @protocol NSFastEnumeration
170 - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len;
172 @class NSString, NSDictionary;
173 @interface NSValue : NSObject <NSCopying, NSCoding> - (void)getValue:(void *)value;
175 @interface NSNumber : NSValue
177 - (id)initWithInt:(int)value;
178 + (NSNumber *)numberWithInt:(int)value;
181 @interface NSArray : NSObject <NSCopying, NSMutableCopying, NSCoding, NSFastEnumeration>
183 - (id)initWithObjects:(const id [])objects count:(NSUInteger)cnt;
184 + (id)arrayWithObject:(id)anObject;
185 + (id)arrayWithObjects:(const id [])objects count:(NSUInteger)cnt;
186 + (id)arrayWithObjects:(id)firstObj, ... __attribute__((sentinel(0,1)));
187 - (id)initWithObjects:(id)firstObj, ... __attribute__((sentinel(0,1)));
188 - (id)initWithArray:(NSArray *)array;
189 @end @interface NSArray (NSArrayCreation) + (id)array;
190 @end @interface NSAutoreleasePool : NSObject {
193 @end extern NSString * const NSBundleDidLoadNotification;
194 typedef double NSTimeInterval;
195 @interface NSDate : NSObject <NSCopying, NSCoding> - (NSTimeInterval)timeIntervalSinceReferenceDate;
196 @end typedef unsigned short unichar;
197 @interface NSString : NSObject <NSCopying, NSMutableCopying, NSCoding>
198 - (NSUInteger)length;
199 - (NSString *)stringByAppendingString:(NSString *)aString;
200 - ( const char *)UTF8String;
201 - (id)initWithUTF8String:(const char *)nullTerminatedCString;
202 + (id)stringWithUTF8String:(const char *)nullTerminatedCString;
203 @end @class NSString, NSURL, NSError;
204 @interface NSData : NSObject <NSCopying, NSMutableCopying, NSCoding> - (NSUInteger)length;
205 + (id)dataWithBytesNoCopy:(void *)bytes length:(NSUInteger)length;
206 + (id)dataWithBytesNoCopy:(void *)bytes length:(NSUInteger)length freeWhenDone:(BOOL)b;
207 @end @class NSLocale, NSDate, NSCalendar, NSTimeZone, NSError, NSArray, NSMutableDictionary;
208 @interface NSDictionary : NSObject <NSCopying, NSMutableCopying, NSCoding, NSFastEnumeration>
210 + (id)dictionaryWithObjects:(NSArray *)objects forKeys:(NSArray *)keys;
211 + (id)dictionaryWithObjects:(const id [])objects forKeys:(const id <NSCopying> [])keys count:(NSUInteger)cnt;
213 @interface NSMutableDictionary : NSDictionary - (void)removeObjectForKey:(id)aKey;
214 - (void)setObject:(id)anObject forKey:(id)aKey;
216 @interface NSMutableDictionary (NSMutableDictionaryCreation) + (id)dictionaryWithCapacity:(NSUInteger)numItems;
219 @interface NSNull : NSObject
223 typedef double CGFloat;
226 typedef struct CGSize CGSize;
229 typedef struct CGRect CGRect;
230 typedef mach_port_t io_object_t;
231 typedef char io_name_t[128];
232 typedef io_object_t io_iterator_t;
233 typedef io_object_t io_service_t;
234 typedef struct IONotificationPort * IONotificationPortRef;
235 typedef void (*IOServiceMatchingCallback)( void * refcon, io_iterator_t iterator );
236 io_service_t IOServiceGetMatchingService( mach_port_t mainPort, CFDictionaryRef matching );
237 kern_return_t IOServiceGetMatchingServices( mach_port_t mainPort, CFDictionaryRef matching, io_iterator_t * existing );
238 kern_return_t IOServiceAddNotification( mach_port_t mainPort, const io_name_t notificationType, CFDictionaryRef matching, mach_port_t wakePort, uintptr_t reference, io_iterator_t * notification ) __attribute__((deprecated)); // expected-note {{'IOServiceAddNotification' has been explicitly marked deprecated here}}
239 kern_return_t IOServiceAddMatchingNotification( IONotificationPortRef notifyPort, const io_name_t notificationType, CFDictionaryRef matching, IOServiceMatchingCallback callback, void * refCon, io_iterator_t * notification );
240 CFMutableDictionaryRef IOServiceMatching( const char * name );
241 CFMutableDictionaryRef IOServiceNameMatching( const char * name );
242 CFMutableDictionaryRef IOBSDNameMatching( mach_port_t mainPort, uint32_t options, const char * bsdName );
243 CFMutableDictionaryRef IOOpenFirmwarePathMatching( mach_port_t mainPort, uint32_t options, const char * path );
244 CFMutableDictionaryRef IORegistryEntryIDMatching( uint64_t entryID );
245 typedef struct __DASession * DASessionRef;
246 extern DASessionRef DASessionCreate( CFAllocatorRef allocator );
247 typedef struct __DADisk * DADiskRef;
248 extern DADiskRef DADiskCreateFromBSDName( CFAllocatorRef allocator, DASessionRef session, const char * name );
249 extern DADiskRef DADiskCreateFromIOMedia( CFAllocatorRef allocator, DASessionRef session, io_service_t media );
250 extern CFDictionaryRef DADiskCopyDescription( DADiskRef disk );
251 extern DADiskRef DADiskCopyWholeDisk( DADiskRef disk );
252 @interface NSTask : NSObject - (id)init;
253 @end typedef struct CGColorSpace *CGColorSpaceRef;
254 typedef struct CGImage *CGImageRef;
255 typedef struct CGLayer *CGLayerRef;
256 @interface NSResponder : NSObject <NSCoding> {
258 @end @protocol NSAnimatablePropertyContainer - (id)animator;
259 @end extern NSString *NSAnimationTriggerOrderIn ;
260 @interface NSView : NSResponder <NSAnimatablePropertyContainer> {
262 @end @protocol NSValidatedUserInterfaceItem - (SEL)action;
263 @end @protocol NSUserInterfaceValidations - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)anItem;
264 @end @class NSDate, NSDictionary, NSError, NSException, NSNotification;
265 @class NSTextField, NSPanel, NSArray, NSWindow, NSImage, NSButton, NSError;
266 @interface NSApplication : NSResponder <NSUserInterfaceValidations> {
268 - (void)beginSheet:(NSWindow *)sheet modalForWindow:(NSWindow *)docWindow modalDelegate:(id)modalDelegate didEndSelector:(SEL)didEndSelector contextInfo:(void *)contextInfo;
270 NSTerminateCancel = 0, NSTerminateNow = 1, NSTerminateLater = 2 };
271 typedef NSUInteger NSApplicationTerminateReply;
272 @protocol NSApplicationDelegate <NSObject> @optional - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender;
273 @end @class NSAttributedString, NSEvent, NSFont, NSFormatter, NSImage, NSMenu, NSText, NSView, NSTextView;
274 @interface NSCell : NSObject <NSCopying, NSCoding> {
280 @interface CIImage : NSObject <NSCoding, NSCopying> {
282 typedef int CIFormat;
284 kDAReturnSuccess = 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 };
285 typedef mach_error_t DAReturn;
286 typedef const struct __DADissenter * DADissenterRef;
287 extern DADissenterRef DADissenterCreate( CFAllocatorRef allocator, DAReturn status, CFStringRef string );
288 @interface CIContext: NSObject {
290 - (CGImageRef)createCGImage:(CIImage *)im fromRect:(CGRect)r;
291 - (CGImageRef)createCGImage:(CIImage *)im fromRect:(CGRect)r format:(CIFormat)f colorSpace:(CGColorSpaceRef)cs;
292 - (CGLayerRef)createCGLayerWithSize:(CGSize)size info:(CFDictionaryRef)d;
293 @end extern NSString* const QCRendererEventKey;
294 @protocol QCCompositionRenderer - (NSDictionary*) attributes;
295 @end @interface QCRenderer : NSObject <QCCompositionRenderer> {
297 - (id) createSnapshotImageOfType:(NSString*)type;
298 @end extern NSString* const QCViewDidStartRenderingNotification;
299 @interface QCView : NSView <QCCompositionRenderer> {
301 - (id) createSnapshotImageOfType:(NSString*)type;
303 ICEXIFOrientation1 = 1, ICEXIFOrientation2 = 2, ICEXIFOrientation3 = 3, ICEXIFOrientation4 = 4, ICEXIFOrientation5 = 5, ICEXIFOrientation6 = 6, ICEXIFOrientation7 = 7, ICEXIFOrientation8 = 8, };
305 @protocol ICDeviceDelegate <NSObject> @required - (void)didRemoveDevice:(ICDevice*)device;
306 @end extern NSString *const ICScannerStatusWarmingUp;
307 @class ICScannerDevice;
308 @protocol ICScannerDeviceDelegate <ICDeviceDelegate> @optional - (void)scannerDeviceDidBecomeAvailable:(ICScannerDevice*)scanner;
311 typedef long unsigned int __darwin_size_t;
312 typedef __darwin_size_t size_t;
313 typedef unsigned long CFTypeID;
318 typedef struct CGPoint CGPoint;
319 typedef struct CGGradient *CGGradientRef;
320 typedef uint32_t CGGradientDrawingOptions;
321 extern CFTypeID CGGradientGetTypeID(void);
322 extern CGGradientRef CGGradientCreateWithColorComponents(CGColorSpaceRef
323 space, const CGFloat components[], const CGFloat locations[], size_t count);
324 extern CGGradientRef CGGradientCreateWithColors(CGColorSpaceRef space,
325 CFArrayRef colors, const CGFloat locations[]);
326 extern CGGradientRef CGGradientRetain(CGGradientRef gradient);
327 extern void CGGradientRelease(CGGradientRef gradient);
328 typedef struct CGContext *CGContextRef;
329 extern void CGContextDrawLinearGradient(CGContextRef context,
330 CGGradientRef gradient, CGPoint startPoint, CGPoint endPoint,
331 CGGradientDrawingOptions options);
332 extern CGColorSpaceRef CGColorSpaceCreateDeviceRGB(void);
334 @interface NSMutableArray : NSObject
335 - (void)addObject:(id)object;
339 // This is how NSMakeCollectable is declared in the OS X 10.8 headers.
340 id NSMakeCollectable(CFTypeRef __attribute__((cf_consumed))) __attribute__((ns_returns_retained));
342 typedef const struct __CFUUID * CFUUIDRef;
345 void *CFPlugInInstanceCreate(CFAllocatorRef allocator, CFUUIDRef factoryUUID, CFUUIDRef typeUUID);
350 //===----------------------------------------------------------------------===//
352 //===----------------------------------------------------------------------===//
354 CFAbsoluteTime f1(void) {
355 CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
356 CFDateRef date = CFDateCreate(0, t);
359 CFDateGetAbsoluteTime(date); // no-warning
361 t = CFDateGetAbsoluteTime(date); // expected-warning{{Reference-counted object is used after it is released}}
365 CFAbsoluteTime f2(void) {
366 CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
367 CFDateRef date = CFDateCreate(0, t);
368 [((NSDate*) date) retain];
370 CFDateGetAbsoluteTime(date); // no-warning
371 [((NSDate*) date) release];
372 t = CFDateGetAbsoluteTime(date); // expected-warning{{Reference-counted object is used after it is released}}
379 // Test to see if we suppress an error when we store the pointer
382 CFAbsoluteTime f3(void) {
383 CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
384 CFDateRef date = CFDateCreate(0, t);
385 [((NSDate*) date) retain];
387 CFDateGetAbsoluteTime(date); // no-warning
388 global_x = (NSDate*) date;
389 [((NSDate*) date) release];
390 t = CFDateGetAbsoluteTime(date); // no-warning
394 //---------------------------------------------------------------------------
395 // Test case 'f4' differs for region store and basic store. See
396 // retain-release-region-store.m and retain-release-basic-store.m.
397 //---------------------------------------------------------------------------
401 CFAbsoluteTime f5(int x) {
402 CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
403 CFDateRef date = CFDateCreate(0, t); // expected-warning{{leak}}
411 // Test a leak involving the return.
413 CFDateRef f6(int x) {
414 CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent()); // expected-warning{{leak}}
419 // Test a leak involving an overwrite.
422 CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent()); //expected-warning{{leak}}
424 date = CFDateCreate(0, CFAbsoluteTimeGetCurrent()); // expected-warning {{leak}}
428 // Generalization of Create rule. MyDateCreate returns a CFXXXTypeRef, and
429 // has the word create.
430 CFDateRef MyDateCreate(void);
433 CFDateRef date = MyDateCreate(); // expected-warning{{leak}}
438 __attribute__((cf_returns_retained)) CFDateRef f9(void) {
439 CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent()); // no-warning
441 // When allocations fail, CFDateCreate can return null.
442 if (!date) *p = 1; // expected-warning{{null}}
446 // Handle DiskArbitration API:
448 // http://developer.apple.com/DOCUMENTATION/DARWIN/Reference/DiscArbitrationFramework/
450 void f10(io_service_t media, DADiskRef d, CFStringRef s) {
451 DADiskRef disk = DADiskCreateFromBSDName(kCFAllocatorDefault, 0, "hello"); // expected-warning{{leak}}
452 if (disk) NSLog(@"ok");
454 disk = DADiskCreateFromIOMedia(kCFAllocatorDefault, 0, media); // expected-warning{{leak}}
455 if (disk) NSLog(@"ok");
457 CFDictionaryRef dict = DADiskCopyDescription(d); // expected-warning{{leak}}
458 if (dict) NSLog(@"ok");
460 disk = DADiskCopyWholeDisk(d); // expected-warning{{leak}}
461 if (disk) NSLog(@"ok");
463 DADissenterRef dissenter = DADissenterCreate(kCFAllocatorDefault, // expected-warning{{leak}}
464 kDAReturnSuccess, s);
465 if (dissenter) NSLog(@"ok");
467 DASessionRef session = DASessionCreate(kCFAllocatorDefault); // expected-warning{{leak}}
468 if (session) NSLog(@"ok");
472 // Handle CoreMedia API
475 typedef struct CMFoo *CMFooRef;
477 CMFooRef CMCreateFooRef(void);
478 CMFooRef CMGetFooRef(void);
480 typedef signed long SInt32;
481 typedef SInt32 OSStatus;
482 OSStatus CMCreateFooAndReturnViaOutParameter(CMFooRef * CF_RETURNS_RETAINED fooOut);
484 void testLeakCoreMediaReferenceType(void) {
485 CMFooRef f = CMCreateFooRef(); // expected-warning{{leak}}
488 void testOverReleaseMediaReferenceType(void) {
489 CMFooRef f = CMGetFooRef();
490 CFRelease(f); // expected-warning{{Incorrect decrement of the reference count}}
493 void testOkToReleaseReturnsRetainedOutParameter(void) {
495 OSStatus status = CMCreateFooAndReturnViaOutParameter(&foo);
500 CFRelease(foo); // no-warning
503 void testLeakWithReturnsRetainedOutParameter(void) {
505 OSStatus status = CMCreateFooAndReturnViaOutParameter(&foo);
510 // FIXME: Ideally we would report a leak here since it is the caller's
511 // responsibility to release 'foo'. However, we don't currently have
512 // a mechanism in this checker to only require a release when a successful
513 // status is returned.
516 typedef CFTypeRef CMBufferRef;
518 typedef CFTypeRef *CMBufferQueueRef;
520 CMBufferRef CMBufferQueueDequeueAndRetain(CMBufferQueueRef);
522 void testCMBufferQueueDequeueAndRetain(CMBufferQueueRef queue) {
523 CMBufferRef buffer = CMBufferQueueDequeueAndRetain(queue); // expected-warning{{Potential leak of an object stored into 'buffer'}}
524 // There's a state split due to the eagerly-assume behavior.
525 // The point here is that we don't treat CMBufferQueueDequeueAndRetain
526 // as some sort of CFRetain() that returns its argument.
527 clang_analyzer_eval((CMFooRef)buffer == (CMFooRef)queue); // expected-warning{{TRUE}}
528 // expected-warning@-1{{FALSE}}
531 // Test retain/release checker with CFString and CFMutableArray.
534 CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
537 CFStringRef s1 = CFStringCreateWithCString(0, "hello world",
538 kCFStringEncodingUTF8);
540 // Add the string to the array.
541 CFArrayAppendValue(A, s1);
543 // Decrement the reference count.
544 CFRelease(s1); // no-warning
546 // Get the string. We don't own it.
547 s1 = (CFStringRef) CFArrayGetValueAtIndex(A, 0);
549 // Release the array.
550 CFRelease(A); // no-warning
552 // Release the string. This is a bug.
553 CFRelease(s1); // expected-warning{{Incorrect decrement of the reference count}}
556 // PR 3337: Handle functions declared using typedefs.
557 typedef CFTypeRef CREATEFUN(void);
558 CREATEFUN MyCreateFun;
561 CFTypeRef o = MyCreateFun(); // expected-warning {{leak}}
564 void f13_autorelease(void) {
565 CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
566 [(id) A autorelease]; // no-warning
569 void f13_autorelease_b(void) {
570 CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
571 [(id) A autorelease];
572 [(id) A autorelease];
573 } // expected-warning{{Object autoreleased too many times}}
575 CFMutableArrayRef f13_autorelease_c(void) {
576 CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
577 [(id) A autorelease];
578 [(id) A autorelease];
579 return A; // expected-warning{{Object autoreleased too many times}}
582 CFMutableArrayRef f13_autorelease_d(void) {
583 CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
584 [(id) A autorelease];
585 [(id) A autorelease];
586 CFMutableArrayRef B = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning{{Object autoreleased too many times}}
587 CFRelease(B); // no-warning
592 // This case exercises the logic where the leak site is the same as the allocation site.
593 void f14_leakimmediately(void) {
594 CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning{{leak}}
597 // Test that we track an allocated object beyond the point where the *name*
598 // of the variable storing the reference is no longer live.
601 CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
602 CFMutableArrayRef *B = &A;
603 // At this point, the name 'A' is no longer live.
604 CFRelease(*B); // no-warning
607 // Test when we pass NULL to CFRetain/CFRelease/CFMakeCollectable/CFAutorelease.
608 void f16(int x, CFTypeRef p) {
614 CFRelease(p); // expected-warning{{Null pointer argument in call to CFRelease}}
617 CFRetain(p); // expected-warning{{Null pointer argument in call to CFRetain}}
620 CFMakeCollectable(p); // expected-warning{{Null pointer argument in call to CFMakeCollectable}}
623 CFAutorelease(p); // expected-warning{{Null pointer argument in call to CFAutorelease}}
630 #ifdef TRACK_START_PARAM
631 @interface TestParam : NSObject
632 - (void) f:(id) object;
635 @implementation TestParam
636 - (void) f:(id) object { // expected-warning{{Potential leak of an object of type 'id'}}
643 // Test that an object is non-null after CFRetain/CFRelease/CFMakeCollectable/CFAutorelease.
644 void f17(int x, CFTypeRef p) {
645 #ifdef TRACK_START_PARAM
646 // expected-warning@-2{{Potential leak of an object of type 'CFTypeRef'}}
651 #ifdef TRACK_START_PARAM
652 // expected-warning@-2{{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
655 CFRelease(0); // no-warning
660 CFRetain(0); // no-warning
663 CFMakeCollectable(p);
665 CFMakeCollectable(0); // no-warning
670 CFAutorelease(0); // no-warning
676 #ifdef TRACK_START_PARAM
677 // expected-warning@-2{{Object autoreleased too many times}}
680 __attribute__((annotate("rc_ownership_returns_retained"))) isl_basic_map *isl_basic_map_cow(__attribute__((annotate("rc_ownership_consumed"))) isl_basic_map *bmap);
682 // Test custom diagnostics for generalized objects.
683 void f18(__attribute__((annotate("rc_ownership_consumed"))) isl_basic_map *bmap) {
684 // After this call, 'bmap' has a +1 reference count.
685 bmap = isl_basic_map_cow(bmap); // expected-warning {{Potential leak of an object}}
688 // Test basic tracking of ivars associated with 'self'. For the retain/release
689 // checker we currently do not want to flag leaks associated with stores
690 // of tracked objects to ivars.
691 @interface SelfIvarTest : NSObject {
694 - (void)test_self_tracking;
697 @implementation SelfIvarTest
698 - (void)test_self_tracking {
699 myObj = (id) CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
703 // Test return of non-owned objects in contexts where an owned object
705 @interface TestReturnNotOwnedWhenExpectedOwned
706 - (NSString*)newString;
709 @implementation TestReturnNotOwnedWhenExpectedOwned
710 - (NSString*)newString {
711 NSString *s = [NSString stringWithUTF8String:"hello"];
712 return s; // expected-warning{{Object with a +0 retain count returned to caller where a +1 (owning) retain count is expected}}
718 static void rdar_6659160(char *inkind, char *inname)
720 // We currently expect that [NSObject alloc] cannot fail. This
721 // will be a toggled flag in the future. It can indeed return null, but
722 // Cocoa programmers generally aren't expected to reason about out-of-memory
724 NSString *kind = [[NSString alloc] initWithUTF8String:inkind]; // expected-warning{{leak}}
726 // We do allow stringWithUTF8String to fail. This isn't really correct, as
727 // far as returning 0. In most error conditions it will throw an exception.
728 // If allocation fails it could return 0, but again this
730 NSString *name = [NSString stringWithUTF8String:inname];
734 const char *kindC = 0;
735 const char *nameC = 0;
737 // In both cases, we cannot reach a point down below where we
738 // dereference kindC or nameC with either being null. This is because
739 // we assume that [NSObject alloc] doesn't fail and that we have the guard
743 kindC = [kind UTF8String];
745 nameC = [name UTF8String];
746 if(!isFoo(kindC[0])) // expected-warning{{null}}
748 if(!isFoo(nameC[0])) // no-warning
752 [name release]; // expected-warning{{Incorrect decrement of the reference count}}
755 // PR 3677 - 'allocWithZone' should be treated as following the Cocoa naming
756 // conventions with respect to 'return'ing ownership.
757 @interface PR3677: NSObject @end
758 @implementation PR3677
759 + (id)allocWithZone:(NSZone *)inZone {
760 return [super allocWithZone:inZone]; // no-warning
764 // PR 3820 - Reason about calls to -dealloc
765 void pr3820_DeallocInsteadOfRelease(void)
767 id foo = [[NSString alloc] init]; // no-warning
769 // foo is not leaked, since it has been deallocated.
772 void pr3820_ReleaseAfterDealloc(void)
774 id foo = [[NSString alloc] init];
776 [foo release]; // expected-warning{{used after it is release}}
777 // NSInternalInconsistencyException: message sent to deallocated object
780 void pr3820_DeallocAfterRelease(void)
782 NSLog(@"\n\n[%s]", __FUNCTION__);
783 id foo = [[NSString alloc] init];
785 [foo dealloc]; // expected-warning{{used after it is released}}
786 // message sent to released object
789 // The problem here is that 'length' binds to'($0 - 1)' after '--length', but
790 // SimpleConstraintManager doesn't know how to reason about
791 // '($0 - 1) > constant'. As a temporary hack, we drop the value of '($0 - 1)'
792 // and conjure a new symbol.
793 void rdar6704930(unsigned char *s, unsigned int length) {
801 name = [[NSString alloc] init]; // no-warning
807 if ((length == 0) && (name != 0)) {
811 if (length == 0) { // no ':' found -> use it all as name
812 name = [[NSString alloc] init]; // no-warning
822 //===----------------------------------------------------------------------===//
823 // One build of the analyzer accidentally stopped tracking the allocated
824 // object after the 'retain'.
825 //===----------------------------------------------------------------------===//
827 @interface rdar_6833332 : NSObject <NSApplicationDelegate> {
830 @property (nonatomic, retain) NSWindow *window;
833 @implementation rdar_6833332
835 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
836 NSMutableDictionary *dict = [[NSMutableDictionary dictionaryWithCapacity:4] retain]; // expected-warning{{leak}}
838 [dict setObject:@"foo" forKey:@"bar"];
847 - (void)radar10102244 {
848 NSMutableDictionary *dict = [[NSMutableDictionary dictionaryWithCapacity:4] retain]; // expected-warning{{leak}}
850 NSLog(@"%@", window);
854 //===----------------------------------------------------------------------===//
855 // clang checker fails to catch use-after-release
856 //===----------------------------------------------------------------------===//
857 int rdar_6257780_Case1(void) {
858 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
859 NSArray *array = [NSArray array];
860 [array release]; // expected-warning{{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
865 //===----------------------------------------------------------------------===//
866 // Analyzer is confused about NSAutoreleasePool -allocWithZone:.
867 //===----------------------------------------------------------------------===//
868 void rdar_10640253_autorelease_allocWithZone(void) {
869 NSAutoreleasePool *pool = [[NSAutoreleasePool allocWithZone:(NSZone*)0] init];
873 //===----------------------------------------------------------------------===//
874 // Checker should understand new/setObject:/release constructs
875 //===----------------------------------------------------------------------===//
876 void rdar_6866843(void) {
877 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
878 NSMutableDictionary* dictionary = [[NSMutableDictionary alloc] init];
879 NSArray* array = [[NSArray alloc] init];
880 [dictionary setObject:array forKey:@"key"];
882 // Using 'array' here should be fine
883 NSLog(@"array = %@\n", array); // no-warning
884 // Now the array is released
885 [dictionary release];
890 //===----------------------------------------------------------------------===//
891 // Classes typedef-ed to CF objects should get the same treatment as CF objects
892 //===----------------------------------------------------------------------===//
894 typedef CFTypeRef OtherRef;
896 @interface RDar6877235 : NSObject {}
897 - (CFTypeRef)_copyCFTypeRef;
898 - (OtherRef)_copyOtherRef;
901 @implementation RDar6877235
902 - (CFTypeRef)_copyCFTypeRef {
903 return [[NSString alloc] init]; // no-warning
905 - (OtherRef)_copyOtherRef {
906 return [[NSString alloc] init]; // no-warning
910 //===----------------------------------------------------------------------===//
911 // False positive - init method returns an object owned by caller.
912 //===----------------------------------------------------------------------===//
913 @interface RDar6320065 : NSObject {
916 - (id)initReturningNewClass;
917 - (id)_initReturningNewClassBad;
918 - (id)initReturningNewClassBad2;
921 @interface RDar6320065Subclass : RDar6320065
924 @implementation RDar6320065
925 - (id)initReturningNewClass {
927 self = [[RDar6320065Subclass alloc] init]; // no-warning
930 - (id)_initReturningNewClassBad {
932 [[RDar6320065Subclass alloc] init]; // expected-warning {{leak}}
935 - (id)initReturningNewClassBad2 {
937 self = [[RDar6320065Subclass alloc] init];
938 return [self autorelease]; // expected-warning{{Object with a +0 retain count returned to caller where a +1 (owning) retain count is expected}}
943 @implementation RDar6320065Subclass
946 int RDar6320065_test(void) {
947 RDar6320065 *test = [[RDar6320065 alloc] init]; // no-warning
952 //===----------------------------------------------------------------------===//
953 // -awakeAfterUsingCoder: returns an owned object and claims the receiver
954 //===----------------------------------------------------------------------===//
955 @interface RDar7129086 : NSObject {} @end
956 @implementation RDar7129086
957 - (id)awakeAfterUsingCoder:(NSCoder *)aDecoder {
958 [self release]; // no-warning
959 return [NSString alloc]; // no-warning
963 //===----------------------------------------------------------------------===//
964 // [NSData dataWithBytesNoCopy] does not return a retained object
965 //===----------------------------------------------------------------------===//
966 @interface RDar6859457 : NSObject {}
967 - (NSString*) NoCopyString;
968 - (NSString*) noCopyString;
971 @implementation RDar6859457
972 - (NSString*) NoCopyString { return [[NSString alloc] init]; } // expected-warning{{leak}}
973 - (NSString*) noCopyString { return [[NSString alloc] init]; } // expected-warning{{leak}}
976 void test_RDar6859457(RDar6859457 *x, void *bytes, NSUInteger dataLength) {
977 [x NoCopyString]; // expected-warning{{leak}}
978 [x noCopyString]; // expected-warning{{leak}}
979 [NSData dataWithBytesNoCopy:bytes length:dataLength]; // no-warning
980 [NSData dataWithBytesNoCopy:bytes length:dataLength freeWhenDone:1]; // no-warning
983 //===----------------------------------------------------------------------===//
984 // PR 4230 - an autorelease pool is not necessarily leaked during a premature
986 //===----------------------------------------------------------------------===//
988 static void PR4230(void)
990 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // no-warning
991 NSString *object = [[[NSString alloc] init] autorelease]; // no-warning
995 static void PR4230_new(void)
997 NSAutoreleasePool *pool = [NSAutoreleasePool new]; // no-warning
998 NSString *object = [[[NSString alloc] init] autorelease]; // no-warning
1002 //===----------------------------------------------------------------------===//
1003 // Method name that has a null IdentifierInfo* for its first selector slot.
1004 // This test just makes sure that we handle it.
1005 //===----------------------------------------------------------------------===//
1007 @interface TestNullIdentifier
1010 @implementation TestNullIdentifier
1011 + (id):(int)x, ... {
1012 return [[NSString alloc] init]; // expected-warning{{leak}}
1016 //===----------------------------------------------------------------------===//
1017 // Don't flag leaks for return types that cannot be determined to be CF types.
1018 //===----------------------------------------------------------------------===//
1020 // We don't know if 'struct s6893565' represents a Core Foundation type, so
1021 // we shouldn't emit an error here.
1022 typedef struct s6893565* TD6893565;
1024 @interface RDar6893565 {}
1025 -(TD6893565)newThing;
1028 @implementation RDar6893565
1029 -(TD6893565)newThing {
1030 return (TD6893565) [[NSString alloc] init]; // no-warning
1034 //===----------------------------------------------------------------------===//
1035 // clang: false positives w/QC and CoreImage methods
1036 //===----------------------------------------------------------------------===//
1037 void rdar6902710(QCView *view, QCRenderer *renderer, CIContext *context,
1038 NSString *str, CIImage *img, CGRect rect,
1039 CIFormat form, CGColorSpaceRef cs) {
1040 [view createSnapshotImageOfType:str]; // expected-warning{{leak}}
1041 [renderer createSnapshotImageOfType:str]; // expected-warning{{leak}}
1042 [context createCGImage:img fromRect:rect]; // expected-warning{{leak}}
1043 [context createCGImage:img fromRect:rect format:form colorSpace:cs]; // expected-warning{{leak}}
1046 //===----------------------------------------------------------------------===//
1047 // -[CIContext createCGLayerWithSize:info:] misinterpreted by clang scan-build
1048 //===----------------------------------------------------------------------===//
1049 void rdar6945561(CIContext *context, CGSize size, CFDictionaryRef d) {
1050 [context createCGLayerWithSize:size info:d]; // expected-warning{{leak}}
1053 //===----------------------------------------------------------------------===//
1054 // Add knowledge of IOKit functions to retain/release checker.
1055 //===----------------------------------------------------------------------===//
1056 void IOBSDNameMatching_wrapper(mach_port_t mainPort, uint32_t options, const char * bsdName) {
1057 IOBSDNameMatching(mainPort, options, bsdName); // expected-warning{{leak}}
1060 void IOServiceMatching_wrapper(const char * name) {
1061 IOServiceMatching(name); // expected-warning{{leak}}
1064 void IOServiceNameMatching_wrapper(const char * name) {
1065 IOServiceNameMatching(name); // expected-warning{{leak}}
1068 CF_RETURNS_RETAINED CFDictionaryRef CreateDict(void);
1070 void IOServiceAddNotification_wrapper(mach_port_t mainPort, const io_name_t notificationType,
1071 mach_port_t wakePort, uintptr_t reference, io_iterator_t * notification ) {
1073 CFDictionaryRef matching = CreateDict();
1074 CFRelease(matching);
1075 IOServiceAddNotification(mainPort, notificationType, matching, // expected-warning{{used after it is released}} expected-warning{{deprecated}}
1076 wakePort, reference, notification);
1079 void IORegistryEntryIDMatching_wrapper(uint64_t entryID ) {
1080 IORegistryEntryIDMatching(entryID); // expected-warning{{leak}}
1083 void IOOpenFirmwarePathMatching_wrapper(mach_port_t mainPort, uint32_t options,
1084 const char * path) {
1085 IOOpenFirmwarePathMatching(mainPort, options, path); // expected-warning{{leak}}
1088 void IOServiceGetMatchingService_wrapper(mach_port_t mainPort) {
1089 CFDictionaryRef matching = CreateDict();
1090 IOServiceGetMatchingService(mainPort, matching);
1091 CFRelease(matching); // expected-warning{{used after it is released}}
1094 void IOServiceGetMatchingServices_wrapper(mach_port_t mainPort, io_iterator_t *existing) {
1095 CFDictionaryRef matching = CreateDict();
1096 IOServiceGetMatchingServices(mainPort, matching, existing);
1097 CFRelease(matching); // expected-warning{{used after it is released}}
1100 void IOServiceAddMatchingNotification_wrapper(IONotificationPortRef notifyPort, const io_name_t notificationType,
1101 IOServiceMatchingCallback callback, void * refCon, io_iterator_t * notification) {
1103 CFDictionaryRef matching = CreateDict();
1104 IOServiceAddMatchingNotification(notifyPort, notificationType, matching, callback, refCon, notification);
1105 CFRelease(matching); // expected-warning{{used after it is released}}
1108 //===----------------------------------------------------------------------===//
1109 // Test of handling objects whose references "escape" to containers.
1110 //===----------------------------------------------------------------------===//
1112 void CFDictionaryAddValue(CFMutableDictionaryRef, void *, void *);
1114 void rdar_6539791(CFMutableDictionaryRef y, void* key, void* val_key) {
1115 CFMutableDictionaryRef x = CFDictionaryCreateMutable(kCFAllocatorDefault, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
1116 CFDictionaryAddValue(y, key, x);
1117 CFRelease(x); // the dictionary keeps a reference, so the object isn't deallocated yet
1119 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z);
1121 CFDictionaryAddValue(x, val_key, (void*)value); // no-warning
1123 CFDictionaryAddValue(y, val_key, (void*)value); // no-warning
1127 // Same issue, except with "AppendValue" functions.
1128 void rdar_6560661(CFMutableArrayRef x) {
1130 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z);
1131 // CFArrayAppendValue keeps a reference to value.
1132 CFArrayAppendValue(x, value);
1135 CFRelease(value); // no-warning
1138 // Same issue, excwept with "CFAttributeStringSetAttribute".
1139 void rdar_7152619(CFStringRef str) {
1140 CFAttributedStringRef string = CFAttributedStringCreate(kCFAllocatorDefault, str, 0);
1141 CFMutableAttributedStringRef attrString = CFAttributedStringCreateMutableCopy(kCFAllocatorDefault, 100, string);
1143 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1144 CFAttributedStringSetAttribute(attrString, CFRangeMake(0, 1), str, number);
1147 CFRelease(attrString);
1150 //===----------------------------------------------------------------------===//
1151 // Test of handling CGGradientXXX functions.
1152 //===----------------------------------------------------------------------===//
1154 void rdar_7184450(CGContextRef myContext, CGFloat x, CGPoint myStartPoint,
1155 CGPoint myEndPoint) {
1156 size_t num_locations = 6;
1157 CGFloat locations[6] = { 0.0, 0.265, 0.28, 0.31, 0.36, 1.0 };
1158 CGFloat components[28] = { 239.0/256.0, 167.0/256.0, 170.0/256.0,
1160 207.0/255.0, 39.0/255.0, 39.0/255.0, x,
1161 147.0/255.0, 21.0/255.0, 22.0/255.0, x,
1162 175.0/255.0, 175.0/255.0, 175.0/255.0, x,
1163 255.0/255.0,255.0/255.0, 255.0/255.0, x,
1164 255.0/255.0,255.0/255.0, 255.0/255.0, x
1167 CGGradientRef myGradient =
1168 CGGradientCreateWithColorComponents(CGColorSpaceCreateDeviceRGB(), // expected-warning{{leak}}
1169 components, locations, num_locations);
1171 CGContextDrawLinearGradient(myContext, myGradient, myStartPoint, myEndPoint,
1173 CGGradientRelease(myGradient);
1176 void rdar_7184450_pos(CGContextRef myContext, CGFloat x, CGPoint myStartPoint,
1177 CGPoint myEndPoint) {
1178 size_t num_locations = 6;
1179 CGFloat locations[6] = { 0.0, 0.265, 0.28, 0.31, 0.36, 1.0 };
1180 CGFloat components[28] = { 239.0/256.0, 167.0/256.0, 170.0/256.0,
1182 207.0/255.0, 39.0/255.0, 39.0/255.0, x,
1183 147.0/255.0, 21.0/255.0, 22.0/255.0, x,
1184 175.0/255.0, 175.0/255.0, 175.0/255.0, x,
1185 255.0/255.0,255.0/255.0, 255.0/255.0, x,
1186 255.0/255.0,255.0/255.0, 255.0/255.0, x
1189 CGGradientRef myGradient =
1190 CGGradientCreateWithColorComponents(CGColorSpaceCreateDeviceRGB(), components, locations, num_locations); // expected-warning 2 {{leak}}
1192 CGContextDrawLinearGradient(myContext, myGradient, myStartPoint, myEndPoint,
1196 //===----------------------------------------------------------------------===//
1197 // clang false positive: retained instance passed to thread in pthread_create
1200 // Until we have full IPA, the analyzer should stop tracking the reference
1201 // count of objects passed to pthread_create.
1202 //===----------------------------------------------------------------------===//
1203 struct _opaque_pthread_t {};
1204 struct _opaque_pthread_attr_t {};
1205 typedef struct _opaque_pthread_t *__darwin_pthread_t;
1206 typedef struct _opaque_pthread_attr_t __darwin_pthread_attr_t;
1207 typedef __darwin_pthread_t pthread_t;
1208 typedef __darwin_pthread_attr_t pthread_attr_t;
1209 typedef unsigned long __darwin_pthread_key_t;
1210 typedef __darwin_pthread_key_t pthread_key_t;
1212 int pthread_create(pthread_t *, const pthread_attr_t *,
1213 void *(*)(void *), void *);
1215 int pthread_setspecific(pthread_key_t key, const void *value);
1217 void *rdar_7299394_start_routine(void *p) {
1221 void rdar_7299394(pthread_attr_t *attr, pthread_t *thread, void *args) {
1222 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1223 pthread_create(thread, attr, rdar_7299394_start_routine, number);
1225 void rdar_7299394_positive(pthread_attr_t *attr, pthread_t *thread) {
1226 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1229 //===----------------------------------------------------------------------===//
1230 // False positive with not understanding thread local storage.
1231 //===----------------------------------------------------------------------===//
1232 void rdar11282706(pthread_key_t key) {
1233 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1234 pthread_setspecific(key, (void*) number);
1237 //===----------------------------------------------------------------------===//
1238 // False leak associated with call to CVPixelBufferCreateWithBytes()
1240 // According to the Core Video Reference (ADC), CVPixelBufferCreateWithBytes and
1241 // CVPixelBufferCreateWithPlanarBytes can release (via a callback) the
1242 // pixel buffer object. These test cases show how the analyzer stops tracking
1243 // the reference count for the objects passed for this argument. This
1244 // could be made smarter.
1245 //===----------------------------------------------------------------------===//
1246 typedef int int32_t;
1247 typedef UInt32 FourCharCode;
1248 typedef FourCharCode OSType;
1249 typedef uint64_t CVOptionFlags;
1250 typedef int32_t CVReturn;
1251 typedef struct __CVBuffer *CVBufferRef;
1252 typedef CVBufferRef CVImageBufferRef;
1253 typedef CVImageBufferRef CVPixelBufferRef;
1254 typedef CVBufferRef CMTaggedBufferGroupRef;
1255 typedef void (*CVPixelBufferReleaseBytesCallback)( void *releaseRefCon, const void *baseAddress );
1257 extern CVReturn CVPixelBufferCreateWithBytes(CFAllocatorRef allocator,
1260 OSType pixelFormatType,
1263 CVPixelBufferReleaseBytesCallback releaseCallback,
1264 void *releaseRefCon,
1265 CFDictionaryRef pixelBufferAttributes,
1266 CVPixelBufferRef *pixelBufferOut) ;
1268 typedef void (*CVPixelBufferReleasePlanarBytesCallback)( void *releaseRefCon, const void *dataPtr, size_t dataSize, size_t numberOfPlanes, const void *planeAddresses[] );
1270 extern CVReturn CVPixelBufferCreateWithPlanarBytes(CFAllocatorRef allocator,
1273 OSType pixelFormatType,
1276 size_t numberOfPlanes,
1277 void *planeBaseAddress[],
1278 size_t planeWidth[],
1279 size_t planeHeight[],
1280 size_t planeBytesPerRow[],
1281 CVPixelBufferReleasePlanarBytesCallback releaseCallback,
1282 void *releaseRefCon,
1283 CFDictionaryRef pixelBufferAttributes,
1284 CVPixelBufferRef *pixelBufferOut) ;
1286 extern CVReturn CVPixelBufferCreateWithBytes(CFAllocatorRef allocator,
1289 OSType pixelFormatType,
1292 CVPixelBufferReleaseBytesCallback releaseCallback,
1293 void *releaseRefCon,
1294 CFDictionaryRef pixelBufferAttributes,
1295 CVPixelBufferRef *pixelBufferOut) ;
1297 CVReturn rdar_7283567(CFAllocatorRef allocator, size_t width, size_t height,
1298 OSType pixelFormatType, void *baseAddress,
1300 CVPixelBufferReleaseBytesCallback releaseCallback,
1301 CFDictionaryRef pixelBufferAttributes,
1302 CVPixelBufferRef *pixelBufferOut) {
1304 // For the allocated object, it doesn't really matter what type it is
1305 // for the purpose of this test. All we want to show is that
1306 // this is freed later by the callback.
1307 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1309 return CVPixelBufferCreateWithBytes(allocator, width, height, pixelFormatType,
1310 baseAddress, bytesPerRow, releaseCallback,
1311 number, // potentially released by callback
1312 pixelBufferAttributes, pixelBufferOut) ;
1315 CVReturn rdar_7283567_2(CFAllocatorRef allocator, size_t width, size_t height,
1316 OSType pixelFormatType, void *dataPtr, size_t dataSize,
1317 size_t numberOfPlanes, void *planeBaseAddress[],
1318 size_t planeWidth[], size_t planeHeight[], size_t planeBytesPerRow[],
1319 CVPixelBufferReleasePlanarBytesCallback releaseCallback,
1320 CFDictionaryRef pixelBufferAttributes,
1321 CVPixelBufferRef *pixelBufferOut) {
1323 // For the allocated object, it doesn't really matter what type it is
1324 // for the purpose of this test. All we want to show is that
1325 // this is freed later by the callback.
1326 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1328 return CVPixelBufferCreateWithPlanarBytes(allocator,
1329 width, height, pixelFormatType, dataPtr, dataSize,
1330 numberOfPlanes, planeBaseAddress, planeWidth,
1331 planeHeight, planeBytesPerRow, releaseCallback,
1332 number, // potentially released by callback
1333 pixelBufferAttributes, pixelBufferOut) ;
1336 #pragma clang arc_cf_code_audited begin
1337 typedef struct SomeOpaqueStruct *CMSampleBufferRef;
1338 CVImageBufferRef _Nonnull CMSampleBufferGetImageBuffer(CMSampleBufferRef _Nonnull sbuf);
1339 #pragma clang arc_cf_code_audited end
1341 CVBufferRef _Nullable CVBufferRetain(CVBufferRef _Nullable buffer);
1342 void CVBufferRelease(CF_CONSUMED CVBufferRef _Nullable buffer);
1344 void testCVPrefixRetain(CMSampleBufferRef sbuf) {
1345 // Make sure RetainCountChecker treats CVFooRetain() as a CF-style retain.
1346 CVPixelBufferRef pixelBuf = CMSampleBufferGetImageBuffer(sbuf);
1347 CVBufferRetain(pixelBuf);
1348 CVBufferRelease(pixelBuf); // no-warning
1351 // Make sure result of CVFooRetain() is the same as its argument.
1352 CVPixelBufferRef pixelBufAlias = CVBufferRetain(pixelBuf);
1353 CVBufferRelease(pixelBufAlias); // no-warning
1356 typedef signed long SInt32;
1357 typedef SInt32 OSStatus;
1358 typedef FourCharCode CMVideoCodecType;
1361 typedef UInt32 VTEncodeInfoFlags; enum {
1362 kVTEncodeInfo_Asynchronous = 1UL << 0,
1363 kVTEncodeInfo_FrameDropped = 1UL << 1,
1371 typedef void (*VTCompressionOutputCallback)(
1372 void * _Nullable outputCallbackRefCon,
1373 void * _Nullable sourceFrameRefCon,
1375 VTEncodeInfoFlags infoFlags,
1376 _Nullable CMSampleBufferRef sampleBuffer );
1378 typedef struct OpaqueVTCompressionSession* VTCompressionSessionRef;
1381 VTCompressionSessionCreate(_Nullable CFAllocatorRef allocator,
1384 CMVideoCodecType codecType,
1385 _Nullable CFDictionaryRef encoderSpecification,
1386 _Nullable CFDictionaryRef sourceImageBufferAttributes,
1387 _Nullable CFAllocatorRef compressedDataAllocator,
1388 _Nullable VTCompressionOutputCallback outputCallback,
1389 void * _Nullable outputCallbackRefCon,
1390 CF_RETURNS_RETAINED _Nullable VTCompressionSessionRef * _Nonnull compressionSessionOut);
1393 VTCompressionSessionEncodeFrame(
1394 _Nonnull VTCompressionSessionRef session,
1395 _Nonnull CVImageBufferRef imageBuffer,
1396 CMTime presentationTimeStamp,
1398 _Nullable CFDictionaryRef frameProperties,
1399 void * _Nullable sourceFrameRefCon,
1400 VTEncodeInfoFlags * _Nullable infoFlagsOut);
1403 VTCompressionSessionEncodeMultiImageFrame(
1404 _Nonnull VTCompressionSessionRef session,
1405 _Nonnull CVImageBufferRef imageBuffer,
1406 CMTime presentationTimeStamp,
1408 _Nullable CFDictionaryRef frameProperties,
1409 void * _Nullable sourceFrameRefCon,
1410 VTEncodeInfoFlags * _Nullable infoFlagsOut);
1412 OSStatus test_VTCompressionSessionCreateAndEncode_CallbackReleases(
1413 _Nullable CFAllocatorRef allocator,
1416 CMVideoCodecType codecType,
1417 _Nullable CFDictionaryRef encoderSpecification,
1418 _Nullable CFDictionaryRef sourceImageBufferAttributes,
1419 _Nullable CFAllocatorRef compressedDataAllocator,
1420 _Nullable VTCompressionOutputCallback outputCallback,
1422 _Nonnull CVImageBufferRef imageBuffer,
1423 CMTime presentationTimeStamp,
1425 _Nullable CFDictionaryRef frameProperties
1428 // The outputCallback is passed both contexts and so can release either.
1429 NSNumber *contextForCreate = [[NSNumber alloc] initWithInt:5]; // no-warning
1430 NSNumber *contextForEncode = [[NSNumber alloc] initWithInt:6]; // no-warning
1431 NSNumber *contextForEncodeMultiFrame = [[NSNumber alloc] initWithInt:7]; // no-warning
1434 VTCompressionSessionRef session = 0;
1435 OSStatus status = VTCompressionSessionCreate(allocator,
1436 width, height, codecType, encoderSpecification,
1437 sourceImageBufferAttributes,
1438 compressedDataAllocator, outputCallback, contextForCreate,
1441 VTEncodeInfoFlags encodeInfoFlags;
1443 status = VTCompressionSessionEncodeFrame(session, imageBuffer,
1444 presentationTimeStamp, duration, frameProperties, contextForEncode,
1447 status = VTCompressionSessionEncodeMultiImageFrame(session, imageBuffer,
1448 presentationTimeStamp, duration, frameProperties, contextForEncodeMultiFrame,
1454 //===----------------------------------------------------------------------===//
1455 // False leak associated with CGBitmapContextCreateWithData.
1456 //===----------------------------------------------------------------------===//
1457 typedef uint32_t CGBitmapInfo;
1458 typedef void (*CGBitmapContextReleaseDataCallback)(void *releaseInfo, void *data);
1460 CGContextRef CGBitmapContextCreateWithData(void *data,
1461 size_t width, size_t height, size_t bitsPerComponent,
1462 size_t bytesPerRow, CGColorSpaceRef space, CGBitmapInfo bitmapInfo,
1463 CGBitmapContextReleaseDataCallback releaseCallback, void *releaseInfo);
1465 void rdar_7358899(void *data,
1466 size_t width, size_t height, size_t bitsPerComponent,
1467 size_t bytesPerRow, CGColorSpaceRef space, CGBitmapInfo bitmapInfo,
1468 CGBitmapContextReleaseDataCallback releaseCallback) {
1470 // For the allocated object, it doesn't really matter what type it is
1471 // for the purpose of this test. All we want to show is that
1472 // this is freed later by the callback.
1473 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1475 CGBitmapContextCreateWithData(data, width, height, bitsPerComponent, // expected-warning{{leak}}
1476 bytesPerRow, space, bitmapInfo, releaseCallback, number);
1479 //===----------------------------------------------------------------------===//
1480 // Allow 'new', 'copy', 'alloc', 'init' prefix to start before '_' when
1481 // determining Cocoa fundamental rule.
1483 // Previously the retain/release checker just skipped prefixes before the
1484 // first '_' entirely. Now the checker honors the prefix if it results in a
1485 // recognizable naming convention (e.g., 'new', 'init').
1486 //===----------------------------------------------------------------------===//
1487 @interface RDar7265711 {}
1491 void rdar7265711_a(RDar7265711 *x) {
1492 id y = [x new_stuff]; // expected-warning{{leak}}
1495 void rdar7265711_b(RDar7265711 *x) {
1496 id y = [x new_stuff]; // no-warning
1500 //===----------------------------------------------------------------------===//
1501 // clang thinks [NSCursor dragCopyCursor] returns a retained reference.
1502 //===----------------------------------------------------------------------===//
1503 @interface NSCursor : NSObject
1504 + (NSCursor *)dragCopyCursor;
1507 void rdar7306898(void) {
1508 // 'dragCopyCursor' does not follow Cocoa's fundamental rule. It is a noun, not an sentence
1509 // implying a 'copy' of something.
1510 NSCursor *c = [NSCursor dragCopyCursor]; // no-warning
1511 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1514 //===----------------------------------------------------------------------===//
1515 // Sending 'release', 'retain', etc. to a Class directly is not likely what the
1517 //===----------------------------------------------------------------------===//
1518 @interface RDar7252064 : NSObject @end
1519 void rdar7252064(void) {
1520 [RDar7252064 release]; // expected-warning{{The 'release' message should be sent to instances of class 'RDar7252064' and not the class directly}}
1521 [RDar7252064 retain]; // expected-warning{{The 'retain' message should be sent to instances of class 'RDar7252064' and not the class directly}}
1522 [RDar7252064 autorelease]; // expected-warning{{The 'autorelease' message should be sent to instances of class 'RDar7252064' and not the class directly}}
1523 [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}}
1526 //===----------------------------------------------------------------------===//
1527 // Tests of ownership attributes.
1528 //===----------------------------------------------------------------------===//
1530 typedef NSString* MyStringTy;
1534 @interface TestOwnershipAttr : NSObject
1535 - (NSString*) returnsAnOwnedString NS_RETURNS_RETAINED; // no-warning
1536 - (NSString*) returnsAnOwnedCFString CF_RETURNS_RETAINED; // no-warning
1537 - (MyStringTy) returnsAnOwnedTypedString NS_RETURNS_RETAINED; // no-warning
1538 - (NSString*) newString NS_RETURNS_NOT_RETAINED; // no-warning
1539 - (NSString*) newString_auto NS_RETURNS_AUTORELEASED; // no-warning
1540 - (NSString*) newStringNoAttr;
1541 - (int) returnsAnOwnedInt NS_RETURNS_RETAINED; // expected-warning{{'ns_returns_retained' attribute only applies to methods that return an Objective-C object}}
1542 - (id) pseudoInit NS_CONSUMES_SELF NS_RETURNS_RETAINED;
1543 + (void) consume:(id) NS_CONSUMED x;
1544 + (void) consume2:(id) CF_CONSUMED x;
1547 static int ownership_attribute_doesnt_go_here NS_RETURNS_RETAINED; // expected-warning{{'ns_returns_retained' only applies to function types; type here is 'int'}}
1549 void test_attr_1(TestOwnershipAttr *X) {
1550 NSString *str = [X returnsAnOwnedString]; // expected-warning{{leak}}
1553 void test_attr_1b(TestOwnershipAttr *X) {
1554 NSString *str = [X returnsAnOwnedCFString]; // expected-warning{{leak}}
1557 void test_attr1c(TestOwnershipAttr *X) {
1558 NSString *str = [X newString]; // no-warning
1559 NSString *str2 = [X newStringNoAttr]; // expected-warning{{leak}}
1560 NSString *str3 = [X newString_auto]; // no-warning
1561 NSString *str4 = [[X newString_auto] retain]; // expected-warning {{leak}}
1564 void testattr2_a(void) {
1565 TestOwnershipAttr *x = [TestOwnershipAttr alloc]; // expected-warning{{leak}}
1568 void testattr2_b(void) {
1569 TestOwnershipAttr *x = [[TestOwnershipAttr alloc] pseudoInit]; // expected-warning{{leak}}
1572 void testattr2_b_11358224_self_assign_looses_the_leak(void) {
1573 TestOwnershipAttr *x = [[TestOwnershipAttr alloc] pseudoInit];// expected-warning{{leak}}
1577 void testattr2_c(void) {
1578 TestOwnershipAttr *x = [[TestOwnershipAttr alloc] pseudoInit]; // no-warning
1582 void testattr3(void) {
1583 TestOwnershipAttr *x = [TestOwnershipAttr alloc]; // no-warning
1584 [TestOwnershipAttr consume:x];
1585 TestOwnershipAttr *y = [TestOwnershipAttr alloc]; // no-warning
1586 [TestOwnershipAttr consume2:y];
1589 void consume_ns(id NS_CONSUMED x);
1590 void consume_cf(id CF_CONSUMED x);
1592 void testattr4(void) {
1593 TestOwnershipAttr *x = [TestOwnershipAttr alloc]; // no-warning
1595 TestOwnershipAttr *y = [TestOwnershipAttr alloc]; // no-warning
1599 @interface TestOwnershipAttr2 : NSObject
1600 - (NSString*) newString NS_RETURNS_NOT_RETAINED; // no-warning
1603 @implementation TestOwnershipAttr2
1604 - (NSString*) newString {
1605 return [NSString alloc]; // expected-warning {{Potential leak of an object}}
1609 @interface MyClassTestCFAttr : NSObject {}
1610 - (NSDate*) returnsCFRetained CF_RETURNS_RETAINED;
1611 - (CFDateRef) returnsCFRetainedAsCF CF_RETURNS_RETAINED;
1612 - (CFDateRef) newCFRetainedAsCF CF_RETURNS_NOT_RETAINED;
1613 - (CFDateRef) newCFRetainedAsCFNoAttr;
1614 - (NSDate*) alsoReturnsRetained;
1615 - (CFDateRef) alsoReturnsRetainedAsCF;
1616 - (NSDate*) returnsNSRetained NS_RETURNS_RETAINED;
1620 CFDateRef returnsRetainedCFDate(void) {
1621 return CFDateCreate(0, CFAbsoluteTimeGetCurrent());
1624 @implementation MyClassTestCFAttr
1625 - (NSDate*) returnsCFRetained {
1626 return (NSDate*) returnsRetainedCFDate(); // No leak.
1629 - (CFDateRef) returnsCFRetainedAsCF {
1630 return returnsRetainedCFDate(); // No leak.
1633 - (CFDateRef) newCFRetainedAsCF {
1634 return (CFDateRef)[(id)[self returnsCFRetainedAsCF] autorelease];
1637 - (CFDateRef) newCFRetainedAsCFNoAttr {
1638 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}}
1641 - (NSDate*) alsoReturnsRetained {
1642 return (NSDate*) returnsRetainedCFDate(); // expected-warning{{leak}}
1645 - (CFDateRef) alsoReturnsRetainedAsCF {
1646 return returnsRetainedCFDate(); // expected-warning{{leak}}
1650 - (NSDate*) returnsNSRetained {
1651 return (NSDate*) returnsRetainedCFDate(); // no-warning
1655 //===----------------------------------------------------------------------===//
1656 // Test that leaks post-dominated by "panic" functions are not reported.
1658 // Do not report a leak when post-dominated by a call to a noreturn or panic
1660 //===----------------------------------------------------------------------===//
1661 void panic(void) __attribute__((noreturn));
1662 void panic_not_in_hardcoded_list(void) __attribute__((noreturn));
1664 void test_panic_negative(void) {
1666 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // expected-warning{{leak}}
1669 void test_panic_positive(void) {
1671 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // no-warning
1675 void test_panic_neg_2(int x) {
1677 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // expected-warning{{leak}}
1682 void test_panic_pos_2(int x) {
1684 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // no-warning
1688 // This showed up previously where we silently missed checking the function
1689 // type for noreturn. "panic()" is a hard-coded known panic function that
1690 // isn't always noreturn.
1691 panic_not_in_hardcoded_list();
1695 //===----------------------------------------------------------------------===//
1696 // Test uses of blocks (closures)
1697 //===----------------------------------------------------------------------===//
1699 void test_blocks_1_pos(void) {
1700 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1704 void test_blocks_1_indirect_release(void) {
1705 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1706 ^{ [number release]; }();
1709 void test_blocks_1_indirect_retain(void) {
1710 // Eventually this should be reported as a leak.
1711 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1712 ^{ [number retain]; }();
1715 void test_blocks_1_indirect_release_via_call(void) {
1716 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1717 ^(NSObject *o){ [o release]; }(number);
1720 void test_blocks_1_indirect_retain_via_call(void) {
1721 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning {{leak}}
1722 ^(NSObject *o){ [o retain]; }(number);
1725 //===--------------------------------------------------------------------===//
1726 // Test sending message to super that returns an object alias. Previously
1727 // this caused a crash in the analyzer.
1728 //===--------------------------------------------------------------------===//
1730 @interface Rdar8015556 : NSObject {} @end
1731 @implementation Rdar8015556
1733 return [super retain];
1737 // Correcly handle Class<...> in Cocoa Conventions detector.
1738 @protocol Prot_R8272168 @end
1739 Class <Prot_R8272168> GetAClassThatImplementsProt_R8272168(void);
1740 void r8272168(void) {
1741 GetAClassThatImplementsProt_R8272168();
1744 // This used to trigger a false positive.
1745 @interface RDar8356342
1746 - (NSDate*) rdar8356342:(NSDate *)inValue;
1749 @implementation RDar8356342
1750 - (NSDate*) rdar8356342:(NSDate*)inValue {
1751 NSDate *outValue = inValue;
1753 outValue = [[NSDate alloc] init]; // no-warning
1755 if (outValue != inValue)
1756 [outValue autorelease];
1762 // This test case previously crashed because of a bug in BugReporter.
1763 extern const void *CFDictionaryGetValue(CFDictionaryRef theDict, const void *key);
1764 typedef struct __CFError * CFErrorRef;
1765 extern const CFStringRef kCFErrorUnderlyingErrorKey;
1766 extern CFDictionaryRef CFErrorCopyUserInfo(CFErrorRef err);
1767 static void rdar_8724287(CFErrorRef error)
1769 CFErrorRef error_to_dump;
1771 error_to_dump = error;
1772 while (error_to_dump != ((void*)0)) {
1773 CFDictionaryRef info;
1775 info = CFErrorCopyUserInfo(error_to_dump); // expected-warning{{Potential leak of an object}}
1777 if (info != ((void*)0)) {
1780 error_to_dump = (CFErrorRef) CFDictionaryGetValue(info, kCFErrorUnderlyingErrorKey);
1784 // Make sure the model applies cf_consumed correctly in argument positions
1785 // besides the first.
1786 extern void *CFStringCreate(void);
1787 extern void rdar_9234108_helper(void *key, void * CF_CONSUMED value);
1788 void rdar_9234108(void) {
1789 rdar_9234108_helper(0, CFStringCreate());
1792 // Make sure that objc_method_family works to override naming conventions.
1797 typedef struct TwoDoubles TwoDoubles;
1799 @interface NSValue (Mine)
1800 - (id)_prefix_initWithTwoDoubles:(TwoDoubles)twoDoubles __attribute__((objc_method_family(init)));
1803 @implementation NSValue (Mine)
1804 - (id)_prefix_initWithTwoDoubles:(TwoDoubles)twoDoubles
1810 void rdar9726279(void) {
1811 TwoDoubles twoDoubles = { 0.0, 0.0 };
1812 NSValue *value = [[NSValue alloc] _prefix_initWithTwoDoubles:twoDoubles];
1816 // Test camelcase support for CF conventions. While Core Foundation APIs
1817 // don't use camel casing, other code is allowed to use it.
1818 CFArrayRef camelcase_create_1(void) {
1819 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1822 CFArrayRef camelcase_createno(void) {
1823 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1826 CFArrayRef camelcase_copy(void) {
1827 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1830 CFArrayRef camelcase_copying(void) {
1831 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1834 CFArrayRef copyCamelCase(void) {
1835 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1838 CFArrayRef __copyCamelCase(void) {
1839 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1842 CFArrayRef __createCamelCase(void) {
1843 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1846 CFArrayRef camel_create(void) {
1847 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1851 CFArrayRef camel_creat(void) {
1852 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1855 CFArrayRef camel_copy(void) {
1856 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1859 CFArrayRef camel_copyMachine(void) {
1860 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1863 CFArrayRef camel_copymachine(void) {
1864 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1868 - (id) clone; // expected-note 2 {{method declared here}}
1870 @interface F18 : NSObject<F18P> @end
1872 - (id) clone NS_RETURNS_RETAINED; // expected-warning {{overriding method has mismatched ns_returns_retained attributes}}
1876 - (id) clone { // expected-warning {{overriding method has mismatched ns_returns_retained attributes}}
1881 void rdar6582778(void) {
1882 CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
1883 CFTypeRef vals[] = { CFDateCreate(0, t) }; // expected-warning {{leak}}
1888 void rdar6582778_2(void) {
1889 CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
1890 global = CFDateCreate(0, t); // no-warning
1893 // Test that objects passed to containers are marked "escaped".
1894 void rdar10232019(void) {
1895 NSMutableArray *array = [NSMutableArray array];
1897 NSString *string = [[NSString alloc] initWithUTF8String:"foo"];
1898 [array addObject:string];
1901 NSString *otherString = [string stringByAppendingString:@"bar"]; // no-warning
1902 NSLog(@"%@", otherString);
1905 void rdar10232019_positive(void) {
1906 NSMutableArray *array = [NSMutableArray array];
1908 NSString *string = [[NSString alloc] initWithUTF8String:"foo"];
1911 NSString *otherString = [string stringByAppendingString:@"bar"]; // expected-warning {{Reference-counted object is used after it is release}}
1912 NSLog(@"%@", otherString);
1915 // RetainCountChecker support for XPC.
1916 typedef void * xpc_object_t;
1917 xpc_object_t _CFXPCCreateXPCObjectFromCFObject(CFTypeRef cf);
1918 void xpc_release(xpc_object_t object);
1920 void rdar9658496(void) {
1923 cf = CFStringCreateWithCString( ((CFAllocatorRef)0), "test", kCFStringEncodingUTF8 ); // no-warning
1924 xpc = _CFXPCCreateXPCObjectFromCFObject( cf );
1929 // Support annotations with method families.
1930 @interface RDar10824732 : NSObject
1931 - (id)initWithObj:(id CF_CONSUMED)obj;
1934 @implementation RDar10824732
1935 - (id)initWithObj:(id)obj {
1937 return [super init];
1941 void rdar_10824732(void) {
1943 NSString *obj = @"test";
1944 RDar10824732 *foo = [[RDar10824732 alloc] initWithObj:obj]; // no-warning
1949 // Stop tracking objects passed to functions, which take callbacks as parameters.
1950 typedef int (*CloseCallback) (void *);
1951 void ReaderForIO(CloseCallback ioclose, void *ioctx);
1952 int IOClose(void *context);
1954 @protocol SInS <NSObject>
1957 @interface radar10973977 : NSObject
1962 @implementation radar10973977
1965 id<SInS> inputS = [[self inputS] retain];
1966 ReaderForIO(IOClose, inputS);
1974 // Object escapes through a selector callback
1976 @interface MySheetController
1978 - (void)showDoSomethingSheetAction:(id)action;
1979 - (void)sheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo;
1982 @implementation MySheetController
1983 - (id<SInS>)inputS {
1986 - (void)showDoSomethingSheetAction:(id)action {
1987 id<SInS> inputS = [[self inputS] retain];
1991 didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:)
1992 contextInfo:(void *)inputS]; // no - warning
1994 - (void)sheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo {
1996 id contextObject = (id)contextInfo;
1997 [contextObject release];
2000 - (id)copyAutoreleaseRadar13081402 {
2001 id x = [[[NSString alloc] initWithUTF8String:"foo"] autorelease];
2003 return x; // no warning
2007 //===----------------------------------------------------------------------===//
2008 // Test returning allocated memory in a struct.
2010 // We currently don't have a general way to track pointers that "escape".
2011 // Here we test that RetainCountChecker doesn't get excited about returning
2012 // allocated CF objects in struct fields.
2013 //===----------------------------------------------------------------------===//
2014 void *malloc(size_t);
2015 struct rdar11104566 { CFStringRef myStr; };
2016 struct rdar11104566 test_rdar11104566(void) {
2017 CFStringRef cf = CFStringCreateWithCString( ((CFAllocatorRef)0), "test", kCFStringEncodingUTF8 ); // no-warning
2018 struct rdar11104566 V;
2020 return V; // no-warning
2023 struct rdar11104566 *test_2_rdar11104566(void) {
2024 CFStringRef cf = CFStringCreateWithCString( ((CFAllocatorRef)0), "test", kCFStringEncodingUTF8 ); // no-warning
2025 struct rdar11104566 *V = (struct rdar11104566 *) malloc(sizeof(*V));
2027 return V; // no-warning
2030 //===----------------------------------------------------------------------===//
2031 // ObjC literals support.
2032 //===----------------------------------------------------------------------===//
2034 void test_objc_arrays(void) {
2035 { // CASE ONE -- OBJECT IN ARRAY CREATED DIRECTLY
2036 NSObject *o = [[NSObject alloc] init];
2037 NSArray *a = [[NSArray alloc] initWithObjects:o, (void*)0]; // expected-warning {{leak}}
2043 { // CASE TWO -- OBJECT IN ARRAY CREATED BY DUPING AUTORELEASED ARRAY
2044 NSObject *o = [[NSObject alloc] init];
2045 NSArray *a1 = [NSArray arrayWithObjects:o, (void*)0];
2046 NSArray *a2 = [[NSArray alloc] initWithArray:a1]; // expected-warning {{leak}}
2052 { // CASE THREE -- OBJECT IN RETAINED @[]
2053 NSObject *o = [[NSObject alloc] init];
2054 NSArray *a3 = [@[o] retain]; // expected-warning {{leak}}
2060 { // CASE FOUR -- OBJECT IN ARRAY CREATED BY DUPING @[]
2061 NSObject *o = [[NSObject alloc] init];
2062 NSArray *a = [[NSArray alloc] initWithArray:@[o]]; // expected-warning {{leak}}
2069 { // CASE FIVE -- OBJECT IN RETAINED @{}
2070 NSValue *o = [[NSValue alloc] init];
2071 NSDictionary *a = [@{o : o} retain]; // expected-warning {{leak}}
2079 void test_objc_integer_literals(void) {
2080 id value = [@1 retain]; // expected-warning {{leak}}
2081 [value description];
2084 void test_objc_boxed_expressions(int x, const char *y) {
2085 id value = [@(x) retain]; // expected-warning {{leak}}
2086 [value description];
2088 value = [@(y) retain]; // expected-warning {{leak}}
2089 [value description];
2092 // Test NSLog doesn't escape tracked objects.
2093 void rdar11400885(int y)
2096 NSString *printString;
2098 printString = [[NSString alloc] init];
2100 printString = [[NSString alloc] init];
2101 NSLog(@"Once %@", printString);
2102 [printString release];
2103 NSLog(@"Again: %@", printString); // expected-warning {{Reference-counted object is used after it is released}}
2107 id makeCollectableNonLeak(void) {
2108 extern CFTypeRef CFCreateSomething(void);
2110 CFTypeRef object = CFCreateSomething(); // +1
2111 CFRetain(object); // +2
2112 id objCObject = NSMakeCollectable(object); // +2
2113 [objCObject release]; // +1
2114 return [objCObject autorelease]; // +0
2117 void consumeAndStopTracking(id NS_CONSUMED obj, void (^callback)(void));
2118 void CFConsumeAndStopTracking(CFTypeRef CF_CONSUMED obj, void (^callback)(void));
2120 void testConsumeAndStopTracking(void) {
2121 id retained = [@[] retain]; // +1
2122 consumeAndStopTracking(retained, ^{}); // no-warning
2124 id doubleRetained = [[@[] retain] retain]; // +2
2125 consumeAndStopTracking(doubleRetained, ^{
2126 [doubleRetained release];
2129 id unretained = @[]; // +0
2130 consumeAndStopTracking(unretained, ^{}); // expected-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
2133 void testCFConsumeAndStopTracking(void) {
2134 id retained = [@[] retain]; // +1
2135 CFConsumeAndStopTracking((CFTypeRef)retained, ^{}); // no-warning
2137 id doubleRetained = [[@[] retain] retain]; // +2
2138 CFConsumeAndStopTracking((CFTypeRef)doubleRetained, ^{
2139 [doubleRetained release];
2142 id unretained = @[]; // +0
2143 CFConsumeAndStopTracking((CFTypeRef)unretained, ^{}); // expected-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
2145 //===----------------------------------------------------------------------===//
2146 // Test 'pragma clang arc_cf_code_audited' support.
2147 //===----------------------------------------------------------------------===//
2149 typedef void *MyCFType;
2150 #pragma clang arc_cf_code_audited begin
2151 MyCFType CreateMyCFType(void);
2152 #pragma clang arc_cf_code_audited end
2154 void test_custom_cf(void) {
2155 MyCFType x = CreateMyCFType(); // expected-warning {{leak of an object stored into 'x'}}
2158 //===----------------------------------------------------------------------===//
2159 // Test calling CFPlugInInstanceCreate, which appears in CF but doesn't
2160 // return a CF object.
2161 //===----------------------------------------------------------------------===//
2163 void test_CFPlugInInstanceCreate(CFUUIDRef factoryUUID, CFUUIDRef typeUUID) {
2164 CFPlugInInstanceCreate(kCFAllocatorDefault, factoryUUID, typeUUID); // no-warning
2167 //===----------------------------------------------------------------------===//
2168 // PR14927: -drain only has retain-count semantics on NSAutoreleasePool.
2169 //===----------------------------------------------------------------------===//
2171 @interface PR14927 : NSObject
2175 void test_drain(void) {
2176 PR14927 *obj = [[PR14927 alloc] init];
2178 [obj release]; // no-warning
2181 //===----------------------------------------------------------------------===//
2182 // Allow cf_returns_retained and cf_returns_not_retained to mark a return
2183 // value as tracked, even if the object isn't a known CF type.
2184 //===----------------------------------------------------------------------===//
2186 MyCFType getCustom(void) __attribute__((cf_returns_not_retained));
2187 MyCFType makeCustom(void) __attribute__((cf_returns_retained));
2189 void testCustomReturnsRetained(void) {
2190 MyCFType obj = makeCustom(); // expected-warning {{leak of an object stored into 'obj'}}
2193 void testCustomReturnsNotRetained(void) {
2194 CFRelease(getCustom()); // expected-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
2197 //===----------------------------------------------------------------------===//
2198 // Don't print variables which are out of the current scope.
2199 //===----------------------------------------------------------------------===//
2200 @interface MyObj12706177 : NSObject
2202 +(void)test12706177;
2205 @implementation MyObj12706177
2209 self = [super init];
2212 +(void)test12706177 {
2213 id x = [[MyObj12706177 alloc] initX]; //expected-warning {{Potential leak of an object}}
2218 //===----------------------------------------------------------------------===//
2220 //===----------------------------------------------------------------------===//
2222 CFTypeRef getAutoreleasedCFType(void) {
2223 extern CFTypeRef CFCreateSomething(void);
2224 return CFAutorelease(CFCreateSomething()); // no-warning
2227 CFTypeRef getIncorrectlyAutoreleasedCFType(void) {
2228 extern CFTypeRef CFGetSomething(void);
2229 return CFAutorelease(CFGetSomething()); // expected-warning{{Object autoreleased too many times}}
2232 CFTypeRef createIncorrectlyAutoreleasedCFType(void) {
2233 extern CFTypeRef CFCreateSomething(void);
2234 return CFAutorelease(CFCreateSomething()); // expected-warning{{Object with a +0 retain count returned to caller where a +1 (owning) retain count is expected}}
2237 void useAfterAutorelease(void) {
2238 extern CFTypeRef CFCreateSomething(void);
2239 CFTypeRef obj = CFCreateSomething();
2242 extern void useCF(CFTypeRef);
2243 useCF(obj); // no-warning
2246 void useAfterRelease(void) {
2247 // Verify that the previous example would have warned with CFRelease.
2248 extern CFTypeRef CFCreateSomething(void);
2249 CFTypeRef obj = CFCreateSomething();
2252 extern void useCF(CFTypeRef);
2253 useCF(obj); // expected-warning{{Reference-counted object is used after it is released}}
2256 void testAutoreleaseReturnsInput(void) {
2257 extern CFTypeRef CFCreateSomething(void);
2258 CFTypeRef obj = CFCreateSomething(); // expected-warning{{Potential leak of an object stored into 'second'}}
2259 CFTypeRef second = CFAutorelease(obj);
2263 CFTypeRef testAutoreleaseReturnsInputSilent(void) {
2264 extern CFTypeRef CFCreateSomething(void);
2265 CFTypeRef obj = CFCreateSomething();
2266 CFTypeRef alias = CFAutorelease(obj);
2269 return obj; // no-warning
2272 void autoreleaseTypedObject(void) {
2273 CFArrayRef arr = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
2274 CFAutorelease((CFTypeRef)arr); // no-warning
2277 void autoreleaseReturningTypedObject(void) {
2278 CFArrayRef arr = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning{{Potential leak of an object stored into 'alias'}}
2279 CFArrayRef alias = (CFArrayRef)CFAutorelease((CFTypeRef)arr);
2283 CFArrayRef autoreleaseReturningTypedObjectSilent(void) {
2284 CFArrayRef arr = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
2285 CFArrayRef alias = (CFArrayRef)CFAutorelease((CFTypeRef)arr);
2288 return alias; // no-warning
2291 void autoreleaseObjC(void) {
2292 id obj = [@1 retain];
2293 CFAutorelease(obj); // no-warning
2296 CFAutorelease(anotherObj);
2297 } // expected-warning{{Object autoreleased too many times}}
2299 //===----------------------------------------------------------------------===//
2300 // xpc_connection_set_finalizer_f
2301 //===----------------------------------------------------------------------===//
2302 typedef xpc_object_t xpc_connection_t;
2303 typedef void (*xpc_finalizer_t)(void *value);
2304 void xpc_connection_set_context(xpc_connection_t connection, void *ctx);
2305 void xpc_connection_set_finalizer_f(xpc_connection_t connection,
2306 xpc_finalizer_t finalizer);
2307 void releaseAfterXPC(void *context) {
2308 [(NSArray *)context release];
2311 void rdar13783514(xpc_connection_t connection) {
2312 xpc_connection_set_context(connection, [[NSMutableArray alloc] init]);
2313 xpc_connection_set_finalizer_f(connection, releaseAfterXPC);
2316 // Do not report leaks when object is cleaned up with __attribute__((cleanup ..)).
2317 inline static void cleanupFunction(void *tp) {
2318 CFTypeRef x = *(CFTypeRef *)tp;
2323 #define ADDCLEANUP __attribute__((cleanup(cleanupFunction)))
2325 ADDCLEANUP CFStringRef myString;
2326 myString = CFStringCreateWithCString(0, "hello world", kCFStringEncodingUTF8);
2327 ADDCLEANUP CFStringRef myString2 =
2328 CFStringCreateWithCString(0, "hello world", kCFStringEncodingUTF8);
2331 //===----------------------------------------------------------------------===//
2333 //===----------------------------------------------------------------------===//
2335 __attribute__((ns_returns_retained))
2336 id returnNSNull(void) {
2337 return [NSNull null]; // no-warning
2340 //===----------------------------------------------------------------------===//
2341 // cf_returns_[not_]retained on parameters
2342 //===----------------------------------------------------------------------===//
2344 void testCFReturnsNotRetained(void) {
2345 extern void getViaParam(CFTypeRef * CF_RETURNS_NOT_RETAINED outObj);
2348 CFRelease(obj); // // expected-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
2351 void testCFReturnsNotRetainedAnnotated(void) {
2352 extern void getViaParam2(CFTypeRef * _Nonnull CF_RETURNS_NOT_RETAINED outObj);
2355 CFRelease(obj); // // expected-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
2358 void testCFReturnsRetained(void) {
2359 extern int copyViaParam(CFTypeRef * CF_RETURNS_RETAINED outObj);
2363 CFRelease(obj); // // FIXME-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
2366 void testCFReturnsRetainedError(void) {
2367 extern int copyViaParam(CFTypeRef * CF_RETURNS_RETAINED outObj);
2369 if (copyViaParam(&obj) == -42)
2370 return; // no-warning