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: cat %t.objcpp.plist | %diff_plist %S/Inputs/expected-plists/retain-release.m.objcpp.plist -
14 // RUN: cat %t.objc.plist | %diff_plist %S/Inputs/expected-plists/retain-release.m.objc.plist -
16 void clang_analyzer_eval(int);
18 #if __has_feature(attribute_ns_returns_retained)
19 #define NS_RETURNS_RETAINED __attribute__((ns_returns_retained))
21 #if __has_feature(attribute_cf_returns_retained)
22 #define CF_RETURNS_RETAINED __attribute__((cf_returns_retained))
24 #if __has_feature(attribute_ns_returns_not_retained)
25 #define NS_RETURNS_NOT_RETAINED __attribute__((ns_returns_not_retained))
27 #if __has_feature(attribute_cf_returns_not_retained)
28 #define CF_RETURNS_NOT_RETAINED __attribute__((cf_returns_not_retained))
30 #if __has_feature(attribute_ns_consumes_self)
31 #define NS_CONSUMES_SELF __attribute__((ns_consumes_self))
33 #if __has_feature(attribute_ns_consumed)
34 #define NS_CONSUMED __attribute__((ns_consumed))
36 #if __has_feature(attribute_cf_consumed)
37 #define CF_CONSUMED __attribute__((cf_consumed))
39 #if __has_attribute(ns_returns_autoreleased)
40 #define NS_RETURNS_AUTORELEASED __attribute__((ns_returns_autoreleased))
43 //===----------------------------------------------------------------------===//
44 // The following code is reduced using delta-debugging from Mac OS X headers:
46 // #include <Cocoa/Cocoa.h>
47 // #include <CoreFoundation/CoreFoundation.h>
48 // #include <DiskArbitration/DiskArbitration.h>
49 // #include <QuartzCore/QuartzCore.h>
50 // #include <Quartz/Quartz.h>
51 // #include <IOKit/IOKitLib.h>
53 // It includes the basic definitions for the test cases below.
54 //===----------------------------------------------------------------------===//
56 typedef unsigned int __darwin_natural_t;
57 typedef unsigned long uintptr_t;
58 typedef unsigned int uint32_t;
59 typedef unsigned long long uint64_t;
60 typedef unsigned int UInt32;
61 typedef signed long CFIndex;
62 typedef CFIndex CFByteOrder;
67 static __inline__ __attribute__((always_inline)) CFRange CFRangeMake(CFIndex loc, CFIndex len) {
73 typedef const void * CFTypeRef;
74 typedef const struct __CFString * CFStringRef;
75 typedef const struct __CFAllocator * CFAllocatorRef;
76 extern const CFAllocatorRef kCFAllocatorDefault;
78 extern CFTypeRef CFRetain(CFTypeRef cf);
79 extern void CFRelease(CFTypeRef cf);
80 extern CFTypeRef CFMakeCollectable(CFTypeRef cf);
81 extern CFTypeRef CFAutorelease(CFTypeRef CF_CONSUMED cf);
86 extern const CFArrayCallBacks kCFTypeArrayCallBacks;
87 typedef const struct __CFArray * CFArrayRef;
88 typedef struct __CFArray * CFMutableArrayRef;
89 extern CFMutableArrayRef CFArrayCreateMutable(CFAllocatorRef allocator, CFIndex capacity, const CFArrayCallBacks *callBacks);
90 extern const void *CFArrayGetValueAtIndex(CFArrayRef theArray, CFIndex idx);
91 extern void CFArrayAppendValue(CFMutableArrayRef theArray, const void *value);
94 CFDictionaryKeyCallBacks;
95 extern const CFDictionaryKeyCallBacks kCFTypeDictionaryKeyCallBacks;
98 CFDictionaryValueCallBacks;
99 extern const CFDictionaryValueCallBacks kCFTypeDictionaryValueCallBacks;
100 typedef const struct __CFDictionary * CFDictionaryRef;
101 typedef struct __CFDictionary * CFMutableDictionaryRef;
102 extern CFMutableDictionaryRef CFDictionaryCreateMutable(CFAllocatorRef allocator, CFIndex capacity, const CFDictionaryKeyCallBacks *keyCallBacks, const CFDictionaryValueCallBacks *valueCallBacks);
103 typedef UInt32 CFStringEncoding;
105 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 };
106 extern CFStringRef CFStringCreateWithCString(CFAllocatorRef alloc, const char *cStr, CFStringEncoding encoding);
107 typedef double CFTimeInterval;
108 typedef CFTimeInterval CFAbsoluteTime;
109 extern CFAbsoluteTime CFAbsoluteTimeGetCurrent(void);
110 typedef const struct __CFDate * CFDateRef;
111 extern CFDateRef CFDateCreate(CFAllocatorRef allocator, CFAbsoluteTime at);
112 extern CFAbsoluteTime CFDateGetAbsoluteTime(CFDateRef theDate);
113 typedef __darwin_natural_t natural_t;
114 typedef natural_t mach_port_name_t;
115 typedef mach_port_name_t mach_port_t;
116 typedef int kern_return_t;
117 typedef kern_return_t mach_error_t;
119 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 };
120 typedef CFIndex CFNumberType;
121 typedef const struct __CFNumber * CFNumberRef;
122 extern CFNumberRef CFNumberCreate(CFAllocatorRef allocator, CFNumberType theType, const void *valuePtr);
123 typedef const struct __CFAttributedString *CFAttributedStringRef;
124 typedef struct __CFAttributedString *CFMutableAttributedStringRef;
125 extern CFAttributedStringRef CFAttributedStringCreate(CFAllocatorRef alloc, CFStringRef str, CFDictionaryRef attributes) ;
126 extern CFMutableAttributedStringRef CFAttributedStringCreateMutableCopy(CFAllocatorRef alloc, CFIndex maxLength, CFAttributedStringRef aStr) ;
127 extern void CFAttributedStringSetAttribute(CFMutableAttributedStringRef aStr, CFRange range, CFStringRef attrName, CFTypeRef value) ;
128 typedef signed char BOOL;
129 typedef unsigned long NSUInteger;
130 @class NSString, Protocol;
131 extern void NSLog(NSString *format, ...) __attribute__((format(__NSString__, 1, 2)));
132 typedef struct _NSZone NSZone;
133 @class NSInvocation, NSMethodSignature, NSCoder, NSString, NSEnumerator;
135 - (BOOL)isEqual:(id)object;
137 - (oneway void)release;
139 - (NSString *)description;
143 - (id)copyWithZone:(NSZone *)zone;
145 @protocol NSMutableCopying - (id)mutableCopyWithZone:(NSZone *)zone;
147 @protocol NSCoding - (void)encodeWithCoder:(NSCoder *)aCoder;
149 @interface NSObject <NSObject> {}
150 + (id)allocWithZone:(NSZone *)zone;
155 @interface NSObject (NSCoderMethods)
156 - (id)awakeAfterUsingCoder:(NSCoder *)aDecoder;
158 extern id NSAllocateObject(Class aClass, NSUInteger extraBytes, NSZone *zone);
161 NSFastEnumerationState;
162 @protocol NSFastEnumeration
163 - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len;
165 @class NSString, NSDictionary;
166 @interface NSValue : NSObject <NSCopying, NSCoding> - (void)getValue:(void *)value;
168 @interface NSNumber : NSValue
170 - (id)initWithInt:(int)value;
171 + (NSNumber *)numberWithInt:(int)value;
174 @interface NSArray : NSObject <NSCopying, NSMutableCopying, NSCoding, NSFastEnumeration>
176 - (id)initWithObjects:(const id [])objects count:(NSUInteger)cnt;
177 + (id)arrayWithObject:(id)anObject;
178 + (id)arrayWithObjects:(const id [])objects count:(NSUInteger)cnt;
179 + (id)arrayWithObjects:(id)firstObj, ... __attribute__((sentinel(0,1)));
180 - (id)initWithObjects:(id)firstObj, ... __attribute__((sentinel(0,1)));
181 - (id)initWithArray:(NSArray *)array;
182 @end @interface NSArray (NSArrayCreation) + (id)array;
183 @end @interface NSAutoreleasePool : NSObject {
186 @end extern NSString * const NSBundleDidLoadNotification;
187 typedef double NSTimeInterval;
188 @interface NSDate : NSObject <NSCopying, NSCoding> - (NSTimeInterval)timeIntervalSinceReferenceDate;
189 @end typedef unsigned short unichar;
190 @interface NSString : NSObject <NSCopying, NSMutableCopying, NSCoding>
191 - (NSUInteger)length;
192 - (NSString *)stringByAppendingString:(NSString *)aString;
193 - ( const char *)UTF8String;
194 - (id)initWithUTF8String:(const char *)nullTerminatedCString;
195 + (id)stringWithUTF8String:(const char *)nullTerminatedCString;
196 @end @class NSString, NSURL, NSError;
197 @interface NSData : NSObject <NSCopying, NSMutableCopying, NSCoding> - (NSUInteger)length;
198 + (id)dataWithBytesNoCopy:(void *)bytes length:(NSUInteger)length;
199 + (id)dataWithBytesNoCopy:(void *)bytes length:(NSUInteger)length freeWhenDone:(BOOL)b;
200 @end @class NSLocale, NSDate, NSCalendar, NSTimeZone, NSError, NSArray, NSMutableDictionary;
201 @interface NSDictionary : NSObject <NSCopying, NSMutableCopying, NSCoding, NSFastEnumeration>
203 + (id)dictionaryWithObjects:(NSArray *)objects forKeys:(NSArray *)keys;
204 + (id)dictionaryWithObjects:(const id [])objects forKeys:(const id <NSCopying> [])keys count:(NSUInteger)cnt;
206 @interface NSMutableDictionary : NSDictionary - (void)removeObjectForKey:(id)aKey;
207 - (void)setObject:(id)anObject forKey:(id)aKey;
209 @interface NSMutableDictionary (NSMutableDictionaryCreation) + (id)dictionaryWithCapacity:(NSUInteger)numItems;
212 @interface NSNull : NSObject
216 typedef double CGFloat;
219 typedef struct CGSize CGSize;
222 typedef struct CGRect CGRect;
223 typedef mach_port_t io_object_t;
224 typedef char io_name_t[128];
225 typedef io_object_t io_iterator_t;
226 typedef io_object_t io_service_t;
227 typedef struct IONotificationPort * IONotificationPortRef;
228 typedef void (*IOServiceMatchingCallback)( void * refcon, io_iterator_t iterator );
229 io_service_t IOServiceGetMatchingService( mach_port_t masterPort, CFDictionaryRef matching );
230 kern_return_t IOServiceGetMatchingServices( mach_port_t masterPort, CFDictionaryRef matching, io_iterator_t * existing );
231 kern_return_t IOServiceAddNotification( mach_port_t masterPort, const io_name_t notificationType, CFDictionaryRef matching, mach_port_t wakePort, uintptr_t reference, io_iterator_t * notification ) __attribute__((deprecated)); // expected-note {{'IOServiceAddNotification' has been explicitly marked deprecated here}}
232 kern_return_t IOServiceAddMatchingNotification( IONotificationPortRef notifyPort, const io_name_t notificationType, CFDictionaryRef matching, IOServiceMatchingCallback callback, void * refCon, io_iterator_t * notification );
233 CFMutableDictionaryRef IOServiceMatching( const char * name );
234 CFMutableDictionaryRef IOServiceNameMatching( const char * name );
235 CFMutableDictionaryRef IOBSDNameMatching( mach_port_t masterPort, uint32_t options, const char * bsdName );
236 CFMutableDictionaryRef IOOpenFirmwarePathMatching( mach_port_t masterPort, uint32_t options, const char * path );
237 CFMutableDictionaryRef IORegistryEntryIDMatching( uint64_t entryID );
238 typedef struct __DASession * DASessionRef;
239 extern DASessionRef DASessionCreate( CFAllocatorRef allocator );
240 typedef struct __DADisk * DADiskRef;
241 extern DADiskRef DADiskCreateFromBSDName( CFAllocatorRef allocator, DASessionRef session, const char * name );
242 extern DADiskRef DADiskCreateFromIOMedia( CFAllocatorRef allocator, DASessionRef session, io_service_t media );
243 extern CFDictionaryRef DADiskCopyDescription( DADiskRef disk );
244 extern DADiskRef DADiskCopyWholeDisk( DADiskRef disk );
245 @interface NSTask : NSObject - (id)init;
246 @end typedef struct CGColorSpace *CGColorSpaceRef;
247 typedef struct CGImage *CGImageRef;
248 typedef struct CGLayer *CGLayerRef;
249 @interface NSResponder : NSObject <NSCoding> {
251 @end @protocol NSAnimatablePropertyContainer - (id)animator;
252 @end extern NSString *NSAnimationTriggerOrderIn ;
253 @interface NSView : NSResponder <NSAnimatablePropertyContainer> {
255 @end @protocol NSValidatedUserInterfaceItem - (SEL)action;
256 @end @protocol NSUserInterfaceValidations - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)anItem;
257 @end @class NSDate, NSDictionary, NSError, NSException, NSNotification;
258 @class NSTextField, NSPanel, NSArray, NSWindow, NSImage, NSButton, NSError;
259 @interface NSApplication : NSResponder <NSUserInterfaceValidations> {
261 - (void)beginSheet:(NSWindow *)sheet modalForWindow:(NSWindow *)docWindow modalDelegate:(id)modalDelegate didEndSelector:(SEL)didEndSelector contextInfo:(void *)contextInfo;
263 NSTerminateCancel = 0, NSTerminateNow = 1, NSTerminateLater = 2 };
264 typedef NSUInteger NSApplicationTerminateReply;
265 @protocol NSApplicationDelegate <NSObject> @optional - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender;
266 @end @class NSAttributedString, NSEvent, NSFont, NSFormatter, NSImage, NSMenu, NSText, NSView, NSTextView;
267 @interface NSCell : NSObject <NSCopying, NSCoding> {
273 @interface CIImage : NSObject <NSCoding, NSCopying> {
275 typedef int CIFormat;
277 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 };
278 typedef mach_error_t DAReturn;
279 typedef const struct __DADissenter * DADissenterRef;
280 extern DADissenterRef DADissenterCreate( CFAllocatorRef allocator, DAReturn status, CFStringRef string );
281 @interface CIContext: NSObject {
283 - (CGImageRef)createCGImage:(CIImage *)im fromRect:(CGRect)r;
284 - (CGImageRef)createCGImage:(CIImage *)im fromRect:(CGRect)r format:(CIFormat)f colorSpace:(CGColorSpaceRef)cs;
285 - (CGLayerRef)createCGLayerWithSize:(CGSize)size info:(CFDictionaryRef)d;
286 @end extern NSString* const QCRendererEventKey;
287 @protocol QCCompositionRenderer - (NSDictionary*) attributes;
288 @end @interface QCRenderer : NSObject <QCCompositionRenderer> {
290 - (id) createSnapshotImageOfType:(NSString*)type;
291 @end extern NSString* const QCViewDidStartRenderingNotification;
292 @interface QCView : NSView <QCCompositionRenderer> {
294 - (id) createSnapshotImageOfType:(NSString*)type;
296 ICEXIFOrientation1 = 1, ICEXIFOrientation2 = 2, ICEXIFOrientation3 = 3, ICEXIFOrientation4 = 4, ICEXIFOrientation5 = 5, ICEXIFOrientation6 = 6, ICEXIFOrientation7 = 7, ICEXIFOrientation8 = 8, };
298 @protocol ICDeviceDelegate <NSObject> @required - (void)didRemoveDevice:(ICDevice*)device;
299 @end extern NSString *const ICScannerStatusWarmingUp;
300 @class ICScannerDevice;
301 @protocol ICScannerDeviceDelegate <ICDeviceDelegate> @optional - (void)scannerDeviceDidBecomeAvailable:(ICScannerDevice*)scanner;
304 typedef long unsigned int __darwin_size_t;
305 typedef __darwin_size_t size_t;
306 typedef unsigned long CFTypeID;
311 typedef struct CGPoint CGPoint;
312 typedef struct CGGradient *CGGradientRef;
313 typedef uint32_t CGGradientDrawingOptions;
314 extern CFTypeID CGGradientGetTypeID(void);
315 extern CGGradientRef CGGradientCreateWithColorComponents(CGColorSpaceRef
316 space, const CGFloat components[], const CGFloat locations[], size_t count);
317 extern CGGradientRef CGGradientCreateWithColors(CGColorSpaceRef space,
318 CFArrayRef colors, const CGFloat locations[]);
319 extern CGGradientRef CGGradientRetain(CGGradientRef gradient);
320 extern void CGGradientRelease(CGGradientRef gradient);
321 typedef struct CGContext *CGContextRef;
322 extern void CGContextDrawLinearGradient(CGContextRef context,
323 CGGradientRef gradient, CGPoint startPoint, CGPoint endPoint,
324 CGGradientDrawingOptions options);
325 extern CGColorSpaceRef CGColorSpaceCreateDeviceRGB(void);
327 @interface NSMutableArray : NSObject
328 - (void)addObject:(id)object;
332 // This is how NSMakeCollectable is declared in the OS X 10.8 headers.
333 id NSMakeCollectable(CFTypeRef __attribute__((cf_consumed))) __attribute__((ns_returns_retained));
335 typedef const struct __CFUUID * CFUUIDRef;
338 void *CFPlugInInstanceCreate(CFAllocatorRef allocator, CFUUIDRef factoryUUID, CFUUIDRef typeUUID);
343 //===----------------------------------------------------------------------===//
345 //===----------------------------------------------------------------------===//
347 CFAbsoluteTime f1() {
348 CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
349 CFDateRef date = CFDateCreate(0, t);
352 CFDateGetAbsoluteTime(date); // no-warning
354 t = CFDateGetAbsoluteTime(date); // expected-warning{{Reference-counted object is used after it is released}}
358 CFAbsoluteTime f2() {
359 CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
360 CFDateRef date = CFDateCreate(0, t);
361 [((NSDate*) date) retain];
363 CFDateGetAbsoluteTime(date); // no-warning
364 [((NSDate*) date) release];
365 t = CFDateGetAbsoluteTime(date); // expected-warning{{Reference-counted object is used after it is released}}
372 // Test to see if we suppress an error when we store the pointer
375 CFAbsoluteTime f3() {
376 CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
377 CFDateRef date = CFDateCreate(0, t);
378 [((NSDate*) date) retain];
380 CFDateGetAbsoluteTime(date); // no-warning
381 global_x = (NSDate*) date;
382 [((NSDate*) date) release];
383 t = CFDateGetAbsoluteTime(date); // no-warning
387 //---------------------------------------------------------------------------
388 // Test case 'f4' differs for region store and basic store. See
389 // retain-release-region-store.m and retain-release-basic-store.m.
390 //---------------------------------------------------------------------------
394 CFAbsoluteTime f5(int x) {
395 CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
396 CFDateRef date = CFDateCreate(0, t); // expected-warning{{leak}}
404 // Test a leak involving the return.
406 CFDateRef f6(int x) {
407 CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent()); // expected-warning{{leak}}
412 // Test a leak involving an overwrite.
415 CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent()); //expected-warning{{leak}}
417 date = CFDateCreate(0, CFAbsoluteTimeGetCurrent()); // expected-warning {{leak}}
421 // Generalization of Create rule. MyDateCreate returns a CFXXXTypeRef, and
422 // has the word create.
423 CFDateRef MyDateCreate();
426 CFDateRef date = MyDateCreate(); // expected-warning{{leak}}
431 __attribute__((cf_returns_retained)) CFDateRef f9() {
432 CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent()); // no-warning
434 // When allocations fail, CFDateCreate can return null.
435 if (!date) *p = 1; // expected-warning{{null}}
439 // Handle DiskArbitration API:
441 // http://developer.apple.com/DOCUMENTATION/DARWIN/Reference/DiscArbitrationFramework/
443 void f10(io_service_t media, DADiskRef d, CFStringRef s) {
444 DADiskRef disk = DADiskCreateFromBSDName(kCFAllocatorDefault, 0, "hello"); // expected-warning{{leak}}
445 if (disk) NSLog(@"ok");
447 disk = DADiskCreateFromIOMedia(kCFAllocatorDefault, 0, media); // expected-warning{{leak}}
448 if (disk) NSLog(@"ok");
450 CFDictionaryRef dict = DADiskCopyDescription(d); // expected-warning{{leak}}
451 if (dict) NSLog(@"ok");
453 disk = DADiskCopyWholeDisk(d); // expected-warning{{leak}}
454 if (disk) NSLog(@"ok");
456 DADissenterRef dissenter = DADissenterCreate(kCFAllocatorDefault, // expected-warning{{leak}}
457 kDAReturnSuccess, s);
458 if (dissenter) NSLog(@"ok");
460 DASessionRef session = DASessionCreate(kCFAllocatorDefault); // expected-warning{{leak}}
461 if (session) NSLog(@"ok");
465 // Handle CoreMedia API
468 typedef struct CMFoo *CMFooRef;
470 CMFooRef CMCreateFooRef();
471 CMFooRef CMGetFooRef();
473 typedef signed long SInt32;
474 typedef SInt32 OSStatus;
475 OSStatus CMCreateFooAndReturnViaOutParameter(CMFooRef * CF_RETURNS_RETAINED fooOut);
477 void testLeakCoreMediaReferenceType() {
478 CMFooRef f = CMCreateFooRef(); // expected-warning{{leak}}
481 void testOverReleaseMediaReferenceType() {
482 CMFooRef f = CMGetFooRef();
483 CFRelease(f); // expected-warning{{Incorrect decrement of the reference count}}
486 void testOkToReleaseReturnsRetainedOutParameter() {
488 OSStatus status = CMCreateFooAndReturnViaOutParameter(&foo);
493 CFRelease(foo); // no-warning
496 void testLeakWithReturnsRetainedOutParameter() {
498 OSStatus status = CMCreateFooAndReturnViaOutParameter(&foo);
503 // FIXME: Ideally we would report a leak here since it is the caller's
504 // responsibility to release 'foo'. However, we don't currently have
505 // a mechanism in this checker to only require a release when a successful
506 // status is returned.
509 typedef CFTypeRef CMBufferRef;
511 typedef CFTypeRef *CMBufferQueueRef;
513 CMBufferRef CMBufferQueueDequeueAndRetain(CMBufferQueueRef);
515 void testCMBufferQueueDequeueAndRetain(CMBufferQueueRef queue) {
516 CMBufferRef buffer = CMBufferQueueDequeueAndRetain(queue); // expected-warning{{Potential leak of an object stored into 'buffer'}}
517 // There's a state split due to the eagerly-assume behavior.
518 // The point here is that we don't treat CMBufferQueueDequeueAndRetain
519 // as some sort of CFRetain() that returns its argument.
520 clang_analyzer_eval((CMFooRef)buffer == (CMFooRef)queue); // expected-warning{{TRUE}}
521 // expected-warning@-1{{FALSE}}
524 // Test retain/release checker with CFString and CFMutableArray.
527 CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
530 CFStringRef s1 = CFStringCreateWithCString(0, "hello world",
531 kCFStringEncodingUTF8);
533 // Add the string to the array.
534 CFArrayAppendValue(A, s1);
536 // Decrement the reference count.
537 CFRelease(s1); // no-warning
539 // Get the string. We don't own it.
540 s1 = (CFStringRef) CFArrayGetValueAtIndex(A, 0);
542 // Release the array.
543 CFRelease(A); // no-warning
545 // Release the string. This is a bug.
546 CFRelease(s1); // expected-warning{{Incorrect decrement of the reference count}}
549 // PR 3337: Handle functions declared using typedefs.
550 typedef CFTypeRef CREATEFUN();
551 CREATEFUN MyCreateFun;
554 CFTypeRef o = MyCreateFun(); // expected-warning {{leak}}
557 void f13_autorelease() {
558 CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
559 [(id) A autorelease]; // no-warning
562 void f13_autorelease_b() {
563 CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
564 [(id) A autorelease];
565 [(id) A autorelease];
566 } // expected-warning{{Object autoreleased too many times}}
568 CFMutableArrayRef f13_autorelease_c() {
569 CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
570 [(id) A autorelease];
571 [(id) A autorelease];
572 return A; // expected-warning{{Object autoreleased too many times}}
575 CFMutableArrayRef f13_autorelease_d() {
576 CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
577 [(id) A autorelease];
578 [(id) A autorelease];
579 CFMutableArrayRef B = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning{{Object autoreleased too many times}}
580 CFRelease(B); // no-warning
585 // This case exercises the logic where the leak site is the same as the allocation site.
586 void f14_leakimmediately() {
587 CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning{{leak}}
590 // Test that we track an allocated object beyond the point where the *name*
591 // of the variable storing the reference is no longer live.
594 CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
595 CFMutableArrayRef *B = &A;
596 // At this point, the name 'A' is no longer live.
597 CFRelease(*B); // no-warning
600 // Test when we pass NULL to CFRetain/CFRelease/CFMakeCollectable/CFAutorelease.
601 void f16(int x, CFTypeRef p) {
607 CFRelease(p); // expected-warning{{Null pointer argument in call to CFRelease}}
610 CFRetain(p); // expected-warning{{Null pointer argument in call to CFRetain}}
613 CFMakeCollectable(p); // expected-warning{{Null pointer argument in call to CFMakeCollectable}}
616 CFAutorelease(p); // expected-warning{{Null pointer argument in call to CFAutorelease}}
623 // Test that an object is non-null after CFRetain/CFRelease/CFMakeCollectable/CFAutorelease.
624 void f17(int x, CFTypeRef p) {
629 CFRelease(0); // no-warning
634 CFRetain(0); // no-warning
637 CFMakeCollectable(p);
639 CFMakeCollectable(0); // no-warning
644 CFAutorelease(0); // no-warning
651 __attribute__((annotate("rc_ownership_returns_retained"))) isl_basic_map *isl_basic_map_cow(__attribute__((annotate("rc_ownership_consumed"))) isl_basic_map *bmap);
653 // Test custom diagnostics for generalized objects.
654 void f18(__attribute__((annotate("rc_ownership_consumed"))) isl_basic_map *bmap) {
655 // After this call, 'bmap' has a +1 reference count.
656 bmap = isl_basic_map_cow(bmap); // expected-warning {{Potential leak of an object}}
659 // Test basic tracking of ivars associated with 'self'. For the retain/release
660 // checker we currently do not want to flag leaks associated with stores
661 // of tracked objects to ivars.
662 @interface SelfIvarTest : NSObject {
665 - (void)test_self_tracking;
668 @implementation SelfIvarTest
669 - (void)test_self_tracking {
670 myObj = (id) CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
674 // Test return of non-owned objects in contexts where an owned object
676 @interface TestReturnNotOwnedWhenExpectedOwned
677 - (NSString*)newString;
680 @implementation TestReturnNotOwnedWhenExpectedOwned
681 - (NSString*)newString {
682 NSString *s = [NSString stringWithUTF8String:"hello"];
683 return s; // expected-warning{{Object with a +0 retain count returned to caller where a +1 (owning) retain count is expected}}
687 // <rdar://problem/6659160>
690 static void rdar_6659160(char *inkind, char *inname)
692 // We currently expect that [NSObject alloc] cannot fail. This
693 // will be a toggled flag in the future. It can indeed return null, but
694 // Cocoa programmers generally aren't expected to reason about out-of-memory
696 NSString *kind = [[NSString alloc] initWithUTF8String:inkind]; // expected-warning{{leak}}
698 // We do allow stringWithUTF8String to fail. This isn't really correct, as
699 // far as returning 0. In most error conditions it will throw an exception.
700 // If allocation fails it could return 0, but again this
702 NSString *name = [NSString stringWithUTF8String:inname];
706 const char *kindC = 0;
707 const char *nameC = 0;
709 // In both cases, we cannot reach a point down below where we
710 // dereference kindC or nameC with either being null. This is because
711 // we assume that [NSObject alloc] doesn't fail and that we have the guard
715 kindC = [kind UTF8String];
717 nameC = [name UTF8String];
718 if(!isFoo(kindC[0])) // expected-warning{{null}}
720 if(!isFoo(nameC[0])) // no-warning
724 [name release]; // expected-warning{{Incorrect decrement of the reference count}}
727 // PR 3677 - 'allocWithZone' should be treated as following the Cocoa naming
728 // conventions with respect to 'return'ing ownership.
729 @interface PR3677: NSObject @end
730 @implementation PR3677
731 + (id)allocWithZone:(NSZone *)inZone {
732 return [super allocWithZone:inZone]; // no-warning
736 // PR 3820 - Reason about calls to -dealloc
737 void pr3820_DeallocInsteadOfRelease(void)
739 id foo = [[NSString alloc] init]; // no-warning
741 // foo is not leaked, since it has been deallocated.
744 void pr3820_ReleaseAfterDealloc(void)
746 id foo = [[NSString alloc] init];
748 [foo release]; // expected-warning{{used after it is release}}
749 // NSInternalInconsistencyException: message sent to deallocated object
752 void pr3820_DeallocAfterRelease(void)
754 NSLog(@"\n\n[%s]", __FUNCTION__);
755 id foo = [[NSString alloc] init];
757 [foo dealloc]; // expected-warning{{used after it is released}}
758 // message sent to released object
761 // From <rdar://problem/6704930>. The problem here is that 'length' binds to
762 // '($0 - 1)' after '--length', but SimpleConstraintManager doesn't know how to
763 // reason about '($0 - 1) > constant'. As a temporary hack, we drop the value
764 // of '($0 - 1)' and conjure a new symbol.
765 void rdar6704930(unsigned char *s, unsigned int length) {
773 name = [[NSString alloc] init]; // no-warning
779 if ((length == 0) && (name != 0)) {
783 if (length == 0) { // no ':' found -> use it all as name
784 name = [[NSString alloc] init]; // no-warning
794 //===----------------------------------------------------------------------===//
795 // <rdar://problem/6833332>
796 // One build of the analyzer accidentally stopped tracking the allocated
797 // object after the 'retain'.
798 //===----------------------------------------------------------------------===//
800 @interface rdar_6833332 : NSObject <NSApplicationDelegate> {
803 @property (nonatomic, retain) NSWindow *window;
806 @implementation rdar_6833332
808 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
809 NSMutableDictionary *dict = [[NSMutableDictionary dictionaryWithCapacity:4] retain]; // expected-warning{{leak}}
811 [dict setObject:@"foo" forKey:@"bar"];
820 - (void)radar10102244 {
821 NSMutableDictionary *dict = [[NSMutableDictionary dictionaryWithCapacity:4] retain]; // expected-warning{{leak}}
823 NSLog(@"%@", window);
827 //===----------------------------------------------------------------------===//
828 // <rdar://problem/6257780> clang checker fails to catch use-after-release
829 //===----------------------------------------------------------------------===//
831 int rdar_6257780_Case1() {
832 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
833 NSArray *array = [NSArray array];
834 [array release]; // expected-warning{{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
839 //===----------------------------------------------------------------------===//
840 // <rdar://problem/10640253> Analyzer is confused about NSAutoreleasePool -allocWithZone:.
841 //===----------------------------------------------------------------------===//
843 void rdar_10640253_autorelease_allocWithZone() {
844 NSAutoreleasePool *pool = [[NSAutoreleasePool allocWithZone:(NSZone*)0] init];
848 //===----------------------------------------------------------------------===//
849 // <rdar://problem/6866843> Checker should understand new/setObject:/release constructs
850 //===----------------------------------------------------------------------===//
852 void rdar_6866843() {
853 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
854 NSMutableDictionary* dictionary = [[NSMutableDictionary alloc] init];
855 NSArray* array = [[NSArray alloc] init];
856 [dictionary setObject:array forKey:@"key"];
858 // Using 'array' here should be fine
859 NSLog(@"array = %@\n", array); // no-warning
860 // Now the array is released
861 [dictionary release];
866 //===----------------------------------------------------------------------===//
867 // <rdar://problem/6877235> Classes typedef-ed to CF objects should get the same treatment as CF objects
868 //===----------------------------------------------------------------------===//
870 typedef CFTypeRef OtherRef;
872 @interface RDar6877235 : NSObject {}
873 - (CFTypeRef)_copyCFTypeRef;
874 - (OtherRef)_copyOtherRef;
877 @implementation RDar6877235
878 - (CFTypeRef)_copyCFTypeRef {
879 return [[NSString alloc] init]; // no-warning
881 - (OtherRef)_copyOtherRef {
882 return [[NSString alloc] init]; // no-warning
886 //===----------------------------------------------------------------------===//
887 // <rdar://problem/6320065> false positive - init method returns an object
889 //===----------------------------------------------------------------------===//
891 @interface RDar6320065 : NSObject {
894 - (id)initReturningNewClass;
895 - (id)_initReturningNewClassBad;
896 - (id)initReturningNewClassBad2;
899 @interface RDar6320065Subclass : RDar6320065
902 @implementation RDar6320065
903 - (id)initReturningNewClass {
905 self = [[RDar6320065Subclass alloc] init]; // no-warning
908 - (id)_initReturningNewClassBad {
910 [[RDar6320065Subclass alloc] init]; // expected-warning {{leak}}
913 - (id)initReturningNewClassBad2 {
915 self = [[RDar6320065Subclass alloc] init];
916 return [self autorelease]; // expected-warning{{Object with a +0 retain count returned to caller where a +1 (owning) retain count is expected}}
921 @implementation RDar6320065Subclass
924 int RDar6320065_test() {
925 RDar6320065 *test = [[RDar6320065 alloc] init]; // no-warning
930 //===----------------------------------------------------------------------===//
931 // <rdar://problem/7129086> -awakeAfterUsingCoder: returns an owned object
932 // and claims the receiver
933 //===----------------------------------------------------------------------===//
935 @interface RDar7129086 : NSObject {} @end
936 @implementation RDar7129086
937 - (id)awakeAfterUsingCoder:(NSCoder *)aDecoder {
938 [self release]; // no-warning
939 return [NSString alloc]; // no-warning
943 //===----------------------------------------------------------------------===//
944 // <rdar://problem/6859457> [NSData dataWithBytesNoCopy] does not return a
946 //===----------------------------------------------------------------------===//
948 @interface RDar6859457 : NSObject {}
949 - (NSString*) NoCopyString;
950 - (NSString*) noCopyString;
953 @implementation RDar6859457
954 - (NSString*) NoCopyString { return [[NSString alloc] init]; } // expected-warning{{leak}}
955 - (NSString*) noCopyString { return [[NSString alloc] init]; } // expected-warning{{leak}}
958 void test_RDar6859457(RDar6859457 *x, void *bytes, NSUInteger dataLength) {
959 [x NoCopyString]; // expected-warning{{leak}}
960 [x noCopyString]; // expected-warning{{leak}}
961 [NSData dataWithBytesNoCopy:bytes length:dataLength]; // no-warning
962 [NSData dataWithBytesNoCopy:bytes length:dataLength freeWhenDone:1]; // no-warning
965 //===----------------------------------------------------------------------===//
966 // PR 4230 - an autorelease pool is not necessarily leaked during a premature
968 //===----------------------------------------------------------------------===//
970 static void PR4230(void)
972 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // no-warning
973 NSString *object = [[[NSString alloc] init] autorelease]; // no-warning
977 static void PR4230_new(void)
979 NSAutoreleasePool *pool = [NSAutoreleasePool new]; // no-warning
980 NSString *object = [[[NSString alloc] init] autorelease]; // no-warning
984 //===----------------------------------------------------------------------===//
985 // Method name that has a null IdentifierInfo* for its first selector slot.
986 // This test just makes sure that we handle it.
987 //===----------------------------------------------------------------------===//
989 @interface TestNullIdentifier
992 @implementation TestNullIdentifier
994 return [[NSString alloc] init]; // expected-warning{{leak}}
998 //===----------------------------------------------------------------------===//
999 // <rdar://problem/6893565> don't flag leaks for return types that cannot be
1000 // determined to be CF types
1001 //===----------------------------------------------------------------------===//
1003 // We don't know if 'struct s6893565' represents a Core Foundation type, so
1004 // we shouldn't emit an error here.
1005 typedef struct s6893565* TD6893565;
1007 @interface RDar6893565 {}
1008 -(TD6893565)newThing;
1011 @implementation RDar6893565
1012 -(TD6893565)newThing {
1013 return (TD6893565) [[NSString alloc] init]; // no-warning
1017 //===----------------------------------------------------------------------===//
1018 // <rdar://problem/6902710> clang: false positives w/QC and CoreImage methods
1019 //===----------------------------------------------------------------------===//
1021 void rdar6902710(QCView *view, QCRenderer *renderer, CIContext *context,
1022 NSString *str, CIImage *img, CGRect rect,
1023 CIFormat form, CGColorSpaceRef cs) {
1024 [view createSnapshotImageOfType:str]; // expected-warning{{leak}}
1025 [renderer createSnapshotImageOfType:str]; // expected-warning{{leak}}
1026 [context createCGImage:img fromRect:rect]; // expected-warning{{leak}}
1027 [context createCGImage:img fromRect:rect format:form colorSpace:cs]; // expected-warning{{leak}}
1030 //===----------------------------------------------------------------------===//
1031 // <rdar://problem/6945561> -[CIContext createCGLayerWithSize:info:]
1032 // misinterpreted by clang scan-build
1033 //===----------------------------------------------------------------------===//
1035 void rdar6945561(CIContext *context, CGSize size, CFDictionaryRef d) {
1036 [context createCGLayerWithSize:size info:d]; // expected-warning{{leak}}
1039 //===----------------------------------------------------------------------===//
1040 // <rdar://problem/6961230> add knowledge of IOKit functions to retain/release
1042 //===----------------------------------------------------------------------===//
1044 void IOBSDNameMatching_wrapper(mach_port_t masterPort, uint32_t options, const char * bsdName) {
1045 IOBSDNameMatching(masterPort, options, bsdName); // expected-warning{{leak}}
1048 void IOServiceMatching_wrapper(const char * name) {
1049 IOServiceMatching(name); // expected-warning{{leak}}
1052 void IOServiceNameMatching_wrapper(const char * name) {
1053 IOServiceNameMatching(name); // expected-warning{{leak}}
1056 CF_RETURNS_RETAINED CFDictionaryRef CreateDict();
1058 void IOServiceAddNotification_wrapper(mach_port_t masterPort, const io_name_t notificationType,
1059 mach_port_t wakePort, uintptr_t reference, io_iterator_t * notification ) {
1061 CFDictionaryRef matching = CreateDict();
1062 CFRelease(matching);
1063 IOServiceAddNotification(masterPort, notificationType, matching, // expected-warning{{used after it is released}} expected-warning{{deprecated}}
1064 wakePort, reference, notification);
1067 void IORegistryEntryIDMatching_wrapper(uint64_t entryID ) {
1068 IORegistryEntryIDMatching(entryID); // expected-warning{{leak}}
1071 void IOOpenFirmwarePathMatching_wrapper(mach_port_t masterPort, uint32_t options,
1072 const char * path) {
1073 IOOpenFirmwarePathMatching(masterPort, options, path); // expected-warning{{leak}}
1076 void IOServiceGetMatchingService_wrapper(mach_port_t masterPort) {
1077 CFDictionaryRef matching = CreateDict();
1078 IOServiceGetMatchingService(masterPort, matching);
1079 CFRelease(matching); // expected-warning{{used after it is released}}
1082 void IOServiceGetMatchingServices_wrapper(mach_port_t masterPort, io_iterator_t *existing) {
1083 CFDictionaryRef matching = CreateDict();
1084 IOServiceGetMatchingServices(masterPort, matching, existing);
1085 CFRelease(matching); // expected-warning{{used after it is released}}
1088 void IOServiceAddMatchingNotification_wrapper(IONotificationPortRef notifyPort, const io_name_t notificationType,
1089 IOServiceMatchingCallback callback, void * refCon, io_iterator_t * notification) {
1091 CFDictionaryRef matching = CreateDict();
1092 IOServiceAddMatchingNotification(notifyPort, notificationType, matching, callback, refCon, notification);
1093 CFRelease(matching); // expected-warning{{used after it is released}}
1096 //===----------------------------------------------------------------------===//
1097 // Test of handling objects whose references "escape" to containers.
1098 //===----------------------------------------------------------------------===//
1100 void CFDictionaryAddValue(CFMutableDictionaryRef, void *, void *);
1102 // <rdar://problem/6539791>
1103 void rdar_6539791(CFMutableDictionaryRef y, void* key, void* val_key) {
1104 CFMutableDictionaryRef x = CFDictionaryCreateMutable(kCFAllocatorDefault, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
1105 CFDictionaryAddValue(y, key, x);
1106 CFRelease(x); // the dictionary keeps a reference, so the object isn't deallocated yet
1108 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z);
1110 CFDictionaryAddValue(x, val_key, (void*)value); // no-warning
1112 CFDictionaryAddValue(y, val_key, (void*)value); // no-warning
1116 // <rdar://problem/6560661>
1117 // Same issue, except with "AppendValue" functions.
1118 void rdar_6560661(CFMutableArrayRef x) {
1120 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z);
1121 // CFArrayAppendValue keeps a reference to value.
1122 CFArrayAppendValue(x, value);
1125 CFRelease(value); // no-warning
1128 // <rdar://problem/7152619>
1129 // Same issue, excwept with "CFAttributeStringSetAttribute".
1130 void rdar_7152619(CFStringRef str) {
1131 CFAttributedStringRef string = CFAttributedStringCreate(kCFAllocatorDefault, str, 0);
1132 CFMutableAttributedStringRef attrString = CFAttributedStringCreateMutableCopy(kCFAllocatorDefault, 100, string);
1134 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1135 CFAttributedStringSetAttribute(attrString, CFRangeMake(0, 1), str, number);
1138 CFRelease(attrString);
1141 //===----------------------------------------------------------------------===//
1142 // Test of handling CGGradientXXX functions.
1143 //===----------------------------------------------------------------------===//
1145 void rdar_7184450(CGContextRef myContext, CGFloat x, CGPoint myStartPoint,
1146 CGPoint myEndPoint) {
1147 size_t num_locations = 6;
1148 CGFloat locations[6] = { 0.0, 0.265, 0.28, 0.31, 0.36, 1.0 };
1149 CGFloat components[28] = { 239.0/256.0, 167.0/256.0, 170.0/256.0,
1151 207.0/255.0, 39.0/255.0, 39.0/255.0, x,
1152 147.0/255.0, 21.0/255.0, 22.0/255.0, x,
1153 175.0/255.0, 175.0/255.0, 175.0/255.0, x,
1154 255.0/255.0,255.0/255.0, 255.0/255.0, x,
1155 255.0/255.0,255.0/255.0, 255.0/255.0, x
1158 CGGradientRef myGradient =
1159 CGGradientCreateWithColorComponents(CGColorSpaceCreateDeviceRGB(), // expected-warning{{leak}}
1160 components, locations, num_locations);
1162 CGContextDrawLinearGradient(myContext, myGradient, myStartPoint, myEndPoint,
1164 CGGradientRelease(myGradient);
1167 void rdar_7184450_pos(CGContextRef myContext, CGFloat x, CGPoint myStartPoint,
1168 CGPoint myEndPoint) {
1169 size_t num_locations = 6;
1170 CGFloat locations[6] = { 0.0, 0.265, 0.28, 0.31, 0.36, 1.0 };
1171 CGFloat components[28] = { 239.0/256.0, 167.0/256.0, 170.0/256.0,
1173 207.0/255.0, 39.0/255.0, 39.0/255.0, x,
1174 147.0/255.0, 21.0/255.0, 22.0/255.0, x,
1175 175.0/255.0, 175.0/255.0, 175.0/255.0, x,
1176 255.0/255.0,255.0/255.0, 255.0/255.0, x,
1177 255.0/255.0,255.0/255.0, 255.0/255.0, x
1180 CGGradientRef myGradient =
1181 CGGradientCreateWithColorComponents(CGColorSpaceCreateDeviceRGB(), components, locations, num_locations); // expected-warning 2 {{leak}}
1183 CGContextDrawLinearGradient(myContext, myGradient, myStartPoint, myEndPoint,
1187 //===----------------------------------------------------------------------===//
1188 // <rdar://problem/7299394> clang false positive: retained instance passed to
1189 // thread in pthread_create marked as leak
1191 // Until we have full IPA, the analyzer should stop tracking the reference
1192 // count of objects passed to pthread_create.
1194 //===----------------------------------------------------------------------===//
1196 struct _opaque_pthread_t {};
1197 struct _opaque_pthread_attr_t {};
1198 typedef struct _opaque_pthread_t *__darwin_pthread_t;
1199 typedef struct _opaque_pthread_attr_t __darwin_pthread_attr_t;
1200 typedef __darwin_pthread_t pthread_t;
1201 typedef __darwin_pthread_attr_t pthread_attr_t;
1202 typedef unsigned long __darwin_pthread_key_t;
1203 typedef __darwin_pthread_key_t pthread_key_t;
1205 int pthread_create(pthread_t *, const pthread_attr_t *,
1206 void *(*)(void *), void *);
1208 int pthread_setspecific(pthread_key_t key, const void *value);
1210 void *rdar_7299394_start_routine(void *p) {
1214 void rdar_7299394(pthread_attr_t *attr, pthread_t *thread, void *args) {
1215 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1216 pthread_create(thread, attr, rdar_7299394_start_routine, number);
1218 void rdar_7299394_positive(pthread_attr_t *attr, pthread_t *thread) {
1219 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1222 //===----------------------------------------------------------------------===//
1223 // <rdar://problem/11282706> false positive with not understanding thread
1225 //===----------------------------------------------------------------------===//
1227 void rdar11282706(pthread_key_t key) {
1228 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1229 pthread_setspecific(key, (void*) number);
1232 //===----------------------------------------------------------------------===//
1233 // <rdar://problem/7283567> False leak associated with call to
1234 // CVPixelBufferCreateWithBytes ()
1236 // According to the Core Video Reference (ADC), CVPixelBufferCreateWithBytes and
1237 // CVPixelBufferCreateWithPlanarBytes can release (via a callback) the
1238 // pixel buffer object. These test cases show how the analyzer stops tracking
1239 // the reference count for the objects passed for this argument. This
1240 // could be made smarter.
1241 //===----------------------------------------------------------------------===//
1243 typedef int int32_t;
1244 typedef UInt32 FourCharCode;
1245 typedef FourCharCode OSType;
1246 typedef uint64_t CVOptionFlags;
1247 typedef int32_t CVReturn;
1248 typedef struct __CVBuffer *CVBufferRef;
1249 typedef CVBufferRef CVImageBufferRef;
1250 typedef CVImageBufferRef CVPixelBufferRef;
1251 typedef void (*CVPixelBufferReleaseBytesCallback)( void *releaseRefCon, const void *baseAddress );
1253 extern CVReturn CVPixelBufferCreateWithBytes(CFAllocatorRef allocator,
1256 OSType pixelFormatType,
1259 CVPixelBufferReleaseBytesCallback releaseCallback,
1260 void *releaseRefCon,
1261 CFDictionaryRef pixelBufferAttributes,
1262 CVPixelBufferRef *pixelBufferOut) ;
1264 typedef void (*CVPixelBufferReleasePlanarBytesCallback)( void *releaseRefCon, const void *dataPtr, size_t dataSize, size_t numberOfPlanes, const void *planeAddresses[] );
1266 extern CVReturn CVPixelBufferCreateWithPlanarBytes(CFAllocatorRef allocator,
1269 OSType pixelFormatType,
1272 size_t numberOfPlanes,
1273 void *planeBaseAddress[],
1274 size_t planeWidth[],
1275 size_t planeHeight[],
1276 size_t planeBytesPerRow[],
1277 CVPixelBufferReleasePlanarBytesCallback releaseCallback,
1278 void *releaseRefCon,
1279 CFDictionaryRef pixelBufferAttributes,
1280 CVPixelBufferRef *pixelBufferOut) ;
1282 extern CVReturn CVPixelBufferCreateWithBytes(CFAllocatorRef allocator,
1285 OSType pixelFormatType,
1288 CVPixelBufferReleaseBytesCallback releaseCallback,
1289 void *releaseRefCon,
1290 CFDictionaryRef pixelBufferAttributes,
1291 CVPixelBufferRef *pixelBufferOut) ;
1293 CVReturn rdar_7283567(CFAllocatorRef allocator, size_t width, size_t height,
1294 OSType pixelFormatType, void *baseAddress,
1296 CVPixelBufferReleaseBytesCallback releaseCallback,
1297 CFDictionaryRef pixelBufferAttributes,
1298 CVPixelBufferRef *pixelBufferOut) {
1300 // For the allocated object, it doesn't really matter what type it is
1301 // for the purpose of this test. All we want to show is that
1302 // this is freed later by the callback.
1303 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1305 return CVPixelBufferCreateWithBytes(allocator, width, height, pixelFormatType,
1306 baseAddress, bytesPerRow, releaseCallback,
1307 number, // potentially released by callback
1308 pixelBufferAttributes, pixelBufferOut) ;
1311 CVReturn rdar_7283567_2(CFAllocatorRef allocator, size_t width, size_t height,
1312 OSType pixelFormatType, void *dataPtr, size_t dataSize,
1313 size_t numberOfPlanes, void *planeBaseAddress[],
1314 size_t planeWidth[], size_t planeHeight[], size_t planeBytesPerRow[],
1315 CVPixelBufferReleasePlanarBytesCallback releaseCallback,
1316 CFDictionaryRef pixelBufferAttributes,
1317 CVPixelBufferRef *pixelBufferOut) {
1319 // For the allocated object, it doesn't really matter what type it is
1320 // for the purpose of this test. All we want to show is that
1321 // this is freed later by the callback.
1322 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1324 return CVPixelBufferCreateWithPlanarBytes(allocator,
1325 width, height, pixelFormatType, dataPtr, dataSize,
1326 numberOfPlanes, planeBaseAddress, planeWidth,
1327 planeHeight, planeBytesPerRow, releaseCallback,
1328 number, // potentially released by callback
1329 pixelBufferAttributes, pixelBufferOut) ;
1332 #pragma clang arc_cf_code_audited begin
1333 typedef struct SomeOpaqueStruct *CMSampleBufferRef;
1334 CVImageBufferRef _Nonnull CMSampleBufferGetImageBuffer(CMSampleBufferRef _Nonnull sbuf);
1335 #pragma clang arc_cf_code_audited end
1337 CVBufferRef _Nullable CVBufferRetain(CVBufferRef _Nullable buffer);
1338 void CVBufferRelease(CF_CONSUMED CVBufferRef _Nullable buffer);
1340 void testCVPrefixRetain(CMSampleBufferRef sbuf) {
1341 // Make sure RetainCountChecker treats CVFooRetain() as a CF-style retain.
1342 CVPixelBufferRef pixelBuf = CMSampleBufferGetImageBuffer(sbuf);
1343 CVBufferRetain(pixelBuf);
1344 CVBufferRelease(pixelBuf); // no-warning
1347 // Make sure result of CVFooRetain() is the same as its argument.
1348 CVPixelBufferRef pixelBufAlias = CVBufferRetain(pixelBuf);
1349 CVBufferRelease(pixelBufAlias); // no-warning
1352 typedef signed long SInt32;
1353 typedef SInt32 OSStatus;
1354 typedef FourCharCode CMVideoCodecType;
1357 typedef UInt32 VTEncodeInfoFlags; enum {
1358 kVTEncodeInfo_Asynchronous = 1UL << 0,
1359 kVTEncodeInfo_FrameDropped = 1UL << 1,
1367 typedef void (*VTCompressionOutputCallback)(
1368 void * _Nullable outputCallbackRefCon,
1369 void * _Nullable sourceFrameRefCon,
1371 VTEncodeInfoFlags infoFlags,
1372 _Nullable CMSampleBufferRef sampleBuffer );
1374 typedef struct OpaqueVTCompressionSession* VTCompressionSessionRef;
1377 VTCompressionSessionCreate(_Nullable CFAllocatorRef allocator,
1380 CMVideoCodecType codecType,
1381 _Nullable CFDictionaryRef encoderSpecification,
1382 _Nullable CFDictionaryRef sourceImageBufferAttributes,
1383 _Nullable CFAllocatorRef compressedDataAllocator,
1384 _Nullable VTCompressionOutputCallback outputCallback,
1385 void * _Nullable outputCallbackRefCon,
1386 CF_RETURNS_RETAINED _Nullable VTCompressionSessionRef * _Nonnull compressionSessionOut);
1389 VTCompressionSessionEncodeFrame(
1390 _Nonnull VTCompressionSessionRef session,
1391 _Nonnull CVImageBufferRef imageBuffer,
1392 CMTime presentationTimeStamp,
1394 _Nullable CFDictionaryRef frameProperties,
1395 void * _Nullable sourceFrameRefCon,
1396 VTEncodeInfoFlags * _Nullable infoFlagsOut);
1398 OSStatus test_VTCompressionSessionCreateAndEncode_CallbackReleases(
1399 _Nullable CFAllocatorRef allocator,
1402 CMVideoCodecType codecType,
1403 _Nullable CFDictionaryRef encoderSpecification,
1404 _Nullable CFDictionaryRef sourceImageBufferAttributes,
1405 _Nullable CFAllocatorRef compressedDataAllocator,
1406 _Nullable VTCompressionOutputCallback outputCallback,
1408 _Nonnull CVImageBufferRef imageBuffer,
1409 CMTime presentationTimeStamp,
1411 _Nullable CFDictionaryRef frameProperties
1414 // The outputCallback is passed both contexts and so can release either.
1415 NSNumber *contextForCreate = [[NSNumber alloc] initWithInt:5]; // no-warning
1416 NSNumber *contextForEncode = [[NSNumber alloc] initWithInt:6]; // no-warning
1418 VTCompressionSessionRef session = 0;
1419 OSStatus status = VTCompressionSessionCreate(allocator,
1420 width, height, codecType, encoderSpecification,
1421 sourceImageBufferAttributes,
1422 compressedDataAllocator, outputCallback, contextForCreate,
1425 VTEncodeInfoFlags encodeInfoFlags;
1427 status = VTCompressionSessionEncodeFrame(session, imageBuffer,
1428 presentationTimeStamp, duration, frameProperties, contextForEncode,
1434 //===----------------------------------------------------------------------===//
1435 // <rdar://problem/7358899> False leak associated with
1436 // CGBitmapContextCreateWithData
1437 //===----------------------------------------------------------------------===//
1438 typedef uint32_t CGBitmapInfo;
1439 typedef void (*CGBitmapContextReleaseDataCallback)(void *releaseInfo, void *data);
1441 CGContextRef CGBitmapContextCreateWithData(void *data,
1442 size_t width, size_t height, size_t bitsPerComponent,
1443 size_t bytesPerRow, CGColorSpaceRef space, CGBitmapInfo bitmapInfo,
1444 CGBitmapContextReleaseDataCallback releaseCallback, void *releaseInfo);
1446 void rdar_7358899(void *data,
1447 size_t width, size_t height, size_t bitsPerComponent,
1448 size_t bytesPerRow, CGColorSpaceRef space, CGBitmapInfo bitmapInfo,
1449 CGBitmapContextReleaseDataCallback releaseCallback) {
1451 // For the allocated object, it doesn't really matter what type it is
1452 // for the purpose of this test. All we want to show is that
1453 // this is freed later by the callback.
1454 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1456 CGBitmapContextCreateWithData(data, width, height, bitsPerComponent, // expected-warning{{leak}}
1457 bytesPerRow, space, bitmapInfo, releaseCallback, number);
1460 //===----------------------------------------------------------------------===//
1461 // <rdar://problem/7265711> allow 'new', 'copy', 'alloc', 'init' prefix to
1462 // start before '_' when determining Cocoa fundamental rule
1464 // Previously the retain/release checker just skipped prefixes before the
1465 // first '_' entirely. Now the checker honors the prefix if it results in a
1466 // recognizable naming convention (e.g., 'new', 'init').
1467 //===----------------------------------------------------------------------===//
1469 @interface RDar7265711 {}
1473 void rdar7265711_a(RDar7265711 *x) {
1474 id y = [x new_stuff]; // expected-warning{{leak}}
1477 void rdar7265711_b(RDar7265711 *x) {
1478 id y = [x new_stuff]; // no-warning
1482 //===----------------------------------------------------------------------===//
1483 // <rdar://problem/7306898> clang thinks [NSCursor dragCopyCursor] returns a
1484 // retained reference
1485 //===----------------------------------------------------------------------===//
1487 @interface NSCursor : NSObject
1488 + (NSCursor *)dragCopyCursor;
1491 void rdar7306898(void) {
1492 // 'dragCopyCursor' does not follow Cocoa's fundamental rule. It is a noun, not an sentence
1493 // implying a 'copy' of something.
1494 NSCursor *c = [NSCursor dragCopyCursor]; // no-warning
1495 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1498 //===----------------------------------------------------------------------===//
1499 // <rdar://problem/7252064> sending 'release', 'retain', etc. to a Class
1500 // directly is not likely what the user intended
1501 //===----------------------------------------------------------------------===//
1503 @interface RDar7252064 : NSObject @end
1504 void rdar7252064(void) {
1505 [RDar7252064 release]; // expected-warning{{The 'release' message should be sent to instances of class 'RDar7252064' and not the class directly}}
1506 [RDar7252064 retain]; // expected-warning{{The 'retain' message should be sent to instances of class 'RDar7252064' and not the class directly}}
1507 [RDar7252064 autorelease]; // expected-warning{{The 'autorelease' message should be sent to instances of class 'RDar7252064' and not the class directly}}
1508 [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}}
1511 //===----------------------------------------------------------------------===//
1512 // Tests of ownership attributes.
1513 //===----------------------------------------------------------------------===//
1515 typedef NSString* MyStringTy;
1519 @interface TestOwnershipAttr : NSObject
1520 - (NSString*) returnsAnOwnedString NS_RETURNS_RETAINED; // no-warning
1521 - (NSString*) returnsAnOwnedCFString CF_RETURNS_RETAINED; // no-warning
1522 - (MyStringTy) returnsAnOwnedTypedString NS_RETURNS_RETAINED; // no-warning
1523 - (NSString*) newString NS_RETURNS_NOT_RETAINED; // no-warning
1524 - (NSString*) newString_auto NS_RETURNS_AUTORELEASED; // no-warning
1525 - (NSString*) newStringNoAttr;
1526 - (int) returnsAnOwnedInt NS_RETURNS_RETAINED; // expected-warning{{'ns_returns_retained' attribute only applies to methods that return an Objective-C object}}
1527 - (id) pseudoInit NS_CONSUMES_SELF NS_RETURNS_RETAINED;
1528 + (void) consume:(id) NS_CONSUMED x;
1529 + (void) consume2:(id) CF_CONSUMED x;
1532 static int ownership_attribute_doesnt_go_here NS_RETURNS_RETAINED; // expected-warning{{'ns_returns_retained' only applies to function types; type here is 'int'}}
1534 void test_attr_1(TestOwnershipAttr *X) {
1535 NSString *str = [X returnsAnOwnedString]; // expected-warning{{leak}}
1538 void test_attr_1b(TestOwnershipAttr *X) {
1539 NSString *str = [X returnsAnOwnedCFString]; // expected-warning{{leak}}
1542 void test_attr1c(TestOwnershipAttr *X) {
1543 NSString *str = [X newString]; // no-warning
1544 NSString *str2 = [X newStringNoAttr]; // expected-warning{{leak}}
1545 NSString *str3 = [X newString_auto]; // no-warning
1546 NSString *str4 = [[X newString_auto] retain]; // expected-warning {{leak}}
1549 void testattr2_a() {
1550 TestOwnershipAttr *x = [TestOwnershipAttr alloc]; // expected-warning{{leak}}
1553 void testattr2_b() {
1554 TestOwnershipAttr *x = [[TestOwnershipAttr alloc] pseudoInit]; // expected-warning{{leak}}
1557 void testattr2_b_11358224_self_assign_looses_the_leak() {
1558 TestOwnershipAttr *x = [[TestOwnershipAttr alloc] pseudoInit];// expected-warning{{leak}}
1562 void testattr2_c() {
1563 TestOwnershipAttr *x = [[TestOwnershipAttr alloc] pseudoInit]; // no-warning
1568 TestOwnershipAttr *x = [TestOwnershipAttr alloc]; // no-warning
1569 [TestOwnershipAttr consume:x];
1570 TestOwnershipAttr *y = [TestOwnershipAttr alloc]; // no-warning
1571 [TestOwnershipAttr consume2:y];
1574 void consume_ns(id NS_CONSUMED x);
1575 void consume_cf(id CF_CONSUMED x);
1578 TestOwnershipAttr *x = [TestOwnershipAttr alloc]; // no-warning
1580 TestOwnershipAttr *y = [TestOwnershipAttr alloc]; // no-warning
1584 @interface TestOwnershipAttr2 : NSObject
1585 - (NSString*) newString NS_RETURNS_NOT_RETAINED; // no-warning
1588 @implementation TestOwnershipAttr2
1589 - (NSString*) newString {
1590 return [NSString alloc]; // expected-warning {{Potential leak of an object}}
1594 @interface MyClassTestCFAttr : NSObject {}
1595 - (NSDate*) returnsCFRetained CF_RETURNS_RETAINED;
1596 - (CFDateRef) returnsCFRetainedAsCF CF_RETURNS_RETAINED;
1597 - (CFDateRef) newCFRetainedAsCF CF_RETURNS_NOT_RETAINED;
1598 - (CFDateRef) newCFRetainedAsCFNoAttr;
1599 - (NSDate*) alsoReturnsRetained;
1600 - (CFDateRef) alsoReturnsRetainedAsCF;
1601 - (NSDate*) returnsNSRetained NS_RETURNS_RETAINED;
1605 CFDateRef returnsRetainedCFDate() {
1606 return CFDateCreate(0, CFAbsoluteTimeGetCurrent());
1609 @implementation MyClassTestCFAttr
1610 - (NSDate*) returnsCFRetained {
1611 return (NSDate*) returnsRetainedCFDate(); // No leak.
1614 - (CFDateRef) returnsCFRetainedAsCF {
1615 return returnsRetainedCFDate(); // No leak.
1618 - (CFDateRef) newCFRetainedAsCF {
1619 return (CFDateRef)[(id)[self returnsCFRetainedAsCF] autorelease];
1622 - (CFDateRef) newCFRetainedAsCFNoAttr {
1623 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}}
1626 - (NSDate*) alsoReturnsRetained {
1627 return (NSDate*) returnsRetainedCFDate(); // expected-warning{{leak}}
1630 - (CFDateRef) alsoReturnsRetainedAsCF {
1631 return returnsRetainedCFDate(); // expected-warning{{leak}}
1635 - (NSDate*) returnsNSRetained {
1636 return (NSDate*) returnsRetainedCFDate(); // no-warning
1640 //===----------------------------------------------------------------------===//
1641 // Test that leaks post-dominated by "panic" functions are not reported.
1643 // <rdar://problem/5905851> do not report a leak when post-dominated by a call
1644 // to a noreturn or panic function
1645 //===----------------------------------------------------------------------===//
1647 void panic() __attribute__((noreturn));
1648 void panic_not_in_hardcoded_list() __attribute__((noreturn));
1650 void test_panic_negative() {
1652 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // expected-warning{{leak}}
1655 void test_panic_positive() {
1657 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // no-warning
1661 void test_panic_neg_2(int x) {
1663 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // expected-warning{{leak}}
1668 void test_panic_pos_2(int x) {
1670 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // no-warning
1674 // This showed up in <rdar://problem/7796563>, where we silently missed checking
1675 // the function type for noreturn. "panic()" is a hard-coded known panic function
1676 // that isn't always noreturn.
1677 panic_not_in_hardcoded_list();
1681 //===----------------------------------------------------------------------===//
1682 // Test uses of blocks (closures)
1683 //===----------------------------------------------------------------------===//
1685 void test_blocks_1_pos(void) {
1686 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1690 void test_blocks_1_indirect_release(void) {
1691 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1692 ^{ [number release]; }();
1695 void test_blocks_1_indirect_retain(void) {
1696 // Eventually this should be reported as a leak.
1697 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1698 ^{ [number retain]; }();
1701 void test_blocks_1_indirect_release_via_call(void) {
1702 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1703 ^(NSObject *o){ [o release]; }(number);
1706 void test_blocks_1_indirect_retain_via_call(void) {
1707 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning {{leak}}
1708 ^(NSObject *o){ [o retain]; }(number);
1711 //===--------------------------------------------------------------------===//
1712 // Test sending message to super that returns an object alias. Previously
1713 // this caused a crash in the analyzer.
1714 //===--------------------------------------------------------------------===//
1716 @interface Rdar8015556 : NSObject {} @end
1717 @implementation Rdar8015556
1719 return [super retain];
1723 // <rdar://problem/8272168> - Correcly handle Class<...> in Cocoa Conventions
1726 @protocol Prot_R8272168 @end
1727 Class <Prot_R8272168> GetAClassThatImplementsProt_R8272168();
1729 GetAClassThatImplementsProt_R8272168();
1732 // Test case for <rdar://problem/8356342>, which in the past triggered
1733 // a false positive.
1734 @interface RDar8356342
1735 - (NSDate*) rdar8356342:(NSDate *)inValue;
1738 @implementation RDar8356342
1739 - (NSDate*) rdar8356342:(NSDate*)inValue {
1740 NSDate *outValue = inValue;
1742 outValue = [[NSDate alloc] init]; // no-warning
1744 if (outValue != inValue)
1745 [outValue autorelease];
1751 // <rdar://problem/8724287> - This test case previously crashed because
1752 // of a bug in BugReporter.
1753 extern const void *CFDictionaryGetValue(CFDictionaryRef theDict, const void *key);
1754 typedef struct __CFError * CFErrorRef;
1755 extern const CFStringRef kCFErrorUnderlyingErrorKey;
1756 extern CFDictionaryRef CFErrorCopyUserInfo(CFErrorRef err);
1757 static void rdar_8724287(CFErrorRef error)
1759 CFErrorRef error_to_dump;
1761 error_to_dump = error;
1762 while (error_to_dump != ((void*)0)) {
1763 CFDictionaryRef info;
1765 info = CFErrorCopyUserInfo(error_to_dump); // expected-warning{{Potential leak of an object}}
1767 if (info != ((void*)0)) {
1770 error_to_dump = (CFErrorRef) CFDictionaryGetValue(info, kCFErrorUnderlyingErrorKey);
1774 // <rdar://problem/9234108> - Make sure the model applies cf_consumed
1775 // correctly in argument positions besides the first.
1776 extern void *CFStringCreate(void);
1777 extern void rdar_9234108_helper(void *key, void * CF_CONSUMED value);
1778 void rdar_9234108() {
1779 rdar_9234108_helper(0, CFStringCreate());
1782 // <rdar://problem/9726279> - Make sure that objc_method_family works
1783 // to override naming conventions.
1788 typedef struct TwoDoubles TwoDoubles;
1790 @interface NSValue (Mine)
1791 - (id)_prefix_initWithTwoDoubles:(TwoDoubles)twoDoubles __attribute__((objc_method_family(init)));
1794 @implementation NSValue (Mine)
1795 - (id)_prefix_initWithTwoDoubles:(TwoDoubles)twoDoubles
1801 void rdar9726279() {
1802 TwoDoubles twoDoubles = { 0.0, 0.0 };
1803 NSValue *value = [[NSValue alloc] _prefix_initWithTwoDoubles:twoDoubles];
1807 // <rdar://problem/9732321>
1808 // Test camelcase support for CF conventions. While Core Foundation APIs
1809 // don't use camel casing, other code is allowed to use it.
1810 CFArrayRef camelcase_create_1() {
1811 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1814 CFArrayRef camelcase_createno() {
1815 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1818 CFArrayRef camelcase_copy() {
1819 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1822 CFArrayRef camelcase_copying() {
1823 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1826 CFArrayRef copyCamelCase() {
1827 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1830 CFArrayRef __copyCamelCase() {
1831 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1834 CFArrayRef __createCamelCase() {
1835 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1838 CFArrayRef camel_create() {
1839 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1843 CFArrayRef camel_creat() {
1844 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1847 CFArrayRef camel_copy() {
1848 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1851 CFArrayRef camel_copyMachine() {
1852 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1855 CFArrayRef camel_copymachine() {
1856 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1859 // rdar://problem/8024350
1861 - (id) clone; // expected-note 2 {{method declared here}}
1863 @interface F18 : NSObject<F18P> @end
1865 - (id) clone NS_RETURNS_RETAINED; // expected-warning {{overriding method has mismatched ns_returns_retained attributes}}
1869 - (id) clone { // expected-warning {{overriding method has mismatched ns_returns_retained attributes}}
1875 void rdar6582778(void) {
1876 CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
1877 CFTypeRef vals[] = { CFDateCreate(0, t) }; // expected-warning {{leak}}
1882 void rdar6582778_2(void) {
1883 CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
1884 global = CFDateCreate(0, t); // no-warning
1887 // <rdar://problem/10232019> - Test that objects passed to containers
1888 // are marked "escaped".
1890 void rdar10232019() {
1891 NSMutableArray *array = [NSMutableArray array];
1893 NSString *string = [[NSString alloc] initWithUTF8String:"foo"];
1894 [array addObject:string];
1897 NSString *otherString = [string stringByAppendingString:@"bar"]; // no-warning
1898 NSLog(@"%@", otherString);
1901 void rdar10232019_positive() {
1902 NSMutableArray *array = [NSMutableArray array];
1904 NSString *string = [[NSString alloc] initWithUTF8String:"foo"];
1907 NSString *otherString = [string stringByAppendingString:@"bar"]; // expected-warning {{Reference-counted object is used after it is release}}
1908 NSLog(@"%@", otherString);
1911 // RetainCountChecker support for XPC.
1912 // <rdar://problem/9658496>
1913 typedef void * xpc_object_t;
1914 xpc_object_t _CFXPCCreateXPCObjectFromCFObject(CFTypeRef cf);
1915 void xpc_release(xpc_object_t object);
1917 void rdar9658496() {
1920 cf = CFStringCreateWithCString( ((CFAllocatorRef)0), "test", kCFStringEncodingUTF8 ); // no-warning
1921 xpc = _CFXPCCreateXPCObjectFromCFObject( cf );
1926 // Support annotations with method families.
1927 @interface RDar10824732 : NSObject
1928 - (id)initWithObj:(id CF_CONSUMED)obj;
1931 @implementation RDar10824732
1932 - (id)initWithObj:(id)obj {
1934 return [super init];
1938 void rdar_10824732() {
1940 NSString *obj = @"test";
1941 RDar10824732 *foo = [[RDar10824732 alloc] initWithObj:obj]; // no-warning
1946 // Stop tracking objects passed to functions, which take callbacks as parameters.
1948 typedef int (*CloseCallback) (void *);
1949 void ReaderForIO(CloseCallback ioclose, void *ioctx);
1950 int IOClose(void *context);
1952 @protocol SInS <NSObject>
1955 @interface radar10973977 : NSObject
1960 @implementation radar10973977
1963 id<SInS> inputS = [[self inputS] retain];
1964 ReaderForIO(IOClose, inputS);
1972 // Object escapes through a selector callback: radar://11398514
1974 @interface MySheetController
1976 - (void)showDoSomethingSheetAction:(id)action;
1977 - (void)sheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo;
1980 @implementation MySheetController
1981 - (id<SInS>)inputS {
1984 - (void)showDoSomethingSheetAction:(id)action {
1985 id<SInS> inputS = [[self inputS] retain];
1989 didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:)
1990 contextInfo:(void *)inputS]; // no - warning
1992 - (void)sheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo {
1994 id contextObject = (id)contextInfo;
1995 [contextObject release];
1998 - (id)copyAutoreleaseRadar13081402 {
1999 id x = [[[NSString alloc] initWithUTF8String:"foo"] autorelease];
2001 return x; // no warning
2005 //===----------------------------------------------------------------------===//
2006 // Test returning allocated memory in a struct.
2008 // We currently don't have a general way to track pointers that "escape".
2009 // Here we test that RetainCountChecker doesn't get excited about returning
2010 // allocated CF objects in struct fields.
2011 //===----------------------------------------------------------------------===//
2012 void *malloc(size_t);
2013 struct rdar11104566 { CFStringRef myStr; };
2014 struct rdar11104566 test_rdar11104566() {
2015 CFStringRef cf = CFStringCreateWithCString( ((CFAllocatorRef)0), "test", kCFStringEncodingUTF8 ); // no-warning
2016 struct rdar11104566 V;
2018 return V; // no-warning
2021 struct rdar11104566 *test_2_rdar11104566() {
2022 CFStringRef cf = CFStringCreateWithCString( ((CFAllocatorRef)0), "test", kCFStringEncodingUTF8 ); // no-warning
2023 struct rdar11104566 *V = (struct rdar11104566 *) malloc(sizeof(*V));
2025 return V; // no-warning
2028 //===----------------------------------------------------------------------===//
2029 // ObjC literals support.
2030 //===----------------------------------------------------------------------===//
2032 void test_objc_arrays() {
2033 { // CASE ONE -- OBJECT IN ARRAY CREATED DIRECTLY
2034 NSObject *o = [[NSObject alloc] init];
2035 NSArray *a = [[NSArray alloc] initWithObjects:o, (void*)0]; // expected-warning {{leak}}
2041 { // CASE TWO -- OBJECT IN ARRAY CREATED BY DUPING AUTORELEASED ARRAY
2042 NSObject *o = [[NSObject alloc] init];
2043 NSArray *a1 = [NSArray arrayWithObjects:o, (void*)0];
2044 NSArray *a2 = [[NSArray alloc] initWithArray:a1]; // expected-warning {{leak}}
2050 { // CASE THREE -- OBJECT IN RETAINED @[]
2051 NSObject *o = [[NSObject alloc] init];
2052 NSArray *a3 = [@[o] retain]; // expected-warning {{leak}}
2058 { // CASE FOUR -- OBJECT IN ARRAY CREATED BY DUPING @[]
2059 NSObject *o = [[NSObject alloc] init];
2060 NSArray *a = [[NSArray alloc] initWithArray:@[o]]; // expected-warning {{leak}}
2067 { // CASE FIVE -- OBJECT IN RETAINED @{}
2068 NSValue *o = [[NSValue alloc] init];
2069 NSDictionary *a = [@{o : o} retain]; // expected-warning {{leak}}
2077 void test_objc_integer_literals() {
2078 id value = [@1 retain]; // expected-warning {{leak}}
2079 [value description];
2082 void test_objc_boxed_expressions(int x, const char *y) {
2083 id value = [@(x) retain]; // expected-warning {{leak}}
2084 [value description];
2086 value = [@(y) retain]; // expected-warning {{leak}}
2087 [value description];
2090 // Test NSLog doesn't escape tracked objects.
2091 void rdar11400885(int y)
2094 NSString *printString;
2096 printString = [[NSString alloc] init];
2098 printString = [[NSString alloc] init];
2099 NSLog(@"Once %@", printString);
2100 [printString release];
2101 NSLog(@"Again: %@", printString); // expected-warning {{Reference-counted object is used after it is released}}
2105 id makeCollectableNonLeak() {
2106 extern CFTypeRef CFCreateSomething();
2108 CFTypeRef object = CFCreateSomething(); // +1
2109 CFRetain(object); // +2
2110 id objCObject = NSMakeCollectable(object); // +2
2111 [objCObject release]; // +1
2112 return [objCObject autorelease]; // +0
2115 void consumeAndStopTracking(id NS_CONSUMED obj, void (^callback)(void));
2116 void CFConsumeAndStopTracking(CFTypeRef CF_CONSUMED obj, void (^callback)(void));
2118 void testConsumeAndStopTracking() {
2119 id retained = [@[] retain]; // +1
2120 consumeAndStopTracking(retained, ^{}); // no-warning
2122 id doubleRetained = [[@[] retain] retain]; // +2
2123 consumeAndStopTracking(doubleRetained, ^{
2124 [doubleRetained release];
2127 id unretained = @[]; // +0
2128 consumeAndStopTracking(unretained, ^{}); // expected-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
2131 void testCFConsumeAndStopTracking() {
2132 id retained = [@[] retain]; // +1
2133 CFConsumeAndStopTracking((CFTypeRef)retained, ^{}); // no-warning
2135 id doubleRetained = [[@[] retain] retain]; // +2
2136 CFConsumeAndStopTracking((CFTypeRef)doubleRetained, ^{
2137 [doubleRetained release];
2140 id unretained = @[]; // +0
2141 CFConsumeAndStopTracking((CFTypeRef)unretained, ^{}); // expected-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
2143 //===----------------------------------------------------------------------===//
2144 // Test 'pragma clang arc_cf_code_audited' support.
2145 //===----------------------------------------------------------------------===//
2147 typedef void *MyCFType;
2148 #pragma clang arc_cf_code_audited begin
2149 MyCFType CreateMyCFType();
2150 #pragma clang arc_cf_code_audited end
2152 void test_custom_cf() {
2153 MyCFType x = CreateMyCFType(); // expected-warning {{leak of an object stored into 'x'}}
2156 //===----------------------------------------------------------------------===//
2157 // Test calling CFPlugInInstanceCreate, which appears in CF but doesn't
2158 // return a CF object.
2159 //===----------------------------------------------------------------------===//
2161 void test_CFPlugInInstanceCreate(CFUUIDRef factoryUUID, CFUUIDRef typeUUID) {
2162 CFPlugInInstanceCreate(kCFAllocatorDefault, factoryUUID, typeUUID); // no-warning
2165 //===----------------------------------------------------------------------===//
2166 // PR14927: -drain only has retain-count semantics on NSAutoreleasePool.
2167 //===----------------------------------------------------------------------===//
2169 @interface PR14927 : NSObject
2174 PR14927 *obj = [[PR14927 alloc] init];
2176 [obj release]; // no-warning
2179 //===----------------------------------------------------------------------===//
2180 // Allow cf_returns_retained and cf_returns_not_retained to mark a return
2181 // value as tracked, even if the object isn't a known CF type.
2182 //===----------------------------------------------------------------------===//
2184 MyCFType getCustom() __attribute__((cf_returns_not_retained));
2185 MyCFType makeCustom() __attribute__((cf_returns_retained));
2187 void testCustomReturnsRetained() {
2188 MyCFType obj = makeCustom(); // expected-warning {{leak of an object stored into 'obj'}}
2191 void testCustomReturnsNotRetained() {
2192 CFRelease(getCustom()); // expected-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
2195 //===----------------------------------------------------------------------===//
2196 // Don't print variables which are out of the current scope.
2197 //===----------------------------------------------------------------------===//
2198 @interface MyObj12706177 : NSObject
2200 +(void)test12706177;
2203 @implementation MyObj12706177
2207 self = [super init];
2210 +(void)test12706177 {
2211 id x = [[MyObj12706177 alloc] initX]; //expected-warning {{Potential leak of an object}}
2216 //===----------------------------------------------------------------------===//
2218 //===----------------------------------------------------------------------===//
2220 CFTypeRef getAutoreleasedCFType() {
2221 extern CFTypeRef CFCreateSomething();
2222 return CFAutorelease(CFCreateSomething()); // no-warning
2225 CFTypeRef getIncorrectlyAutoreleasedCFType() {
2226 extern CFTypeRef CFGetSomething();
2227 return CFAutorelease(CFGetSomething()); // expected-warning{{Object autoreleased too many times}}
2230 CFTypeRef createIncorrectlyAutoreleasedCFType() {
2231 extern CFTypeRef CFCreateSomething();
2232 return CFAutorelease(CFCreateSomething()); // expected-warning{{Object with a +0 retain count returned to caller where a +1 (owning) retain count is expected}}
2235 void useAfterAutorelease() {
2236 extern CFTypeRef CFCreateSomething();
2237 CFTypeRef obj = CFCreateSomething();
2240 extern void useCF(CFTypeRef);
2241 useCF(obj); // no-warning
2244 void useAfterRelease() {
2245 // Sanity check that the previous example would have warned with CFRelease.
2246 extern CFTypeRef CFCreateSomething();
2247 CFTypeRef obj = CFCreateSomething();
2250 extern void useCF(CFTypeRef);
2251 useCF(obj); // expected-warning{{Reference-counted object is used after it is released}}
2254 void testAutoreleaseReturnsInput() {
2255 extern CFTypeRef CFCreateSomething();
2256 CFTypeRef obj = CFCreateSomething(); // expected-warning{{Potential leak of an object stored into 'obj'}}
2257 CFTypeRef second = CFAutorelease(obj);
2261 CFTypeRef testAutoreleaseReturnsInputSilent() {
2262 extern CFTypeRef CFCreateSomething();
2263 CFTypeRef obj = CFCreateSomething();
2264 CFTypeRef alias = CFAutorelease(obj);
2267 return obj; // no-warning
2270 void autoreleaseTypedObject() {
2271 CFArrayRef arr = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
2272 CFAutorelease((CFTypeRef)arr); // no-warning
2275 void autoreleaseReturningTypedObject() {
2276 CFArrayRef arr = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning{{Potential leak of an object stored into 'arr'}}
2277 CFArrayRef alias = (CFArrayRef)CFAutorelease((CFTypeRef)arr);
2281 CFArrayRef autoreleaseReturningTypedObjectSilent() {
2282 CFArrayRef arr = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
2283 CFArrayRef alias = (CFArrayRef)CFAutorelease((CFTypeRef)arr);
2286 return alias; // no-warning
2289 void autoreleaseObjC() {
2290 id obj = [@1 retain];
2291 CFAutorelease(obj); // no-warning
2294 CFAutorelease(anotherObj);
2295 } // expected-warning{{Object autoreleased too many times}}
2297 //===----------------------------------------------------------------------===//
2298 // <rdar://problem/13783514> xpc_connection_set_finalizer_f
2299 //===----------------------------------------------------------------------===//
2301 typedef xpc_object_t xpc_connection_t;
2302 typedef void (*xpc_finalizer_t)(void *value);
2303 void xpc_connection_set_context(xpc_connection_t connection, void *ctx);
2304 void xpc_connection_set_finalizer_f(xpc_connection_t connection,
2305 xpc_finalizer_t finalizer);
2306 void releaseAfterXPC(void *context) {
2307 [(NSArray *)context release];
2310 void rdar13783514(xpc_connection_t connection) {
2311 xpc_connection_set_context(connection, [[NSMutableArray alloc] init]);
2312 xpc_connection_set_finalizer_f(connection, releaseAfterXPC);
2315 // Do not report leaks when object is cleaned up with __attribute__((cleanup ..)).
2316 inline static void cleanupFunction(void *tp) {
2317 CFTypeRef x = *(CFTypeRef *)tp;
2322 #define ADDCLEANUP __attribute__((cleanup(cleanupFunction)))
2324 ADDCLEANUP CFStringRef myString;
2325 myString = CFStringCreateWithCString(0, "hello world", kCFStringEncodingUTF8);
2326 ADDCLEANUP CFStringRef myString2 =
2327 CFStringCreateWithCString(0, "hello world", kCFStringEncodingUTF8);
2330 //===----------------------------------------------------------------------===//
2332 //===----------------------------------------------------------------------===//
2334 __attribute__((ns_returns_retained))
2336 return [NSNull null]; // no-warning
2339 //===----------------------------------------------------------------------===//
2340 // cf_returns_[not_]retained on parameters
2341 //===----------------------------------------------------------------------===//
2343 void testCFReturnsNotRetained() {
2344 extern void getViaParam(CFTypeRef * CF_RETURNS_NOT_RETAINED outObj);
2347 CFRelease(obj); // // expected-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
2350 void testCFReturnsNotRetainedAnnotated() {
2351 extern void getViaParam2(CFTypeRef * _Nonnull CF_RETURNS_NOT_RETAINED outObj);
2354 CFRelease(obj); // // expected-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
2357 void testCFReturnsRetained() {
2358 extern int copyViaParam(CFTypeRef * CF_RETURNS_RETAINED outObj);
2362 CFRelease(obj); // // FIXME-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
2365 void testCFReturnsRetainedError() {
2366 extern int copyViaParam(CFTypeRef * CF_RETURNS_RETAINED outObj);
2368 if (copyViaParam(&obj) == -42)
2369 return; // no-warning