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}}
716 // <rdar://problem/6659160>
719 static void rdar_6659160(char *inkind, char *inname)
721 // We currently expect that [NSObject alloc] cannot fail. This
722 // will be a toggled flag in the future. It can indeed return null, but
723 // Cocoa programmers generally aren't expected to reason about out-of-memory
725 NSString *kind = [[NSString alloc] initWithUTF8String:inkind]; // expected-warning{{leak}}
727 // We do allow stringWithUTF8String to fail. This isn't really correct, as
728 // far as returning 0. In most error conditions it will throw an exception.
729 // If allocation fails it could return 0, but again this
731 NSString *name = [NSString stringWithUTF8String:inname];
735 const char *kindC = 0;
736 const char *nameC = 0;
738 // In both cases, we cannot reach a point down below where we
739 // dereference kindC or nameC with either being null. This is because
740 // we assume that [NSObject alloc] doesn't fail and that we have the guard
744 kindC = [kind UTF8String];
746 nameC = [name UTF8String];
747 if(!isFoo(kindC[0])) // expected-warning{{null}}
749 if(!isFoo(nameC[0])) // no-warning
753 [name release]; // expected-warning{{Incorrect decrement of the reference count}}
756 // PR 3677 - 'allocWithZone' should be treated as following the Cocoa naming
757 // conventions with respect to 'return'ing ownership.
758 @interface PR3677: NSObject @end
759 @implementation PR3677
760 + (id)allocWithZone:(NSZone *)inZone {
761 return [super allocWithZone:inZone]; // no-warning
765 // PR 3820 - Reason about calls to -dealloc
766 void pr3820_DeallocInsteadOfRelease(void)
768 id foo = [[NSString alloc] init]; // no-warning
770 // foo is not leaked, since it has been deallocated.
773 void pr3820_ReleaseAfterDealloc(void)
775 id foo = [[NSString alloc] init];
777 [foo release]; // expected-warning{{used after it is release}}
778 // NSInternalInconsistencyException: message sent to deallocated object
781 void pr3820_DeallocAfterRelease(void)
783 NSLog(@"\n\n[%s]", __FUNCTION__);
784 id foo = [[NSString alloc] init];
786 [foo dealloc]; // expected-warning{{used after it is released}}
787 // message sent to released object
790 // From <rdar://problem/6704930>. The problem here is that 'length' binds to
791 // '($0 - 1)' after '--length', but SimpleConstraintManager doesn't know how to
792 // reason about '($0 - 1) > constant'. As a temporary hack, we drop the value
793 // of '($0 - 1)' and conjure a new symbol.
794 void rdar6704930(unsigned char *s, unsigned int length) {
802 name = [[NSString alloc] init]; // no-warning
808 if ((length == 0) && (name != 0)) {
812 if (length == 0) { // no ':' found -> use it all as name
813 name = [[NSString alloc] init]; // no-warning
823 //===----------------------------------------------------------------------===//
824 // <rdar://problem/6833332>
825 // One build of the analyzer accidentally stopped tracking the allocated
826 // object after the 'retain'.
827 //===----------------------------------------------------------------------===//
829 @interface rdar_6833332 : NSObject <NSApplicationDelegate> {
832 @property (nonatomic, retain) NSWindow *window;
835 @implementation rdar_6833332
837 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
838 NSMutableDictionary *dict = [[NSMutableDictionary dictionaryWithCapacity:4] retain]; // expected-warning{{leak}}
840 [dict setObject:@"foo" forKey:@"bar"];
849 - (void)radar10102244 {
850 NSMutableDictionary *dict = [[NSMutableDictionary dictionaryWithCapacity:4] retain]; // expected-warning{{leak}}
852 NSLog(@"%@", window);
856 //===----------------------------------------------------------------------===//
857 // <rdar://problem/6257780> clang checker fails to catch use-after-release
858 //===----------------------------------------------------------------------===//
860 int rdar_6257780_Case1(void) {
861 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
862 NSArray *array = [NSArray array];
863 [array release]; // expected-warning{{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
868 //===----------------------------------------------------------------------===//
869 // <rdar://problem/10640253> Analyzer is confused about NSAutoreleasePool -allocWithZone:.
870 //===----------------------------------------------------------------------===//
872 void rdar_10640253_autorelease_allocWithZone(void) {
873 NSAutoreleasePool *pool = [[NSAutoreleasePool allocWithZone:(NSZone*)0] init];
877 //===----------------------------------------------------------------------===//
878 // <rdar://problem/6866843> Checker should understand new/setObject:/release constructs
879 //===----------------------------------------------------------------------===//
881 void rdar_6866843(void) {
882 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
883 NSMutableDictionary* dictionary = [[NSMutableDictionary alloc] init];
884 NSArray* array = [[NSArray alloc] init];
885 [dictionary setObject:array forKey:@"key"];
887 // Using 'array' here should be fine
888 NSLog(@"array = %@\n", array); // no-warning
889 // Now the array is released
890 [dictionary release];
895 //===----------------------------------------------------------------------===//
896 // <rdar://problem/6877235> Classes typedef-ed to CF objects should get the same treatment as CF objects
897 //===----------------------------------------------------------------------===//
899 typedef CFTypeRef OtherRef;
901 @interface RDar6877235 : NSObject {}
902 - (CFTypeRef)_copyCFTypeRef;
903 - (OtherRef)_copyOtherRef;
906 @implementation RDar6877235
907 - (CFTypeRef)_copyCFTypeRef {
908 return [[NSString alloc] init]; // no-warning
910 - (OtherRef)_copyOtherRef {
911 return [[NSString alloc] init]; // no-warning
915 //===----------------------------------------------------------------------===//
916 // <rdar://problem/6320065> false positive - init method returns an object
918 //===----------------------------------------------------------------------===//
920 @interface RDar6320065 : NSObject {
923 - (id)initReturningNewClass;
924 - (id)_initReturningNewClassBad;
925 - (id)initReturningNewClassBad2;
928 @interface RDar6320065Subclass : RDar6320065
931 @implementation RDar6320065
932 - (id)initReturningNewClass {
934 self = [[RDar6320065Subclass alloc] init]; // no-warning
937 - (id)_initReturningNewClassBad {
939 [[RDar6320065Subclass alloc] init]; // expected-warning {{leak}}
942 - (id)initReturningNewClassBad2 {
944 self = [[RDar6320065Subclass alloc] init];
945 return [self autorelease]; // expected-warning{{Object with a +0 retain count returned to caller where a +1 (owning) retain count is expected}}
950 @implementation RDar6320065Subclass
953 int RDar6320065_test(void) {
954 RDar6320065 *test = [[RDar6320065 alloc] init]; // no-warning
959 //===----------------------------------------------------------------------===//
960 // <rdar://problem/7129086> -awakeAfterUsingCoder: returns an owned object
961 // and claims the receiver
962 //===----------------------------------------------------------------------===//
964 @interface RDar7129086 : NSObject {} @end
965 @implementation RDar7129086
966 - (id)awakeAfterUsingCoder:(NSCoder *)aDecoder {
967 [self release]; // no-warning
968 return [NSString alloc]; // no-warning
972 //===----------------------------------------------------------------------===//
973 // <rdar://problem/6859457> [NSData dataWithBytesNoCopy] does not return a
975 //===----------------------------------------------------------------------===//
977 @interface RDar6859457 : NSObject {}
978 - (NSString*) NoCopyString;
979 - (NSString*) noCopyString;
982 @implementation RDar6859457
983 - (NSString*) NoCopyString { return [[NSString alloc] init]; } // expected-warning{{leak}}
984 - (NSString*) noCopyString { return [[NSString alloc] init]; } // expected-warning{{leak}}
987 void test_RDar6859457(RDar6859457 *x, void *bytes, NSUInteger dataLength) {
988 [x NoCopyString]; // expected-warning{{leak}}
989 [x noCopyString]; // expected-warning{{leak}}
990 [NSData dataWithBytesNoCopy:bytes length:dataLength]; // no-warning
991 [NSData dataWithBytesNoCopy:bytes length:dataLength freeWhenDone:1]; // no-warning
994 //===----------------------------------------------------------------------===//
995 // PR 4230 - an autorelease pool is not necessarily leaked during a premature
997 //===----------------------------------------------------------------------===//
999 static void PR4230(void)
1001 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // no-warning
1002 NSString *object = [[[NSString alloc] init] autorelease]; // no-warning
1006 static void PR4230_new(void)
1008 NSAutoreleasePool *pool = [NSAutoreleasePool new]; // no-warning
1009 NSString *object = [[[NSString alloc] init] autorelease]; // no-warning
1013 //===----------------------------------------------------------------------===//
1014 // Method name that has a null IdentifierInfo* for its first selector slot.
1015 // This test just makes sure that we handle it.
1016 //===----------------------------------------------------------------------===//
1018 @interface TestNullIdentifier
1021 @implementation TestNullIdentifier
1022 + (id):(int)x, ... {
1023 return [[NSString alloc] init]; // expected-warning{{leak}}
1027 //===----------------------------------------------------------------------===//
1028 // <rdar://problem/6893565> don't flag leaks for return types that cannot be
1029 // determined to be CF types
1030 //===----------------------------------------------------------------------===//
1032 // We don't know if 'struct s6893565' represents a Core Foundation type, so
1033 // we shouldn't emit an error here.
1034 typedef struct s6893565* TD6893565;
1036 @interface RDar6893565 {}
1037 -(TD6893565)newThing;
1040 @implementation RDar6893565
1041 -(TD6893565)newThing {
1042 return (TD6893565) [[NSString alloc] init]; // no-warning
1046 //===----------------------------------------------------------------------===//
1047 // <rdar://problem/6902710> clang: false positives w/QC and CoreImage methods
1048 //===----------------------------------------------------------------------===//
1050 void rdar6902710(QCView *view, QCRenderer *renderer, CIContext *context,
1051 NSString *str, CIImage *img, CGRect rect,
1052 CIFormat form, CGColorSpaceRef cs) {
1053 [view createSnapshotImageOfType:str]; // expected-warning{{leak}}
1054 [renderer createSnapshotImageOfType:str]; // expected-warning{{leak}}
1055 [context createCGImage:img fromRect:rect]; // expected-warning{{leak}}
1056 [context createCGImage:img fromRect:rect format:form colorSpace:cs]; // expected-warning{{leak}}
1059 //===----------------------------------------------------------------------===//
1060 // <rdar://problem/6945561> -[CIContext createCGLayerWithSize:info:]
1061 // misinterpreted by clang scan-build
1062 //===----------------------------------------------------------------------===//
1064 void rdar6945561(CIContext *context, CGSize size, CFDictionaryRef d) {
1065 [context createCGLayerWithSize:size info:d]; // expected-warning{{leak}}
1068 //===----------------------------------------------------------------------===//
1069 // <rdar://problem/6961230> add knowledge of IOKit functions to retain/release
1071 //===----------------------------------------------------------------------===//
1073 void IOBSDNameMatching_wrapper(mach_port_t mainPort, uint32_t options, const char * bsdName) {
1074 IOBSDNameMatching(mainPort, options, bsdName); // expected-warning{{leak}}
1077 void IOServiceMatching_wrapper(const char * name) {
1078 IOServiceMatching(name); // expected-warning{{leak}}
1081 void IOServiceNameMatching_wrapper(const char * name) {
1082 IOServiceNameMatching(name); // expected-warning{{leak}}
1085 CF_RETURNS_RETAINED CFDictionaryRef CreateDict(void);
1087 void IOServiceAddNotification_wrapper(mach_port_t mainPort, const io_name_t notificationType,
1088 mach_port_t wakePort, uintptr_t reference, io_iterator_t * notification ) {
1090 CFDictionaryRef matching = CreateDict();
1091 CFRelease(matching);
1092 IOServiceAddNotification(mainPort, notificationType, matching, // expected-warning{{used after it is released}} expected-warning{{deprecated}}
1093 wakePort, reference, notification);
1096 void IORegistryEntryIDMatching_wrapper(uint64_t entryID ) {
1097 IORegistryEntryIDMatching(entryID); // expected-warning{{leak}}
1100 void IOOpenFirmwarePathMatching_wrapper(mach_port_t mainPort, uint32_t options,
1101 const char * path) {
1102 IOOpenFirmwarePathMatching(mainPort, options, path); // expected-warning{{leak}}
1105 void IOServiceGetMatchingService_wrapper(mach_port_t mainPort) {
1106 CFDictionaryRef matching = CreateDict();
1107 IOServiceGetMatchingService(mainPort, matching);
1108 CFRelease(matching); // expected-warning{{used after it is released}}
1111 void IOServiceGetMatchingServices_wrapper(mach_port_t mainPort, io_iterator_t *existing) {
1112 CFDictionaryRef matching = CreateDict();
1113 IOServiceGetMatchingServices(mainPort, matching, existing);
1114 CFRelease(matching); // expected-warning{{used after it is released}}
1117 void IOServiceAddMatchingNotification_wrapper(IONotificationPortRef notifyPort, const io_name_t notificationType,
1118 IOServiceMatchingCallback callback, void * refCon, io_iterator_t * notification) {
1120 CFDictionaryRef matching = CreateDict();
1121 IOServiceAddMatchingNotification(notifyPort, notificationType, matching, callback, refCon, notification);
1122 CFRelease(matching); // expected-warning{{used after it is released}}
1125 //===----------------------------------------------------------------------===//
1126 // Test of handling objects whose references "escape" to containers.
1127 //===----------------------------------------------------------------------===//
1129 void CFDictionaryAddValue(CFMutableDictionaryRef, void *, void *);
1131 // <rdar://problem/6539791>
1132 void rdar_6539791(CFMutableDictionaryRef y, void* key, void* val_key) {
1133 CFMutableDictionaryRef x = CFDictionaryCreateMutable(kCFAllocatorDefault, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
1134 CFDictionaryAddValue(y, key, x);
1135 CFRelease(x); // the dictionary keeps a reference, so the object isn't deallocated yet
1137 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z);
1139 CFDictionaryAddValue(x, val_key, (void*)value); // no-warning
1141 CFDictionaryAddValue(y, val_key, (void*)value); // no-warning
1145 // <rdar://problem/6560661>
1146 // Same issue, except with "AppendValue" functions.
1147 void rdar_6560661(CFMutableArrayRef x) {
1149 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z);
1150 // CFArrayAppendValue keeps a reference to value.
1151 CFArrayAppendValue(x, value);
1154 CFRelease(value); // no-warning
1157 // <rdar://problem/7152619>
1158 // Same issue, excwept with "CFAttributeStringSetAttribute".
1159 void rdar_7152619(CFStringRef str) {
1160 CFAttributedStringRef string = CFAttributedStringCreate(kCFAllocatorDefault, str, 0);
1161 CFMutableAttributedStringRef attrString = CFAttributedStringCreateMutableCopy(kCFAllocatorDefault, 100, string);
1163 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1164 CFAttributedStringSetAttribute(attrString, CFRangeMake(0, 1), str, number);
1167 CFRelease(attrString);
1170 //===----------------------------------------------------------------------===//
1171 // Test of handling CGGradientXXX functions.
1172 //===----------------------------------------------------------------------===//
1174 void rdar_7184450(CGContextRef myContext, CGFloat x, CGPoint myStartPoint,
1175 CGPoint myEndPoint) {
1176 size_t num_locations = 6;
1177 CGFloat locations[6] = { 0.0, 0.265, 0.28, 0.31, 0.36, 1.0 };
1178 CGFloat components[28] = { 239.0/256.0, 167.0/256.0, 170.0/256.0,
1180 207.0/255.0, 39.0/255.0, 39.0/255.0, x,
1181 147.0/255.0, 21.0/255.0, 22.0/255.0, x,
1182 175.0/255.0, 175.0/255.0, 175.0/255.0, x,
1183 255.0/255.0,255.0/255.0, 255.0/255.0, x,
1184 255.0/255.0,255.0/255.0, 255.0/255.0, x
1187 CGGradientRef myGradient =
1188 CGGradientCreateWithColorComponents(CGColorSpaceCreateDeviceRGB(), // expected-warning{{leak}}
1189 components, locations, num_locations);
1191 CGContextDrawLinearGradient(myContext, myGradient, myStartPoint, myEndPoint,
1193 CGGradientRelease(myGradient);
1196 void rdar_7184450_pos(CGContextRef myContext, CGFloat x, CGPoint myStartPoint,
1197 CGPoint myEndPoint) {
1198 size_t num_locations = 6;
1199 CGFloat locations[6] = { 0.0, 0.265, 0.28, 0.31, 0.36, 1.0 };
1200 CGFloat components[28] = { 239.0/256.0, 167.0/256.0, 170.0/256.0,
1202 207.0/255.0, 39.0/255.0, 39.0/255.0, x,
1203 147.0/255.0, 21.0/255.0, 22.0/255.0, x,
1204 175.0/255.0, 175.0/255.0, 175.0/255.0, x,
1205 255.0/255.0,255.0/255.0, 255.0/255.0, x,
1206 255.0/255.0,255.0/255.0, 255.0/255.0, x
1209 CGGradientRef myGradient =
1210 CGGradientCreateWithColorComponents(CGColorSpaceCreateDeviceRGB(), components, locations, num_locations); // expected-warning 2 {{leak}}
1212 CGContextDrawLinearGradient(myContext, myGradient, myStartPoint, myEndPoint,
1216 //===----------------------------------------------------------------------===//
1217 // <rdar://problem/7299394> clang false positive: retained instance passed to
1218 // thread in pthread_create marked as leak
1220 // Until we have full IPA, the analyzer should stop tracking the reference
1221 // count of objects passed to pthread_create.
1223 //===----------------------------------------------------------------------===//
1225 struct _opaque_pthread_t {};
1226 struct _opaque_pthread_attr_t {};
1227 typedef struct _opaque_pthread_t *__darwin_pthread_t;
1228 typedef struct _opaque_pthread_attr_t __darwin_pthread_attr_t;
1229 typedef __darwin_pthread_t pthread_t;
1230 typedef __darwin_pthread_attr_t pthread_attr_t;
1231 typedef unsigned long __darwin_pthread_key_t;
1232 typedef __darwin_pthread_key_t pthread_key_t;
1234 int pthread_create(pthread_t *, const pthread_attr_t *,
1235 void *(*)(void *), void *);
1237 int pthread_setspecific(pthread_key_t key, const void *value);
1239 void *rdar_7299394_start_routine(void *p) {
1243 void rdar_7299394(pthread_attr_t *attr, pthread_t *thread, void *args) {
1244 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1245 pthread_create(thread, attr, rdar_7299394_start_routine, number);
1247 void rdar_7299394_positive(pthread_attr_t *attr, pthread_t *thread) {
1248 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1251 //===----------------------------------------------------------------------===//
1252 // <rdar://problem/11282706> false positive with not understanding thread
1254 //===----------------------------------------------------------------------===//
1256 void rdar11282706(pthread_key_t key) {
1257 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1258 pthread_setspecific(key, (void*) number);
1261 //===----------------------------------------------------------------------===//
1262 // <rdar://problem/7283567> False leak associated with call to
1263 // CVPixelBufferCreateWithBytes ()
1265 // According to the Core Video Reference (ADC), CVPixelBufferCreateWithBytes and
1266 // CVPixelBufferCreateWithPlanarBytes can release (via a callback) the
1267 // pixel buffer object. These test cases show how the analyzer stops tracking
1268 // the reference count for the objects passed for this argument. This
1269 // could be made smarter.
1270 //===----------------------------------------------------------------------===//
1272 typedef int int32_t;
1273 typedef UInt32 FourCharCode;
1274 typedef FourCharCode OSType;
1275 typedef uint64_t CVOptionFlags;
1276 typedef int32_t CVReturn;
1277 typedef struct __CVBuffer *CVBufferRef;
1278 typedef CVBufferRef CVImageBufferRef;
1279 typedef CVImageBufferRef CVPixelBufferRef;
1280 typedef void (*CVPixelBufferReleaseBytesCallback)( void *releaseRefCon, const void *baseAddress );
1282 extern CVReturn CVPixelBufferCreateWithBytes(CFAllocatorRef allocator,
1285 OSType pixelFormatType,
1288 CVPixelBufferReleaseBytesCallback releaseCallback,
1289 void *releaseRefCon,
1290 CFDictionaryRef pixelBufferAttributes,
1291 CVPixelBufferRef *pixelBufferOut) ;
1293 typedef void (*CVPixelBufferReleasePlanarBytesCallback)( void *releaseRefCon, const void *dataPtr, size_t dataSize, size_t numberOfPlanes, const void *planeAddresses[] );
1295 extern CVReturn CVPixelBufferCreateWithPlanarBytes(CFAllocatorRef allocator,
1298 OSType pixelFormatType,
1301 size_t numberOfPlanes,
1302 void *planeBaseAddress[],
1303 size_t planeWidth[],
1304 size_t planeHeight[],
1305 size_t planeBytesPerRow[],
1306 CVPixelBufferReleasePlanarBytesCallback releaseCallback,
1307 void *releaseRefCon,
1308 CFDictionaryRef pixelBufferAttributes,
1309 CVPixelBufferRef *pixelBufferOut) ;
1311 extern CVReturn CVPixelBufferCreateWithBytes(CFAllocatorRef allocator,
1314 OSType pixelFormatType,
1317 CVPixelBufferReleaseBytesCallback releaseCallback,
1318 void *releaseRefCon,
1319 CFDictionaryRef pixelBufferAttributes,
1320 CVPixelBufferRef *pixelBufferOut) ;
1322 CVReturn rdar_7283567(CFAllocatorRef allocator, size_t width, size_t height,
1323 OSType pixelFormatType, void *baseAddress,
1325 CVPixelBufferReleaseBytesCallback releaseCallback,
1326 CFDictionaryRef pixelBufferAttributes,
1327 CVPixelBufferRef *pixelBufferOut) {
1329 // For the allocated object, it doesn't really matter what type it is
1330 // for the purpose of this test. All we want to show is that
1331 // this is freed later by the callback.
1332 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1334 return CVPixelBufferCreateWithBytes(allocator, width, height, pixelFormatType,
1335 baseAddress, bytesPerRow, releaseCallback,
1336 number, // potentially released by callback
1337 pixelBufferAttributes, pixelBufferOut) ;
1340 CVReturn rdar_7283567_2(CFAllocatorRef allocator, size_t width, size_t height,
1341 OSType pixelFormatType, void *dataPtr, size_t dataSize,
1342 size_t numberOfPlanes, void *planeBaseAddress[],
1343 size_t planeWidth[], size_t planeHeight[], size_t planeBytesPerRow[],
1344 CVPixelBufferReleasePlanarBytesCallback releaseCallback,
1345 CFDictionaryRef pixelBufferAttributes,
1346 CVPixelBufferRef *pixelBufferOut) {
1348 // For the allocated object, it doesn't really matter what type it is
1349 // for the purpose of this test. All we want to show is that
1350 // this is freed later by the callback.
1351 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1353 return CVPixelBufferCreateWithPlanarBytes(allocator,
1354 width, height, pixelFormatType, dataPtr, dataSize,
1355 numberOfPlanes, planeBaseAddress, planeWidth,
1356 planeHeight, planeBytesPerRow, releaseCallback,
1357 number, // potentially released by callback
1358 pixelBufferAttributes, pixelBufferOut) ;
1361 #pragma clang arc_cf_code_audited begin
1362 typedef struct SomeOpaqueStruct *CMSampleBufferRef;
1363 CVImageBufferRef _Nonnull CMSampleBufferGetImageBuffer(CMSampleBufferRef _Nonnull sbuf);
1364 #pragma clang arc_cf_code_audited end
1366 CVBufferRef _Nullable CVBufferRetain(CVBufferRef _Nullable buffer);
1367 void CVBufferRelease(CF_CONSUMED CVBufferRef _Nullable buffer);
1369 void testCVPrefixRetain(CMSampleBufferRef sbuf) {
1370 // Make sure RetainCountChecker treats CVFooRetain() as a CF-style retain.
1371 CVPixelBufferRef pixelBuf = CMSampleBufferGetImageBuffer(sbuf);
1372 CVBufferRetain(pixelBuf);
1373 CVBufferRelease(pixelBuf); // no-warning
1376 // Make sure result of CVFooRetain() is the same as its argument.
1377 CVPixelBufferRef pixelBufAlias = CVBufferRetain(pixelBuf);
1378 CVBufferRelease(pixelBufAlias); // no-warning
1381 typedef signed long SInt32;
1382 typedef SInt32 OSStatus;
1383 typedef FourCharCode CMVideoCodecType;
1386 typedef UInt32 VTEncodeInfoFlags; enum {
1387 kVTEncodeInfo_Asynchronous = 1UL << 0,
1388 kVTEncodeInfo_FrameDropped = 1UL << 1,
1396 typedef void (*VTCompressionOutputCallback)(
1397 void * _Nullable outputCallbackRefCon,
1398 void * _Nullable sourceFrameRefCon,
1400 VTEncodeInfoFlags infoFlags,
1401 _Nullable CMSampleBufferRef sampleBuffer );
1403 typedef struct OpaqueVTCompressionSession* VTCompressionSessionRef;
1406 VTCompressionSessionCreate(_Nullable CFAllocatorRef allocator,
1409 CMVideoCodecType codecType,
1410 _Nullable CFDictionaryRef encoderSpecification,
1411 _Nullable CFDictionaryRef sourceImageBufferAttributes,
1412 _Nullable CFAllocatorRef compressedDataAllocator,
1413 _Nullable VTCompressionOutputCallback outputCallback,
1414 void * _Nullable outputCallbackRefCon,
1415 CF_RETURNS_RETAINED _Nullable VTCompressionSessionRef * _Nonnull compressionSessionOut);
1418 VTCompressionSessionEncodeFrame(
1419 _Nonnull VTCompressionSessionRef session,
1420 _Nonnull CVImageBufferRef imageBuffer,
1421 CMTime presentationTimeStamp,
1423 _Nullable CFDictionaryRef frameProperties,
1424 void * _Nullable sourceFrameRefCon,
1425 VTEncodeInfoFlags * _Nullable infoFlagsOut);
1427 OSStatus test_VTCompressionSessionCreateAndEncode_CallbackReleases(
1428 _Nullable CFAllocatorRef allocator,
1431 CMVideoCodecType codecType,
1432 _Nullable CFDictionaryRef encoderSpecification,
1433 _Nullable CFDictionaryRef sourceImageBufferAttributes,
1434 _Nullable CFAllocatorRef compressedDataAllocator,
1435 _Nullable VTCompressionOutputCallback outputCallback,
1437 _Nonnull CVImageBufferRef imageBuffer,
1438 CMTime presentationTimeStamp,
1440 _Nullable CFDictionaryRef frameProperties
1443 // The outputCallback is passed both contexts and so can release either.
1444 NSNumber *contextForCreate = [[NSNumber alloc] initWithInt:5]; // no-warning
1445 NSNumber *contextForEncode = [[NSNumber alloc] initWithInt:6]; // no-warning
1447 VTCompressionSessionRef session = 0;
1448 OSStatus status = VTCompressionSessionCreate(allocator,
1449 width, height, codecType, encoderSpecification,
1450 sourceImageBufferAttributes,
1451 compressedDataAllocator, outputCallback, contextForCreate,
1454 VTEncodeInfoFlags encodeInfoFlags;
1456 status = VTCompressionSessionEncodeFrame(session, imageBuffer,
1457 presentationTimeStamp, duration, frameProperties, contextForEncode,
1463 //===----------------------------------------------------------------------===//
1464 // <rdar://problem/7358899> False leak associated with
1465 // CGBitmapContextCreateWithData
1466 //===----------------------------------------------------------------------===//
1467 typedef uint32_t CGBitmapInfo;
1468 typedef void (*CGBitmapContextReleaseDataCallback)(void *releaseInfo, void *data);
1470 CGContextRef CGBitmapContextCreateWithData(void *data,
1471 size_t width, size_t height, size_t bitsPerComponent,
1472 size_t bytesPerRow, CGColorSpaceRef space, CGBitmapInfo bitmapInfo,
1473 CGBitmapContextReleaseDataCallback releaseCallback, void *releaseInfo);
1475 void rdar_7358899(void *data,
1476 size_t width, size_t height, size_t bitsPerComponent,
1477 size_t bytesPerRow, CGColorSpaceRef space, CGBitmapInfo bitmapInfo,
1478 CGBitmapContextReleaseDataCallback releaseCallback) {
1480 // For the allocated object, it doesn't really matter what type it is
1481 // for the purpose of this test. All we want to show is that
1482 // this is freed later by the callback.
1483 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1485 CGBitmapContextCreateWithData(data, width, height, bitsPerComponent, // expected-warning{{leak}}
1486 bytesPerRow, space, bitmapInfo, releaseCallback, number);
1489 //===----------------------------------------------------------------------===//
1490 // <rdar://problem/7265711> allow 'new', 'copy', 'alloc', 'init' prefix to
1491 // start before '_' when determining Cocoa fundamental rule
1493 // Previously the retain/release checker just skipped prefixes before the
1494 // first '_' entirely. Now the checker honors the prefix if it results in a
1495 // recognizable naming convention (e.g., 'new', 'init').
1496 //===----------------------------------------------------------------------===//
1498 @interface RDar7265711 {}
1502 void rdar7265711_a(RDar7265711 *x) {
1503 id y = [x new_stuff]; // expected-warning{{leak}}
1506 void rdar7265711_b(RDar7265711 *x) {
1507 id y = [x new_stuff]; // no-warning
1511 //===----------------------------------------------------------------------===//
1512 // <rdar://problem/7306898> clang thinks [NSCursor dragCopyCursor] returns a
1513 // retained reference
1514 //===----------------------------------------------------------------------===//
1516 @interface NSCursor : NSObject
1517 + (NSCursor *)dragCopyCursor;
1520 void rdar7306898(void) {
1521 // 'dragCopyCursor' does not follow Cocoa's fundamental rule. It is a noun, not an sentence
1522 // implying a 'copy' of something.
1523 NSCursor *c = [NSCursor dragCopyCursor]; // no-warning
1524 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1527 //===----------------------------------------------------------------------===//
1528 // <rdar://problem/7252064> sending 'release', 'retain', etc. to a Class
1529 // directly is not likely what the user intended
1530 //===----------------------------------------------------------------------===//
1532 @interface RDar7252064 : NSObject @end
1533 void rdar7252064(void) {
1534 [RDar7252064 release]; // expected-warning{{The 'release' message should be sent to instances of class 'RDar7252064' and not the class directly}}
1535 [RDar7252064 retain]; // expected-warning{{The 'retain' message should be sent to instances of class 'RDar7252064' and not the class directly}}
1536 [RDar7252064 autorelease]; // expected-warning{{The 'autorelease' message should be sent to instances of class 'RDar7252064' and not the class directly}}
1537 [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}}
1540 //===----------------------------------------------------------------------===//
1541 // Tests of ownership attributes.
1542 //===----------------------------------------------------------------------===//
1544 typedef NSString* MyStringTy;
1548 @interface TestOwnershipAttr : NSObject
1549 - (NSString*) returnsAnOwnedString NS_RETURNS_RETAINED; // no-warning
1550 - (NSString*) returnsAnOwnedCFString CF_RETURNS_RETAINED; // no-warning
1551 - (MyStringTy) returnsAnOwnedTypedString NS_RETURNS_RETAINED; // no-warning
1552 - (NSString*) newString NS_RETURNS_NOT_RETAINED; // no-warning
1553 - (NSString*) newString_auto NS_RETURNS_AUTORELEASED; // no-warning
1554 - (NSString*) newStringNoAttr;
1555 - (int) returnsAnOwnedInt NS_RETURNS_RETAINED; // expected-warning{{'ns_returns_retained' attribute only applies to methods that return an Objective-C object}}
1556 - (id) pseudoInit NS_CONSUMES_SELF NS_RETURNS_RETAINED;
1557 + (void) consume:(id) NS_CONSUMED x;
1558 + (void) consume2:(id) CF_CONSUMED x;
1561 static int ownership_attribute_doesnt_go_here NS_RETURNS_RETAINED; // expected-warning{{'ns_returns_retained' only applies to function types; type here is 'int'}}
1563 void test_attr_1(TestOwnershipAttr *X) {
1564 NSString *str = [X returnsAnOwnedString]; // expected-warning{{leak}}
1567 void test_attr_1b(TestOwnershipAttr *X) {
1568 NSString *str = [X returnsAnOwnedCFString]; // expected-warning{{leak}}
1571 void test_attr1c(TestOwnershipAttr *X) {
1572 NSString *str = [X newString]; // no-warning
1573 NSString *str2 = [X newStringNoAttr]; // expected-warning{{leak}}
1574 NSString *str3 = [X newString_auto]; // no-warning
1575 NSString *str4 = [[X newString_auto] retain]; // expected-warning {{leak}}
1578 void testattr2_a(void) {
1579 TestOwnershipAttr *x = [TestOwnershipAttr alloc]; // expected-warning{{leak}}
1582 void testattr2_b(void) {
1583 TestOwnershipAttr *x = [[TestOwnershipAttr alloc] pseudoInit]; // expected-warning{{leak}}
1586 void testattr2_b_11358224_self_assign_looses_the_leak(void) {
1587 TestOwnershipAttr *x = [[TestOwnershipAttr alloc] pseudoInit];// expected-warning{{leak}}
1591 void testattr2_c(void) {
1592 TestOwnershipAttr *x = [[TestOwnershipAttr alloc] pseudoInit]; // no-warning
1596 void testattr3(void) {
1597 TestOwnershipAttr *x = [TestOwnershipAttr alloc]; // no-warning
1598 [TestOwnershipAttr consume:x];
1599 TestOwnershipAttr *y = [TestOwnershipAttr alloc]; // no-warning
1600 [TestOwnershipAttr consume2:y];
1603 void consume_ns(id NS_CONSUMED x);
1604 void consume_cf(id CF_CONSUMED x);
1606 void testattr4(void) {
1607 TestOwnershipAttr *x = [TestOwnershipAttr alloc]; // no-warning
1609 TestOwnershipAttr *y = [TestOwnershipAttr alloc]; // no-warning
1613 @interface TestOwnershipAttr2 : NSObject
1614 - (NSString*) newString NS_RETURNS_NOT_RETAINED; // no-warning
1617 @implementation TestOwnershipAttr2
1618 - (NSString*) newString {
1619 return [NSString alloc]; // expected-warning {{Potential leak of an object}}
1623 @interface MyClassTestCFAttr : NSObject {}
1624 - (NSDate*) returnsCFRetained CF_RETURNS_RETAINED;
1625 - (CFDateRef) returnsCFRetainedAsCF CF_RETURNS_RETAINED;
1626 - (CFDateRef) newCFRetainedAsCF CF_RETURNS_NOT_RETAINED;
1627 - (CFDateRef) newCFRetainedAsCFNoAttr;
1628 - (NSDate*) alsoReturnsRetained;
1629 - (CFDateRef) alsoReturnsRetainedAsCF;
1630 - (NSDate*) returnsNSRetained NS_RETURNS_RETAINED;
1634 CFDateRef returnsRetainedCFDate(void) {
1635 return CFDateCreate(0, CFAbsoluteTimeGetCurrent());
1638 @implementation MyClassTestCFAttr
1639 - (NSDate*) returnsCFRetained {
1640 return (NSDate*) returnsRetainedCFDate(); // No leak.
1643 - (CFDateRef) returnsCFRetainedAsCF {
1644 return returnsRetainedCFDate(); // No leak.
1647 - (CFDateRef) newCFRetainedAsCF {
1648 return (CFDateRef)[(id)[self returnsCFRetainedAsCF] autorelease];
1651 - (CFDateRef) newCFRetainedAsCFNoAttr {
1652 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}}
1655 - (NSDate*) alsoReturnsRetained {
1656 return (NSDate*) returnsRetainedCFDate(); // expected-warning{{leak}}
1659 - (CFDateRef) alsoReturnsRetainedAsCF {
1660 return returnsRetainedCFDate(); // expected-warning{{leak}}
1664 - (NSDate*) returnsNSRetained {
1665 return (NSDate*) returnsRetainedCFDate(); // no-warning
1669 //===----------------------------------------------------------------------===//
1670 // Test that leaks post-dominated by "panic" functions are not reported.
1672 // <rdar://problem/5905851> do not report a leak when post-dominated by a call
1673 // to a noreturn or panic function
1674 //===----------------------------------------------------------------------===//
1676 void panic(void) __attribute__((noreturn));
1677 void panic_not_in_hardcoded_list(void) __attribute__((noreturn));
1679 void test_panic_negative(void) {
1681 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // expected-warning{{leak}}
1684 void test_panic_positive(void) {
1686 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // no-warning
1690 void test_panic_neg_2(int x) {
1692 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // expected-warning{{leak}}
1697 void test_panic_pos_2(int x) {
1699 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // no-warning
1703 // This showed up in <rdar://problem/7796563>, where we silently missed checking
1704 // the function type for noreturn. "panic()" is a hard-coded known panic function
1705 // that isn't always noreturn.
1706 panic_not_in_hardcoded_list();
1710 //===----------------------------------------------------------------------===//
1711 // Test uses of blocks (closures)
1712 //===----------------------------------------------------------------------===//
1714 void test_blocks_1_pos(void) {
1715 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1719 void test_blocks_1_indirect_release(void) {
1720 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1721 ^{ [number release]; }();
1724 void test_blocks_1_indirect_retain(void) {
1725 // Eventually this should be reported as a leak.
1726 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1727 ^{ [number retain]; }();
1730 void test_blocks_1_indirect_release_via_call(void) {
1731 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1732 ^(NSObject *o){ [o release]; }(number);
1735 void test_blocks_1_indirect_retain_via_call(void) {
1736 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning {{leak}}
1737 ^(NSObject *o){ [o retain]; }(number);
1740 //===--------------------------------------------------------------------===//
1741 // Test sending message to super that returns an object alias. Previously
1742 // this caused a crash in the analyzer.
1743 //===--------------------------------------------------------------------===//
1745 @interface Rdar8015556 : NSObject {} @end
1746 @implementation Rdar8015556
1748 return [super retain];
1752 // <rdar://problem/8272168> - Correcly handle Class<...> in Cocoa Conventions
1755 @protocol Prot_R8272168 @end
1756 Class <Prot_R8272168> GetAClassThatImplementsProt_R8272168(void);
1757 void r8272168(void) {
1758 GetAClassThatImplementsProt_R8272168();
1761 // Test case for <rdar://problem/8356342>, which in the past triggered
1762 // a false positive.
1763 @interface RDar8356342
1764 - (NSDate*) rdar8356342:(NSDate *)inValue;
1767 @implementation RDar8356342
1768 - (NSDate*) rdar8356342:(NSDate*)inValue {
1769 NSDate *outValue = inValue;
1771 outValue = [[NSDate alloc] init]; // no-warning
1773 if (outValue != inValue)
1774 [outValue autorelease];
1780 // <rdar://problem/8724287> - This test case previously crashed because
1781 // of a bug in BugReporter.
1782 extern const void *CFDictionaryGetValue(CFDictionaryRef theDict, const void *key);
1783 typedef struct __CFError * CFErrorRef;
1784 extern const CFStringRef kCFErrorUnderlyingErrorKey;
1785 extern CFDictionaryRef CFErrorCopyUserInfo(CFErrorRef err);
1786 static void rdar_8724287(CFErrorRef error)
1788 CFErrorRef error_to_dump;
1790 error_to_dump = error;
1791 while (error_to_dump != ((void*)0)) {
1792 CFDictionaryRef info;
1794 info = CFErrorCopyUserInfo(error_to_dump); // expected-warning{{Potential leak of an object}}
1796 if (info != ((void*)0)) {
1799 error_to_dump = (CFErrorRef) CFDictionaryGetValue(info, kCFErrorUnderlyingErrorKey);
1803 // <rdar://problem/9234108> - Make sure the model applies cf_consumed
1804 // correctly in argument positions besides the first.
1805 extern void *CFStringCreate(void);
1806 extern void rdar_9234108_helper(void *key, void * CF_CONSUMED value);
1807 void rdar_9234108(void) {
1808 rdar_9234108_helper(0, CFStringCreate());
1811 // <rdar://problem/9726279> - Make sure that objc_method_family works
1812 // to override naming conventions.
1817 typedef struct TwoDoubles TwoDoubles;
1819 @interface NSValue (Mine)
1820 - (id)_prefix_initWithTwoDoubles:(TwoDoubles)twoDoubles __attribute__((objc_method_family(init)));
1823 @implementation NSValue (Mine)
1824 - (id)_prefix_initWithTwoDoubles:(TwoDoubles)twoDoubles
1830 void rdar9726279(void) {
1831 TwoDoubles twoDoubles = { 0.0, 0.0 };
1832 NSValue *value = [[NSValue alloc] _prefix_initWithTwoDoubles:twoDoubles];
1836 // <rdar://problem/9732321>
1837 // Test camelcase support for CF conventions. While Core Foundation APIs
1838 // don't use camel casing, other code is allowed to use it.
1839 CFArrayRef camelcase_create_1(void) {
1840 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1843 CFArrayRef camelcase_createno(void) {
1844 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1847 CFArrayRef camelcase_copy(void) {
1848 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1851 CFArrayRef camelcase_copying(void) {
1852 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1855 CFArrayRef copyCamelCase(void) {
1856 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1859 CFArrayRef __copyCamelCase(void) {
1860 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1863 CFArrayRef __createCamelCase(void) {
1864 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1867 CFArrayRef camel_create(void) {
1868 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1872 CFArrayRef camel_creat(void) {
1873 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1876 CFArrayRef camel_copy(void) {
1877 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1880 CFArrayRef camel_copyMachine(void) {
1881 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1884 CFArrayRef camel_copymachine(void) {
1885 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1888 // rdar://problem/8024350
1890 - (id) clone; // expected-note 2 {{method declared here}}
1892 @interface F18 : NSObject<F18P> @end
1894 - (id) clone NS_RETURNS_RETAINED; // expected-warning {{overriding method has mismatched ns_returns_retained attributes}}
1898 - (id) clone { // expected-warning {{overriding method has mismatched ns_returns_retained attributes}}
1904 void rdar6582778(void) {
1905 CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
1906 CFTypeRef vals[] = { CFDateCreate(0, t) }; // expected-warning {{leak}}
1911 void rdar6582778_2(void) {
1912 CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
1913 global = CFDateCreate(0, t); // no-warning
1916 // <rdar://problem/10232019> - Test that objects passed to containers
1917 // are marked "escaped".
1919 void rdar10232019(void) {
1920 NSMutableArray *array = [NSMutableArray array];
1922 NSString *string = [[NSString alloc] initWithUTF8String:"foo"];
1923 [array addObject:string];
1926 NSString *otherString = [string stringByAppendingString:@"bar"]; // no-warning
1927 NSLog(@"%@", otherString);
1930 void rdar10232019_positive(void) {
1931 NSMutableArray *array = [NSMutableArray array];
1933 NSString *string = [[NSString alloc] initWithUTF8String:"foo"];
1936 NSString *otherString = [string stringByAppendingString:@"bar"]; // expected-warning {{Reference-counted object is used after it is release}}
1937 NSLog(@"%@", otherString);
1940 // RetainCountChecker support for XPC.
1941 // <rdar://problem/9658496>
1942 typedef void * xpc_object_t;
1943 xpc_object_t _CFXPCCreateXPCObjectFromCFObject(CFTypeRef cf);
1944 void xpc_release(xpc_object_t object);
1946 void rdar9658496(void) {
1949 cf = CFStringCreateWithCString( ((CFAllocatorRef)0), "test", kCFStringEncodingUTF8 ); // no-warning
1950 xpc = _CFXPCCreateXPCObjectFromCFObject( cf );
1955 // Support annotations with method families.
1956 @interface RDar10824732 : NSObject
1957 - (id)initWithObj:(id CF_CONSUMED)obj;
1960 @implementation RDar10824732
1961 - (id)initWithObj:(id)obj {
1963 return [super init];
1967 void rdar_10824732(void) {
1969 NSString *obj = @"test";
1970 RDar10824732 *foo = [[RDar10824732 alloc] initWithObj:obj]; // no-warning
1975 // Stop tracking objects passed to functions, which take callbacks as parameters.
1977 typedef int (*CloseCallback) (void *);
1978 void ReaderForIO(CloseCallback ioclose, void *ioctx);
1979 int IOClose(void *context);
1981 @protocol SInS <NSObject>
1984 @interface radar10973977 : NSObject
1989 @implementation radar10973977
1992 id<SInS> inputS = [[self inputS] retain];
1993 ReaderForIO(IOClose, inputS);
2001 // Object escapes through a selector callback: radar://11398514
2003 @interface MySheetController
2005 - (void)showDoSomethingSheetAction:(id)action;
2006 - (void)sheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo;
2009 @implementation MySheetController
2010 - (id<SInS>)inputS {
2013 - (void)showDoSomethingSheetAction:(id)action {
2014 id<SInS> inputS = [[self inputS] retain];
2018 didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:)
2019 contextInfo:(void *)inputS]; // no - warning
2021 - (void)sheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo {
2023 id contextObject = (id)contextInfo;
2024 [contextObject release];
2027 - (id)copyAutoreleaseRadar13081402 {
2028 id x = [[[NSString alloc] initWithUTF8String:"foo"] autorelease];
2030 return x; // no warning
2034 //===----------------------------------------------------------------------===//
2035 // Test returning allocated memory in a struct.
2037 // We currently don't have a general way to track pointers that "escape".
2038 // Here we test that RetainCountChecker doesn't get excited about returning
2039 // allocated CF objects in struct fields.
2040 //===----------------------------------------------------------------------===//
2041 void *malloc(size_t);
2042 struct rdar11104566 { CFStringRef myStr; };
2043 struct rdar11104566 test_rdar11104566(void) {
2044 CFStringRef cf = CFStringCreateWithCString( ((CFAllocatorRef)0), "test", kCFStringEncodingUTF8 ); // no-warning
2045 struct rdar11104566 V;
2047 return V; // no-warning
2050 struct rdar11104566 *test_2_rdar11104566(void) {
2051 CFStringRef cf = CFStringCreateWithCString( ((CFAllocatorRef)0), "test", kCFStringEncodingUTF8 ); // no-warning
2052 struct rdar11104566 *V = (struct rdar11104566 *) malloc(sizeof(*V));
2054 return V; // no-warning
2057 //===----------------------------------------------------------------------===//
2058 // ObjC literals support.
2059 //===----------------------------------------------------------------------===//
2061 void test_objc_arrays(void) {
2062 { // CASE ONE -- OBJECT IN ARRAY CREATED DIRECTLY
2063 NSObject *o = [[NSObject alloc] init];
2064 NSArray *a = [[NSArray alloc] initWithObjects:o, (void*)0]; // expected-warning {{leak}}
2070 { // CASE TWO -- OBJECT IN ARRAY CREATED BY DUPING AUTORELEASED ARRAY
2071 NSObject *o = [[NSObject alloc] init];
2072 NSArray *a1 = [NSArray arrayWithObjects:o, (void*)0];
2073 NSArray *a2 = [[NSArray alloc] initWithArray:a1]; // expected-warning {{leak}}
2079 { // CASE THREE -- OBJECT IN RETAINED @[]
2080 NSObject *o = [[NSObject alloc] init];
2081 NSArray *a3 = [@[o] retain]; // expected-warning {{leak}}
2087 { // CASE FOUR -- OBJECT IN ARRAY CREATED BY DUPING @[]
2088 NSObject *o = [[NSObject alloc] init];
2089 NSArray *a = [[NSArray alloc] initWithArray:@[o]]; // expected-warning {{leak}}
2096 { // CASE FIVE -- OBJECT IN RETAINED @{}
2097 NSValue *o = [[NSValue alloc] init];
2098 NSDictionary *a = [@{o : o} retain]; // expected-warning {{leak}}
2106 void test_objc_integer_literals(void) {
2107 id value = [@1 retain]; // expected-warning {{leak}}
2108 [value description];
2111 void test_objc_boxed_expressions(int x, const char *y) {
2112 id value = [@(x) retain]; // expected-warning {{leak}}
2113 [value description];
2115 value = [@(y) retain]; // expected-warning {{leak}}
2116 [value description];
2119 // Test NSLog doesn't escape tracked objects.
2120 void rdar11400885(int y)
2123 NSString *printString;
2125 printString = [[NSString alloc] init];
2127 printString = [[NSString alloc] init];
2128 NSLog(@"Once %@", printString);
2129 [printString release];
2130 NSLog(@"Again: %@", printString); // expected-warning {{Reference-counted object is used after it is released}}
2134 id makeCollectableNonLeak(void) {
2135 extern CFTypeRef CFCreateSomething(void);
2137 CFTypeRef object = CFCreateSomething(); // +1
2138 CFRetain(object); // +2
2139 id objCObject = NSMakeCollectable(object); // +2
2140 [objCObject release]; // +1
2141 return [objCObject autorelease]; // +0
2144 void consumeAndStopTracking(id NS_CONSUMED obj, void (^callback)(void));
2145 void CFConsumeAndStopTracking(CFTypeRef CF_CONSUMED obj, void (^callback)(void));
2147 void testConsumeAndStopTracking(void) {
2148 id retained = [@[] retain]; // +1
2149 consumeAndStopTracking(retained, ^{}); // no-warning
2151 id doubleRetained = [[@[] retain] retain]; // +2
2152 consumeAndStopTracking(doubleRetained, ^{
2153 [doubleRetained release];
2156 id unretained = @[]; // +0
2157 consumeAndStopTracking(unretained, ^{}); // expected-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
2160 void testCFConsumeAndStopTracking(void) {
2161 id retained = [@[] retain]; // +1
2162 CFConsumeAndStopTracking((CFTypeRef)retained, ^{}); // no-warning
2164 id doubleRetained = [[@[] retain] retain]; // +2
2165 CFConsumeAndStopTracking((CFTypeRef)doubleRetained, ^{
2166 [doubleRetained release];
2169 id unretained = @[]; // +0
2170 CFConsumeAndStopTracking((CFTypeRef)unretained, ^{}); // expected-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
2172 //===----------------------------------------------------------------------===//
2173 // Test 'pragma clang arc_cf_code_audited' support.
2174 //===----------------------------------------------------------------------===//
2176 typedef void *MyCFType;
2177 #pragma clang arc_cf_code_audited begin
2178 MyCFType CreateMyCFType(void);
2179 #pragma clang arc_cf_code_audited end
2181 void test_custom_cf(void) {
2182 MyCFType x = CreateMyCFType(); // expected-warning {{leak of an object stored into 'x'}}
2185 //===----------------------------------------------------------------------===//
2186 // Test calling CFPlugInInstanceCreate, which appears in CF but doesn't
2187 // return a CF object.
2188 //===----------------------------------------------------------------------===//
2190 void test_CFPlugInInstanceCreate(CFUUIDRef factoryUUID, CFUUIDRef typeUUID) {
2191 CFPlugInInstanceCreate(kCFAllocatorDefault, factoryUUID, typeUUID); // no-warning
2194 //===----------------------------------------------------------------------===//
2195 // PR14927: -drain only has retain-count semantics on NSAutoreleasePool.
2196 //===----------------------------------------------------------------------===//
2198 @interface PR14927 : NSObject
2202 void test_drain(void) {
2203 PR14927 *obj = [[PR14927 alloc] init];
2205 [obj release]; // no-warning
2208 //===----------------------------------------------------------------------===//
2209 // Allow cf_returns_retained and cf_returns_not_retained to mark a return
2210 // value as tracked, even if the object isn't a known CF type.
2211 //===----------------------------------------------------------------------===//
2213 MyCFType getCustom(void) __attribute__((cf_returns_not_retained));
2214 MyCFType makeCustom(void) __attribute__((cf_returns_retained));
2216 void testCustomReturnsRetained(void) {
2217 MyCFType obj = makeCustom(); // expected-warning {{leak of an object stored into 'obj'}}
2220 void testCustomReturnsNotRetained(void) {
2221 CFRelease(getCustom()); // expected-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
2224 //===----------------------------------------------------------------------===//
2225 // Don't print variables which are out of the current scope.
2226 //===----------------------------------------------------------------------===//
2227 @interface MyObj12706177 : NSObject
2229 +(void)test12706177;
2232 @implementation MyObj12706177
2236 self = [super init];
2239 +(void)test12706177 {
2240 id x = [[MyObj12706177 alloc] initX]; //expected-warning {{Potential leak of an object}}
2245 //===----------------------------------------------------------------------===//
2247 //===----------------------------------------------------------------------===//
2249 CFTypeRef getAutoreleasedCFType(void) {
2250 extern CFTypeRef CFCreateSomething(void);
2251 return CFAutorelease(CFCreateSomething()); // no-warning
2254 CFTypeRef getIncorrectlyAutoreleasedCFType(void) {
2255 extern CFTypeRef CFGetSomething(void);
2256 return CFAutorelease(CFGetSomething()); // expected-warning{{Object autoreleased too many times}}
2259 CFTypeRef createIncorrectlyAutoreleasedCFType(void) {
2260 extern CFTypeRef CFCreateSomething(void);
2261 return CFAutorelease(CFCreateSomething()); // expected-warning{{Object with a +0 retain count returned to caller where a +1 (owning) retain count is expected}}
2264 void useAfterAutorelease(void) {
2265 extern CFTypeRef CFCreateSomething(void);
2266 CFTypeRef obj = CFCreateSomething();
2269 extern void useCF(CFTypeRef);
2270 useCF(obj); // no-warning
2273 void useAfterRelease(void) {
2274 // Verify that the previous example would have warned with CFRelease.
2275 extern CFTypeRef CFCreateSomething(void);
2276 CFTypeRef obj = CFCreateSomething();
2279 extern void useCF(CFTypeRef);
2280 useCF(obj); // expected-warning{{Reference-counted object is used after it is released}}
2283 void testAutoreleaseReturnsInput(void) {
2284 extern CFTypeRef CFCreateSomething(void);
2285 CFTypeRef obj = CFCreateSomething(); // expected-warning{{Potential leak of an object stored into 'second'}}
2286 CFTypeRef second = CFAutorelease(obj);
2290 CFTypeRef testAutoreleaseReturnsInputSilent(void) {
2291 extern CFTypeRef CFCreateSomething(void);
2292 CFTypeRef obj = CFCreateSomething();
2293 CFTypeRef alias = CFAutorelease(obj);
2296 return obj; // no-warning
2299 void autoreleaseTypedObject(void) {
2300 CFArrayRef arr = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
2301 CFAutorelease((CFTypeRef)arr); // no-warning
2304 void autoreleaseReturningTypedObject(void) {
2305 CFArrayRef arr = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning{{Potential leak of an object stored into 'alias'}}
2306 CFArrayRef alias = (CFArrayRef)CFAutorelease((CFTypeRef)arr);
2310 CFArrayRef autoreleaseReturningTypedObjectSilent(void) {
2311 CFArrayRef arr = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
2312 CFArrayRef alias = (CFArrayRef)CFAutorelease((CFTypeRef)arr);
2315 return alias; // no-warning
2318 void autoreleaseObjC(void) {
2319 id obj = [@1 retain];
2320 CFAutorelease(obj); // no-warning
2323 CFAutorelease(anotherObj);
2324 } // expected-warning{{Object autoreleased too many times}}
2326 //===----------------------------------------------------------------------===//
2327 // <rdar://problem/13783514> xpc_connection_set_finalizer_f
2328 //===----------------------------------------------------------------------===//
2330 typedef xpc_object_t xpc_connection_t;
2331 typedef void (*xpc_finalizer_t)(void *value);
2332 void xpc_connection_set_context(xpc_connection_t connection, void *ctx);
2333 void xpc_connection_set_finalizer_f(xpc_connection_t connection,
2334 xpc_finalizer_t finalizer);
2335 void releaseAfterXPC(void *context) {
2336 [(NSArray *)context release];
2339 void rdar13783514(xpc_connection_t connection) {
2340 xpc_connection_set_context(connection, [[NSMutableArray alloc] init]);
2341 xpc_connection_set_finalizer_f(connection, releaseAfterXPC);
2344 // Do not report leaks when object is cleaned up with __attribute__((cleanup ..)).
2345 inline static void cleanupFunction(void *tp) {
2346 CFTypeRef x = *(CFTypeRef *)tp;
2351 #define ADDCLEANUP __attribute__((cleanup(cleanupFunction)))
2353 ADDCLEANUP CFStringRef myString;
2354 myString = CFStringCreateWithCString(0, "hello world", kCFStringEncodingUTF8);
2355 ADDCLEANUP CFStringRef myString2 =
2356 CFStringCreateWithCString(0, "hello world", kCFStringEncodingUTF8);
2359 //===----------------------------------------------------------------------===//
2361 //===----------------------------------------------------------------------===//
2363 __attribute__((ns_returns_retained))
2364 id returnNSNull(void) {
2365 return [NSNull null]; // no-warning
2368 //===----------------------------------------------------------------------===//
2369 // cf_returns_[not_]retained on parameters
2370 //===----------------------------------------------------------------------===//
2372 void testCFReturnsNotRetained(void) {
2373 extern void getViaParam(CFTypeRef * CF_RETURNS_NOT_RETAINED outObj);
2376 CFRelease(obj); // // expected-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
2379 void testCFReturnsNotRetainedAnnotated(void) {
2380 extern void getViaParam2(CFTypeRef * _Nonnull CF_RETURNS_NOT_RETAINED outObj);
2383 CFRelease(obj); // // expected-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
2386 void testCFReturnsRetained(void) {
2387 extern int copyViaParam(CFTypeRef * CF_RETURNS_RETAINED outObj);
2391 CFRelease(obj); // // FIXME-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
2394 void testCFReturnsRetainedError(void) {
2395 extern int copyViaParam(CFTypeRef * CF_RETURNS_RETAINED outObj);
2397 if (copyViaParam(&obj) == -42)
2398 return; // no-warning