2 // RUN: %clang_cc1 -fblocks -objcmt-migrate-annotation -objcmt-migrate-instancetype -objcmt-migrate-readwrite-property -mt-migrate-directory %t %s -x objective-c -triple x86_64-apple-darwin11
3 // RUN: c-arcmt-test -mt-migrate-directory %t | arcmt-test -verify-transformed-files %s.result
4 // RUN: %clang_cc1 -fblocks -triple x86_64-apple-darwin10 -fsyntax-only -x objective-c %s.result
6 #ifndef CF_IMPLICIT_BRIDGING_ENABLED
7 #if __has_feature(arc_cf_code_audited)
8 #define CF_IMPLICIT_BRIDGING_ENABLED _Pragma("clang arc_cf_code_audited begin")
10 #define CF_IMPLICIT_BRIDGING_ENABLED
14 #ifndef CF_IMPLICIT_BRIDGING_DISABLED
15 #if __has_feature(arc_cf_code_audited)
16 #define CF_IMPLICIT_BRIDGING_DISABLED _Pragma("clang arc_cf_code_audited end")
18 #define CF_IMPLICIT_BRIDGING_DISABLED
22 #if __has_feature(attribute_ns_returns_retained)
23 #define NS_RETURNS_RETAINED __attribute__((ns_returns_retained))
25 #if __has_feature(attribute_cf_returns_retained)
26 #define CF_RETURNS_RETAINED __attribute__((cf_returns_retained))
28 #if __has_feature(attribute_ns_returns_not_retained)
29 #define NS_RETURNS_NOT_RETAINED __attribute__((ns_returns_not_retained))
31 #if __has_feature(attribute_cf_returns_not_retained)
32 #define CF_RETURNS_NOT_RETAINED __attribute__((cf_returns_not_retained))
34 #if __has_feature(attribute_ns_consumes_self)
35 #define NS_CONSUMES_SELF __attribute__((ns_consumes_self))
37 #if __has_feature(attribute_ns_consumed)
38 #define NS_CONSUMED __attribute__((ns_consumed))
40 #if __has_feature(attribute_cf_consumed)
41 #define CF_CONSUMED __attribute__((cf_consumed))
43 #if __has_attribute(ns_returns_autoreleased)
44 #define NS_RETURNS_AUTORELEASED __attribute__((ns_returns_autoreleased))
47 //===----------------------------------------------------------------------===//
48 // The following code is reduced using delta-debugging from Mac OS X headers:
50 // #include <Cocoa/Cocoa.h>
51 // #include <CoreFoundation/CoreFoundation.h>
52 // #include <DiskArbitration/DiskArbitration.h>
53 // #include <QuartzCore/QuartzCore.h>
54 // #include <Quartz/Quartz.h>
55 // #include <IOKit/IOKitLib.h>
57 // It includes the basic definitions for the test cases below.
58 //===----------------------------------------------------------------------===//
60 typedef unsigned int __darwin_natural_t;
61 typedef unsigned long uintptr_t;
62 typedef unsigned int uint32_t;
63 typedef unsigned long long uint64_t;
64 typedef unsigned int UInt32;
65 typedef signed long CFIndex;
66 typedef CFIndex CFByteOrder;
71 static __inline__ __attribute__((always_inline)) CFRange CFRangeMake(CFIndex loc, CFIndex len) {
77 typedef const void * CFTypeRef;
78 typedef const struct __CFString * CFStringRef;
79 typedef const struct __CFAllocator * CFAllocatorRef;
80 extern const CFAllocatorRef kCFAllocatorDefault;
81 extern CFTypeRef CFRetain(CFTypeRef cf);
83 CF_IMPLICIT_BRIDGING_ENABLED
85 extern void CFRelease(CFTypeRef cf);
87 CF_IMPLICIT_BRIDGING_DISABLED
89 extern CFTypeRef CFMakeCollectable(CFTypeRef 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) CF_RETURNS_RETAINED;
97 extern const void *CFArrayGetValueAtIndex(CFArrayRef theArray, CFIndex idx) CF_RETURNS_NOT_RETAINED;
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) CF_RETURNS_RETAINED;
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) CF_RETURNS_RETAINED;
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) CF_RETURNS_RETAINED;
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) CF_RETURNS_RETAINED;
130 typedef const struct __CFAttributedString *CFAttributedStringRef;
131 typedef struct __CFAttributedString *CFMutableAttributedStringRef;
132 extern CFAttributedStringRef CFAttributedStringCreate(CFAllocatorRef alloc, CFStringRef str, CFDictionaryRef attributes) CF_RETURNS_RETAINED ;
133 extern CFMutableAttributedStringRef CFAttributedStringCreateMutableCopy(CFAllocatorRef alloc, CFIndex maxLength, CFAttributedStringRef aStr) CF_RETURNS_RETAINED ;
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;
147 - (instancetype)init;
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 - (instancetype)initWithInt:(int)value;
178 + (NSNumber *)numberWithInt:(int)value;
181 @interface NSArray : NSObject <NSCopying, NSMutableCopying, NSCoding, NSFastEnumeration>
183 - (instancetype)initWithObjects:(const id [])objects count:(NSUInteger)cnt;
184 + (instancetype)arrayWithObject:(id)anObject;
185 + (instancetype)arrayWithObjects:(const id [])objects count:(NSUInteger)cnt;
186 + (instancetype)arrayWithObjects:(id)firstObj, ... __attribute__((sentinel(0,1)));
187 - (instancetype)initWithObjects:(id)firstObj, ... __attribute__((sentinel(0,1)));
188 - (instancetype)initWithArray:(NSArray *)array;
189 @end @interface NSArray (NSArrayCreation) + (instancetype)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 - (instancetype)initWithUTF8String:(const char *)nullTerminatedCString;
202 + (instancetype)stringWithUTF8String:(const char *)nullTerminatedCString;
203 @end @class NSString, NSURL, NSError;
204 @interface NSData : NSObject <NSCopying, NSMutableCopying, NSCoding> - (NSUInteger)length;
205 + (instancetype)dataWithBytesNoCopy:(void *)bytes length:(NSUInteger)length;
206 + (instancetype)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 + (instancetype)dictionaryWithObjects:(NSArray *)objects forKeys:(NSArray *)keys;
211 + (instancetype)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;
215 @end @interface NSMutableDictionary (NSMutableDictionaryCreation) + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
216 @end 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 );
230 CF_IMPLICIT_BRIDGING_ENABLED
232 io_service_t IOServiceGetMatchingService( mach_port_t masterPort, CFDictionaryRef matching );
233 kern_return_t IOServiceGetMatchingServices( mach_port_t masterPort, CFDictionaryRef matching, io_iterator_t * existing );
235 CF_IMPLICIT_BRIDGING_DISABLED
237 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' declared here}}
238 kern_return_t IOServiceAddMatchingNotification( IONotificationPortRef notifyPort, const io_name_t notificationType, CFDictionaryRef CF_CONSUMED matching, IOServiceMatchingCallback callback, void * refCon, io_iterator_t * notification );
240 CF_IMPLICIT_BRIDGING_ENABLED
242 CFMutableDictionaryRef IOServiceMatching( const char * name );
243 CFMutableDictionaryRef IOServiceNameMatching( const char * name );
244 CFMutableDictionaryRef IOBSDNameMatching( mach_port_t masterPort, uint32_t options, const char * bsdName );
245 CFMutableDictionaryRef IOOpenFirmwarePathMatching( mach_port_t masterPort, uint32_t options, const char * path );
246 CFMutableDictionaryRef IORegistryEntryIDMatching( uint64_t entryID );
248 CF_IMPLICIT_BRIDGING_DISABLED
250 typedef struct __DASession * DASessionRef;
251 extern DASessionRef DASessionCreate( CFAllocatorRef allocator ) CF_RETURNS_RETAINED;
252 typedef struct __DADisk * DADiskRef;
253 extern DADiskRef DADiskCreateFromBSDName( CFAllocatorRef allocator, DASessionRef session, const char * name ) CF_RETURNS_RETAINED;
254 extern DADiskRef DADiskCreateFromIOMedia( CFAllocatorRef allocator, DASessionRef session, io_service_t media ) CF_RETURNS_RETAINED;
255 extern CFDictionaryRef DADiskCopyDescription( DADiskRef disk ) CF_RETURNS_RETAINED;
256 extern DADiskRef DADiskCopyWholeDisk( DADiskRef disk ) CF_RETURNS_RETAINED;
257 @interface NSTask : NSObject - (instancetype)init;
258 @end typedef struct CGColorSpace *CGColorSpaceRef;
259 typedef struct CGImage *CGImageRef;
260 typedef struct CGLayer *CGLayerRef;
261 @interface NSResponder : NSObject <NSCoding> {
263 @end @protocol NSAnimatablePropertyContainer - (id)animator;
264 @end extern NSString *NSAnimationTriggerOrderIn ;
265 @interface NSView : NSResponder <NSAnimatablePropertyContainer> {
267 @end @protocol NSValidatedUserInterfaceItem - (SEL)action;
268 @end @protocol NSUserInterfaceValidations - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)anItem;
269 @end @class NSDate, NSDictionary, NSError, NSException, NSNotification;
270 @class NSTextField, NSPanel, NSArray, NSWindow, NSImage, NSButton, NSError;
271 @interface NSApplication : NSResponder <NSUserInterfaceValidations> {
273 - (void)beginSheet:(NSWindow *)sheet modalForWindow:(NSWindow *)docWindow modalDelegate:(id)modalDelegate didEndSelector:(SEL)didEndSelector contextInfo:(void *)contextInfo;
275 NSTerminateCancel = 0, NSTerminateNow = 1, NSTerminateLater = 2 };
276 typedef NSUInteger NSApplicationTerminateReply;
277 @protocol NSApplicationDelegate <NSObject> @optional - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender;
278 @end @class NSAttributedString, NSEvent, NSFont, NSFormatter, NSImage, NSMenu, NSText, NSView, NSTextView;
279 @interface NSCell : NSObject <NSCopying, NSCoding> {
285 @interface CIImage : NSObject <NSCoding, NSCopying> {
287 typedef int CIFormat;
289 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 };
290 typedef mach_error_t DAReturn;
291 typedef const struct __DADissenter * DADissenterRef;
292 extern DADissenterRef DADissenterCreate( CFAllocatorRef allocator, DAReturn status, CFStringRef string ) CF_RETURNS_RETAINED;
293 @interface CIContext: NSObject {
295 - (CGImageRef)createCGImage:(CIImage *)im fromRect:(CGRect)r CF_RETURNS_RETAINED;
296 - (CGImageRef)createCGImage:(CIImage *)im fromRect:(CGRect)r format:(CIFormat)f colorSpace:(CGColorSpaceRef)cs CF_RETURNS_RETAINED;
297 - (CGLayerRef)createCGLayerWithSize:(CGSize)size info:(CFDictionaryRef)d CF_RETURNS_RETAINED;
298 @end extern NSString* const QCRendererEventKey;
299 @protocol QCCompositionRenderer - (NSDictionary*) attributes;
300 @end @interface QCRenderer : NSObject <QCCompositionRenderer> {
302 - (id) createSnapshotImageOfType:(NSString*)type;
303 @end extern NSString* const QCViewDidStartRenderingNotification;
304 @interface QCView : NSView <QCCompositionRenderer> {
306 - (id) createSnapshotImageOfType:(NSString*)type;
308 ICEXIFOrientation1 = 1, ICEXIFOrientation2 = 2, ICEXIFOrientation3 = 3, ICEXIFOrientation4 = 4, ICEXIFOrientation5 = 5, ICEXIFOrientation6 = 6, ICEXIFOrientation7 = 7, ICEXIFOrientation8 = 8, };
310 @protocol ICDeviceDelegate <NSObject> @required - (void)didRemoveDevice:(ICDevice*)device;
311 @end extern NSString *const ICScannerStatusWarmingUp;
312 @class ICScannerDevice;
313 @protocol ICScannerDeviceDelegate <ICDeviceDelegate> @optional - (void)scannerDeviceDidBecomeAvailable:(ICScannerDevice*)scanner;
316 typedef long unsigned int __darwin_size_t;
317 typedef __darwin_size_t size_t;
318 typedef unsigned long CFTypeID;
323 typedef struct CGPoint CGPoint;
324 typedef struct CGGradient *CGGradientRef;
325 typedef uint32_t CGGradientDrawingOptions;
326 extern CFTypeID CGGradientGetTypeID(void);
327 extern CGGradientRef CGGradientCreateWithColorComponents(CGColorSpaceRef
328 space, const CGFloat components[], const CGFloat locations[], size_t count) CF_RETURNS_RETAINED;
329 extern CGGradientRef CGGradientCreateWithColors(CGColorSpaceRef space,
330 CFArrayRef colors, const CGFloat locations[]) CF_RETURNS_RETAINED;
331 extern CGGradientRef CGGradientRetain(CGGradientRef gradient);
333 CF_IMPLICIT_BRIDGING_ENABLED
335 extern void CGGradientRelease(CGGradientRef gradient);
337 CF_IMPLICIT_BRIDGING_DISABLED
339 typedef struct CGContext *CGContextRef;
340 extern void CGContextDrawLinearGradient(CGContextRef context,
341 CGGradientRef gradient, CGPoint startPoint, CGPoint endPoint,
342 CGGradientDrawingOptions options);
344 CF_IMPLICIT_BRIDGING_ENABLED
346 extern CGColorSpaceRef CGColorSpaceCreateDeviceRGB(void);
348 CF_IMPLICIT_BRIDGING_DISABLED
351 @interface NSMutableArray : NSObject
352 - (void)addObject:(id)object;
353 + (instancetype)array;
356 // This is how NSMakeCollectable is declared in the OS X 10.8 headers.
357 id NSMakeCollectable(CFTypeRef __attribute__((cf_consumed))) __attribute__((ns_returns_retained));
359 typedef const struct __CFUUID * CFUUIDRef;
362 void *CFPlugInInstanceCreate(CFAllocatorRef allocator, CFUUIDRef factoryUUID, CFUUIDRef typeUUID);
364 //===----------------------------------------------------------------------===//
366 //===----------------------------------------------------------------------===//
368 CFAbsoluteTime f1() {
369 CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
370 CFDateRef date = CFDateCreate(0, t);
373 CFDateGetAbsoluteTime(date); // no-warning
375 t = CFDateGetAbsoluteTime(date); // expected-warning{{Reference-counted object is used after it is released}}
379 CFAbsoluteTime f2() {
380 CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
381 CFDateRef date = CFDateCreate(0, t);
382 [((NSDate*) date) retain];
384 CFDateGetAbsoluteTime(date); // no-warning
385 [((NSDate*) date) release];
386 t = CFDateGetAbsoluteTime(date); // expected-warning{{Reference-counted object is used after it is released}}
393 // Test to see if we suppress an error when we store the pointer
396 CFAbsoluteTime f3() {
397 CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
398 CFDateRef date = CFDateCreate(0, t);
399 [((NSDate*) date) retain];
401 CFDateGetAbsoluteTime(date); // no-warning
402 global_x = (NSDate*) date;
403 [((NSDate*) date) release];
404 t = CFDateGetAbsoluteTime(date); // no-warning
408 //---------------------------------------------------------------------------
409 // Test case 'f4' differs for region store and basic store. See
410 // retain-release-region-store.m and retain-release-basic-store.m.
411 //---------------------------------------------------------------------------
415 CFAbsoluteTime f5(int x) {
416 CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
417 CFDateRef date = CFDateCreate(0, t); // expected-warning{{leak}}
425 // Test a leak involving the return.
427 CFDateRef f6(int x) {
428 CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent()); // expected-warning{{leak}}
433 // Test a leak involving an overwrite.
436 CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent()); //expected-warning{{leak}}
438 date = CFDateCreate(0, CFAbsoluteTimeGetCurrent()); // expected-warning {{leak}}
442 // Generalization of Create rule. MyDateCreate returns a CFXXXTypeRef, and
443 // has the word create.
445 CF_IMPLICIT_BRIDGING_ENABLED
447 CFDateRef MyDateCreate();
449 CF_IMPLICIT_BRIDGING_DISABLED
453 CFDateRef date = MyDateCreate(); // expected-warning{{leak}}
458 __attribute__((cf_returns_retained)) CFDateRef f9() {
459 CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent()); // no-warning
461 // When allocations fail, CFDateCreate can return null.
462 if (!date) *p = 1; // expected-warning{{null}}
466 // Handle DiskArbitration API:
468 // http://developer.apple.com/DOCUMENTATION/DARWIN/Reference/DiscArbitrationFramework/
470 void f10(io_service_t media, DADiskRef d, CFStringRef s) {
471 DADiskRef disk = DADiskCreateFromBSDName(kCFAllocatorDefault, 0, "hello"); // expected-warning{{leak}}
472 if (disk) NSLog(@"ok");
474 disk = DADiskCreateFromIOMedia(kCFAllocatorDefault, 0, media); // expected-warning{{leak}}
475 if (disk) NSLog(@"ok");
477 CFDictionaryRef dict = DADiskCopyDescription(d); // expected-warning{{leak}}
478 if (dict) NSLog(@"ok");
480 disk = DADiskCopyWholeDisk(d); // expected-warning{{leak}}
481 if (disk) NSLog(@"ok");
483 DADissenterRef dissenter = DADissenterCreate(kCFAllocatorDefault, // expected-warning{{leak}}
484 kDAReturnSuccess, s);
485 if (dissenter) NSLog(@"ok");
487 DASessionRef session = DASessionCreate(kCFAllocatorDefault); // expected-warning{{leak}}
488 if (session) NSLog(@"ok");
491 // Test retain/release checker with CFString and CFMutableArray.
494 CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
497 CFStringRef s1 = CFStringCreateWithCString(0, "hello world",
498 kCFStringEncodingUTF8);
500 // Add the string to the array.
501 CFArrayAppendValue(A, s1);
503 // Decrement the reference count.
504 CFRelease(s1); // no-warning
506 // Get the string. We don't own it.
507 s1 = (CFStringRef) CFArrayGetValueAtIndex(A, 0);
509 // Release the array.
510 CFRelease(A); // no-warning
512 // Release the string. This is a bug.
513 CFRelease(s1); // expected-warning{{Incorrect decrement of the reference count}}
516 // PR 3337: Handle functions declared using typedefs.
517 typedef CFTypeRef CREATEFUN();
519 CF_IMPLICIT_BRIDGING_ENABLED
521 CFTypeRef MyCreateFun();
523 CF_IMPLICIT_BRIDGING_DISABLED
527 CFTypeRef o = MyCreateFun(); // expected-warning {{leak}}
530 void f13_autorelease() {
531 CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
532 [(id) A autorelease]; // no-warning
535 void f13_autorelease_b() {
536 CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
537 [(id) A autorelease];
538 [(id) A autorelease];
539 } // expected-warning{{Object autoreleased too many times}}
541 CFMutableArrayRef f13_autorelease_c() {
542 CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
543 [(id) A autorelease];
544 [(id) A autorelease];
545 return A; // expected-warning{{Object autoreleased too many times}}
548 CFMutableArrayRef f13_autorelease_d() {
549 CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
550 [(id) A autorelease];
551 [(id) A autorelease];
552 CFMutableArrayRef B = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning{{Object autoreleased too many times}}
553 CFRelease(B); // no-warning
558 // This case exercises the logic where the leak site is the same as the allocation site.
559 void f14_leakimmediately() {
560 CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning{{leak}}
563 // Test that we track an allocated object beyond the point where the *name*
564 // of the variable storing the reference is no longer live.
567 CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
568 CFMutableArrayRef *B = &A;
569 // At this point, the name 'A' is no longer live.
570 CFRelease(*B); // no-warning
573 // Test when we pass NULL to CFRetain/CFRelease/CFMakeCollectable/CFAutorelease.
574 void f16(int x, CFTypeRef p) {
586 CFMakeCollectable(p);
596 // Test that an object is non-null after CFRetain/CFRelease/CFMakeCollectable/CFAutorelease.
597 void f17(int x, CFTypeRef p) {
602 CFRelease(0); // no-warning
607 CFRetain(0); // no-warning
610 CFMakeCollectable(p);
612 CFMakeCollectable(0); // no-warning
617 CFAutorelease(0); // no-warning
624 // Test basic tracking of ivars associated with 'self'. For the retain/release
625 // checker we currently do not want to flag leaks associated with stores
626 // of tracked objects to ivars.
627 @interface SelfIvarTest : NSObject {
630 - (void)test_self_tracking;
633 @implementation SelfIvarTest
634 - (void)test_self_tracking {
635 myObj = (id) CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
639 // Test return of non-owned objects in contexts where an owned object
641 @interface TestReturnNotOwnedWhenExpectedOwned
642 - (NSString*)newString;
645 @implementation TestReturnNotOwnedWhenExpectedOwned
646 - (NSString*)newString {
647 NSString *s = [NSString stringWithUTF8String:"hello"];
648 return s; // expected-warning{{Object with a +0 retain count returned to caller where a +1 (owning) retain count is expected}}
652 // <rdar://problem/6659160>
655 static void rdar_6659160(char *inkind, char *inname)
657 // We currently expect that [NSObject alloc] cannot fail. This
658 // will be a toggled flag in the future. It can indeed return null, but
659 // Cocoa programmers generally aren't expected to reason about out-of-memory
661 NSString *kind = [[NSString alloc] initWithUTF8String:inkind]; // expected-warning{{leak}}
663 // We do allow stringWithUTF8String to fail. This isn't really correct, as
664 // far as returning 0. In most error conditions it will throw an exception.
665 // If allocation fails it could return 0, but again this
667 NSString *name = [NSString stringWithUTF8String:inname];
671 const char *kindC = 0;
672 const char *nameC = 0;
674 // In both cases, we cannot reach a point down below where we
675 // dereference kindC or nameC with either being null. This is because
676 // we assume that [NSObject alloc] doesn't fail and that we have the guard
680 kindC = [kind UTF8String];
682 nameC = [name UTF8String];
683 if(!isFoo(kindC[0])) // expected-warning{{null}}
685 if(!isFoo(nameC[0])) // no-warning
689 [name release]; // expected-warning{{Incorrect decrement of the reference count}}
692 // PR 3677 - 'allocWithZone' should be treated as following the Cocoa naming
693 // conventions with respect to 'return'ing ownership.
694 @interface PR3677: NSObject @end
695 @implementation PR3677
696 + (id)allocWithZone:(NSZone *)inZone {
697 return [super allocWithZone:inZone]; // no-warning
701 // PR 3820 - Reason about calls to -dealloc
702 void pr3820_DeallocInsteadOfRelease(void)
704 id foo = [[NSString alloc] init]; // no-warning
706 // foo is not leaked, since it has been deallocated.
709 void pr3820_ReleaseAfterDealloc(void)
711 id foo = [[NSString alloc] init];
713 [foo release]; // expected-warning{{used after it is release}}
714 // NSInternalInconsistencyException: message sent to deallocated object
717 void pr3820_DeallocAfterRelease(void)
719 NSLog(@"\n\n[%s]", __FUNCTION__);
720 id foo = [[NSString alloc] init];
722 [foo dealloc]; // expected-warning{{used after it is released}}
723 // message sent to released object
726 // From <rdar://problem/6704930>. The problem here is that 'length' binds to
727 // '($0 - 1)' after '--length', but SimpleConstraintManager doesn't know how to
728 // reason about '($0 - 1) > constant'. As a temporary hack, we drop the value
729 // of '($0 - 1)' and conjure a new symbol.
730 void rdar6704930(unsigned char *s, unsigned int length) {
738 name = [[NSString alloc] init]; // no-warning
744 if ((length == 0) && (name != 0)) {
748 if (length == 0) { // no ':' found -> use it all as name
749 name = [[NSString alloc] init]; // no-warning
759 //===----------------------------------------------------------------------===//
760 // <rdar://problem/6833332>
761 // One build of the analyzer accidentally stopped tracking the allocated
762 // object after the 'retain'.
763 //===----------------------------------------------------------------------===//
765 @interface rdar_6833332 : NSObject <NSApplicationDelegate> {
768 @property (nonatomic, retain) NSWindow *window;
771 @implementation rdar_6833332
773 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
774 NSMutableDictionary *dict = [[NSMutableDictionary dictionaryWithCapacity:4] retain]; // expected-warning{{leak}}
776 [dict setObject:@"foo" forKey:@"bar"];
785 - (void)radar10102244 {
786 NSMutableDictionary *dict = [[NSMutableDictionary dictionaryWithCapacity:4] retain]; // expected-warning{{leak}}
788 NSLog(@"%@", window);
792 //===----------------------------------------------------------------------===//
793 // <rdar://problem/6257780> clang checker fails to catch use-after-release
794 //===----------------------------------------------------------------------===//
796 int rdar_6257780_Case1() {
797 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
798 NSArray *array = [NSArray array];
799 [array release]; // expected-warning{{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
804 //===----------------------------------------------------------------------===//
805 // <rdar://problem/10640253> Analyzer is confused about NSAutoreleasePool -allocWithZone:.
806 //===----------------------------------------------------------------------===//
808 void rdar_10640253_autorelease_allocWithZone() {
809 NSAutoreleasePool *pool = [[NSAutoreleasePool allocWithZone:(NSZone*)0] init];
813 //===----------------------------------------------------------------------===//
814 // <rdar://problem/6866843> Checker should understand new/setObject:/release constructs
815 //===----------------------------------------------------------------------===//
817 void rdar_6866843() {
818 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
819 NSMutableDictionary* dictionary = [[NSMutableDictionary alloc] init];
820 NSArray* array = [[NSArray alloc] init];
821 [dictionary setObject:array forKey:@"key"];
823 // Using 'array' here should be fine
824 NSLog(@"array = %@\n", array); // no-warning
825 // Now the array is released
826 [dictionary release];
831 //===----------------------------------------------------------------------===//
832 // <rdar://problem/6877235> Classes typedef-ed to CF objects should get the same treatment as CF objects
833 //===----------------------------------------------------------------------===//
835 typedef CFTypeRef OtherRef;
837 @interface RDar6877235 : NSObject {}
838 - (CFTypeRef)_copyCFTypeRef CF_RETURNS_RETAINED;
839 - (OtherRef)_copyOtherRef CF_RETURNS_RETAINED;
842 @implementation RDar6877235
843 - (CFTypeRef)_copyCFTypeRef {
844 return [[NSString alloc] init]; // no-warning
846 - (OtherRef)_copyOtherRef {
847 return [[NSString alloc] init]; // no-warning
851 //===----------------------------------------------------------------------===//
852 // <rdar://problem/6320065> false positive - init method returns an object
854 //===----------------------------------------------------------------------===//
856 @interface RDar6320065 : NSObject {
859 - (instancetype)initReturningNewClass;
860 - (id)_initReturningNewClassBad;
861 - (instancetype)initReturningNewClassBad2;
864 @interface RDar6320065Subclass : RDar6320065
867 @implementation RDar6320065
868 - (instancetype)initReturningNewClass {
870 self = [[RDar6320065Subclass alloc] init]; // no-warning
873 - (id)_initReturningNewClassBad {
875 [[RDar6320065Subclass alloc] init]; // expected-warning {{leak}}
878 - (instancetype)initReturningNewClassBad2 {
880 self = [[RDar6320065Subclass alloc] init];
881 return [self autorelease]; // expected-warning{{Object with a +0 retain count returned to caller where a +1 (owning) retain count is expected}}
886 @implementation RDar6320065Subclass
889 int RDar6320065_test() {
890 RDar6320065 *test = [[RDar6320065 alloc] init]; // no-warning
895 //===----------------------------------------------------------------------===//
896 // <rdar://problem/7129086> -awakeAfterUsingCoder: returns an owned object
897 // and claims the receiver
898 //===----------------------------------------------------------------------===//
900 @interface RDar7129086 : NSObject {} @end
901 @implementation RDar7129086
902 - (id)awakeAfterUsingCoder:(NSCoder *)aDecoder {
903 [self release]; // no-warning
904 return [NSString alloc]; // no-warning
908 //===----------------------------------------------------------------------===//
909 // <rdar://problem/6859457> [NSData dataWithBytesNoCopy] does not return a
911 //===----------------------------------------------------------------------===//
913 @interface RDar6859457 : NSObject {}
914 - (NSString*) NoCopyString;
915 - (NSString*) noCopyString;
918 @implementation RDar6859457
919 - (NSString*) NoCopyString { return [[NSString alloc] init]; } // expected-warning{{leak}}
920 - (NSString*) noCopyString { return [[NSString alloc] init]; } // expected-warning{{leak}}
923 void test_RDar6859457(RDar6859457 *x, void *bytes, NSUInteger dataLength) {
924 [x NoCopyString]; // expected-warning{{leak}}
925 [x noCopyString]; // expected-warning{{leak}}
926 [NSData dataWithBytesNoCopy:bytes length:dataLength]; // no-warning
927 [NSData dataWithBytesNoCopy:bytes length:dataLength freeWhenDone:1]; // no-warning
930 //===----------------------------------------------------------------------===//
931 // PR 4230 - an autorelease pool is not necessarily leaked during a premature
933 //===----------------------------------------------------------------------===//
935 static void PR4230(void)
937 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // no-warning
938 NSString *object = [[[NSString alloc] init] autorelease]; // no-warning
942 static void PR4230_new(void)
944 NSAutoreleasePool *pool = [NSAutoreleasePool new]; // no-warning
945 NSString *object = [[[NSString alloc] init] autorelease]; // no-warning
949 //===----------------------------------------------------------------------===//
950 // Method name that has a null IdentifierInfo* for its first selector slot.
951 // This test just makes sure that we handle it.
952 //===----------------------------------------------------------------------===//
954 @interface TestNullIdentifier
957 @implementation TestNullIdentifier
959 return [[NSString alloc] init]; // expected-warning{{leak}}
963 //===----------------------------------------------------------------------===//
964 // <rdar://problem/6893565> don't flag leaks for return types that cannot be
965 // determined to be CF types
966 //===----------------------------------------------------------------------===//
968 // We don't know if 'struct s6893565' represents a Core Foundation type, so
969 // we shouldn't emit an error here.
970 typedef struct s6893565* TD6893565;
972 @interface RDar6893565 {}
973 -(TD6893565)newThing;
976 @implementation RDar6893565
977 -(TD6893565)newThing {
978 return (TD6893565) [[NSString alloc] init]; // no-warning
982 //===----------------------------------------------------------------------===//
983 // <rdar://problem/6902710> clang: false positives w/QC and CoreImage methods
984 //===----------------------------------------------------------------------===//
986 void rdar6902710(QCView *view, QCRenderer *renderer, CIContext *context,
987 NSString *str, CIImage *img, CGRect rect,
988 CIFormat form, CGColorSpaceRef cs) {
989 [view createSnapshotImageOfType:str]; // expected-warning{{leak}}
990 [renderer createSnapshotImageOfType:str]; // expected-warning{{leak}}
991 [context createCGImage:img fromRect:rect]; // expected-warning{{leak}}
992 [context createCGImage:img fromRect:rect format:form colorSpace:cs]; // expected-warning{{leak}}
995 //===----------------------------------------------------------------------===//
996 // <rdar://problem/6945561> -[CIContext createCGLayerWithSize:info:]
997 // misinterpreted by clang scan-build
998 //===----------------------------------------------------------------------===//
1000 void rdar6945561(CIContext *context, CGSize size, CFDictionaryRef d) {
1001 [context createCGLayerWithSize:size info:d]; // expected-warning{{leak}}
1004 //===----------------------------------------------------------------------===//
1005 // <rdar://problem/6961230> add knowledge of IOKit functions to retain/release
1007 //===----------------------------------------------------------------------===//
1009 void IOBSDNameMatching_wrapper(mach_port_t masterPort, uint32_t options, const char * bsdName) {
1010 IOBSDNameMatching(masterPort, options, bsdName); // expected-warning{{leak}}
1013 void IOServiceMatching_wrapper(const char * name) {
1014 IOServiceMatching(name); // expected-warning{{leak}}
1017 void IOServiceNameMatching_wrapper(const char * name) {
1018 IOServiceNameMatching(name); // expected-warning{{leak}}
1021 CF_RETURNS_RETAINED CFDictionaryRef CreateDict();
1023 void IOServiceAddNotification_wrapper(mach_port_t masterPort, const io_name_t notificationType,
1024 mach_port_t wakePort, uintptr_t reference, io_iterator_t * notification ) {
1026 CFDictionaryRef matching = CreateDict();
1027 CFRelease(matching);
1028 IOServiceAddNotification(masterPort, notificationType, matching, // expected-warning{{used after it is released}} expected-warning{{deprecated}}
1029 wakePort, reference, notification);
1032 void IORegistryEntryIDMatching_wrapper(uint64_t entryID ) {
1033 IORegistryEntryIDMatching(entryID); // expected-warning{{leak}}
1036 void IOOpenFirmwarePathMatching_wrapper(mach_port_t masterPort, uint32_t options,
1037 const char * path) {
1038 IOOpenFirmwarePathMatching(masterPort, options, path); // expected-warning{{leak}}
1041 void IOServiceGetMatchingService_wrapper(mach_port_t masterPort) {
1042 CFDictionaryRef matching = CreateDict();
1043 IOServiceGetMatchingService(masterPort, matching);
1044 CFRelease(matching); // expected-warning{{used after it is released}}
1047 void IOServiceGetMatchingServices_wrapper(mach_port_t masterPort, io_iterator_t *existing) {
1048 CFDictionaryRef matching = CreateDict();
1049 IOServiceGetMatchingServices(masterPort, matching, existing);
1050 CFRelease(matching); // expected-warning{{used after it is released}}
1053 void IOServiceAddMatchingNotification_wrapper(IONotificationPortRef notifyPort, const io_name_t notificationType,
1054 IOServiceMatchingCallback callback, void * refCon, io_iterator_t * notification) {
1056 CFDictionaryRef matching = CreateDict();
1057 IOServiceAddMatchingNotification(notifyPort, notificationType, matching, callback, refCon, notification);
1058 CFRelease(matching); // expected-warning{{used after it is released}}
1061 //===----------------------------------------------------------------------===//
1062 // Test of handling objects whose references "escape" to containers.
1063 //===----------------------------------------------------------------------===//
1065 void CFDictionaryAddValue(CFMutableDictionaryRef, void *, void *);
1067 // <rdar://problem/6539791>
1068 void rdar_6539791(CFMutableDictionaryRef y, void* key, void* val_key) {
1069 CFMutableDictionaryRef x = CFDictionaryCreateMutable(kCFAllocatorDefault, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
1070 CFDictionaryAddValue(y, key, x);
1071 CFRelease(x); // the dictionary keeps a reference, so the object isn't deallocated yet
1073 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z);
1075 CFDictionaryAddValue(x, val_key, (void*)value); // no-warning
1077 CFDictionaryAddValue(y, val_key, (void*)value); // no-warning
1081 // <rdar://problem/6560661>
1082 // Same issue, except with "AppendValue" functions.
1083 void rdar_6560661(CFMutableArrayRef x) {
1085 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z);
1086 // CFArrayAppendValue keeps a reference to value.
1087 CFArrayAppendValue(x, value);
1090 CFRelease(value); // no-warning
1093 // <rdar://problem/7152619>
1094 // Same issue, excwept with "CFAttributeStringSetAttribute".
1095 void rdar_7152619(CFStringRef str) {
1096 CFAttributedStringRef string = CFAttributedStringCreate(kCFAllocatorDefault, str, 0);
1097 CFMutableAttributedStringRef attrString = CFAttributedStringCreateMutableCopy(kCFAllocatorDefault, 100, string);
1099 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1100 CFAttributedStringSetAttribute(attrString, CFRangeMake(0, 1), str, number);
1103 CFRelease(attrString);
1106 //===----------------------------------------------------------------------===//
1107 // Test of handling CGGradientXXX functions.
1108 //===----------------------------------------------------------------------===//
1110 void rdar_7184450(CGContextRef myContext, CGFloat x, CGPoint myStartPoint,
1111 CGPoint myEndPoint) {
1112 size_t num_locations = 6;
1113 CGFloat locations[6] = { 0.0, 0.265, 0.28, 0.31, 0.36, 1.0 };
1114 CGFloat components[28] = { 239.0/256.0, 167.0/256.0, 170.0/256.0,
1116 207.0/255.0, 39.0/255.0, 39.0/255.0, x,
1117 147.0/255.0, 21.0/255.0, 22.0/255.0, x,
1118 175.0/255.0, 175.0/255.0, 175.0/255.0, x,
1119 255.0/255.0,255.0/255.0, 255.0/255.0, x,
1120 255.0/255.0,255.0/255.0, 255.0/255.0, x
1123 CGGradientRef myGradient =
1124 CGGradientCreateWithColorComponents(CGColorSpaceCreateDeviceRGB(), // expected-warning{{leak}}
1125 components, locations, num_locations);
1127 CGContextDrawLinearGradient(myContext, myGradient, myStartPoint, myEndPoint,
1129 CGGradientRelease(myGradient);
1132 void rdar_7184450_pos(CGContextRef myContext, CGFloat x, CGPoint myStartPoint,
1133 CGPoint myEndPoint) {
1134 size_t num_locations = 6;
1135 CGFloat locations[6] = { 0.0, 0.265, 0.28, 0.31, 0.36, 1.0 };
1136 CGFloat components[28] = { 239.0/256.0, 167.0/256.0, 170.0/256.0,
1138 207.0/255.0, 39.0/255.0, 39.0/255.0, x,
1139 147.0/255.0, 21.0/255.0, 22.0/255.0, x,
1140 175.0/255.0, 175.0/255.0, 175.0/255.0, x,
1141 255.0/255.0,255.0/255.0, 255.0/255.0, x,
1142 255.0/255.0,255.0/255.0, 255.0/255.0, x
1145 CGGradientRef myGradient =
1146 CGGradientCreateWithColorComponents(CGColorSpaceCreateDeviceRGB(), components, locations, num_locations); // expected-warning 2 {{leak}}
1148 CGContextDrawLinearGradient(myContext, myGradient, myStartPoint, myEndPoint,
1152 //===----------------------------------------------------------------------===//
1153 // <rdar://problem/7299394> clang false positive: retained instance passed to
1154 // thread in pthread_create marked as leak
1156 // Until we have full IPA, the analyzer should stop tracking the reference
1157 // count of objects passed to pthread_create.
1159 //===----------------------------------------------------------------------===//
1161 struct _opaque_pthread_t {};
1162 struct _opaque_pthread_attr_t {};
1163 typedef struct _opaque_pthread_t *__darwin_pthread_t;
1164 typedef struct _opaque_pthread_attr_t __darwin_pthread_attr_t;
1165 typedef __darwin_pthread_t pthread_t;
1166 typedef __darwin_pthread_attr_t pthread_attr_t;
1167 typedef unsigned long __darwin_pthread_key_t;
1168 typedef __darwin_pthread_key_t pthread_key_t;
1170 int pthread_create(pthread_t *, const pthread_attr_t *,
1171 void *(*)(void *), void *);
1173 int pthread_setspecific(pthread_key_t key, const void *value);
1175 void *rdar_7299394_start_routine(void *p) {
1179 void rdar_7299394(pthread_attr_t *attr, pthread_t *thread, void *args) {
1180 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1181 pthread_create(thread, attr, rdar_7299394_start_routine, number);
1183 void rdar_7299394_positive(pthread_attr_t *attr, pthread_t *thread) {
1184 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1187 //===----------------------------------------------------------------------===//
1188 // <rdar://problem/11282706> false positive with not understanding thread
1190 //===----------------------------------------------------------------------===//
1192 void rdar11282706(pthread_key_t key) {
1193 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1194 pthread_setspecific(key, (void*) number);
1197 //===----------------------------------------------------------------------===//
1198 // <rdar://problem/7283567> False leak associated with call to
1199 // CVPixelBufferCreateWithBytes ()
1201 // According to the Core Video Reference (ADC), CVPixelBufferCreateWithBytes and
1202 // CVPixelBufferCreateWithPlanarBytes can release (via a callback) the
1203 // pixel buffer object. These test cases show how the analyzer stops tracking
1204 // the reference count for the objects passed for this argument. This
1205 // could be made smarter.
1206 //===----------------------------------------------------------------------===//
1208 typedef int int32_t;
1209 typedef UInt32 FourCharCode;
1210 typedef FourCharCode OSType;
1211 typedef uint64_t CVOptionFlags;
1212 typedef int32_t CVReturn;
1213 typedef struct __CVBuffer *CVBufferRef;
1214 typedef CVBufferRef CVImageBufferRef;
1215 typedef CVImageBufferRef CVPixelBufferRef;
1216 typedef void (*CVPixelBufferReleaseBytesCallback)( void *releaseRefCon, const void *baseAddress );
1218 extern CVReturn CVPixelBufferCreateWithBytes(CFAllocatorRef allocator,
1221 OSType pixelFormatType,
1224 CVPixelBufferReleaseBytesCallback releaseCallback,
1225 void *releaseRefCon,
1226 CFDictionaryRef pixelBufferAttributes,
1227 CVPixelBufferRef *pixelBufferOut) ;
1229 typedef void (*CVPixelBufferReleasePlanarBytesCallback)( void *releaseRefCon, const void *dataPtr, size_t dataSize, size_t numberOfPlanes, const void *planeAddresses[] );
1231 extern CVReturn CVPixelBufferCreateWithPlanarBytes(CFAllocatorRef allocator,
1234 OSType pixelFormatType,
1237 size_t numberOfPlanes,
1238 void *planeBaseAddress[],
1239 size_t planeWidth[],
1240 size_t planeHeight[],
1241 size_t planeBytesPerRow[],
1242 CVPixelBufferReleasePlanarBytesCallback releaseCallback,
1243 void *releaseRefCon,
1244 CFDictionaryRef pixelBufferAttributes,
1245 CVPixelBufferRef *pixelBufferOut) ;
1247 extern CVReturn CVPixelBufferCreateWithBytes(CFAllocatorRef allocator,
1250 OSType pixelFormatType,
1253 CVPixelBufferReleaseBytesCallback releaseCallback,
1254 void *releaseRefCon,
1255 CFDictionaryRef pixelBufferAttributes,
1256 CVPixelBufferRef *pixelBufferOut) ;
1258 CVReturn rdar_7283567(CFAllocatorRef allocator, size_t width, size_t height,
1259 OSType pixelFormatType, void *baseAddress,
1261 CVPixelBufferReleaseBytesCallback releaseCallback,
1262 CFDictionaryRef pixelBufferAttributes,
1263 CVPixelBufferRef *pixelBufferOut) {
1265 // For the allocated object, it doesn't really matter what type it is
1266 // for the purpose of this test. All we want to show is that
1267 // this is freed later by the callback.
1268 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1270 return CVPixelBufferCreateWithBytes(allocator, width, height, pixelFormatType,
1271 baseAddress, bytesPerRow, releaseCallback,
1272 number, // potentially released by callback
1273 pixelBufferAttributes, pixelBufferOut) ;
1276 CVReturn rdar_7283567_2(CFAllocatorRef allocator, size_t width, size_t height,
1277 OSType pixelFormatType, void *dataPtr, size_t dataSize,
1278 size_t numberOfPlanes, void *planeBaseAddress[],
1279 size_t planeWidth[], size_t planeHeight[], size_t planeBytesPerRow[],
1280 CVPixelBufferReleasePlanarBytesCallback releaseCallback,
1281 CFDictionaryRef pixelBufferAttributes,
1282 CVPixelBufferRef *pixelBufferOut) {
1284 // For the allocated object, it doesn't really matter what type it is
1285 // for the purpose of this test. All we want to show is that
1286 // this is freed later by the callback.
1287 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1289 return CVPixelBufferCreateWithPlanarBytes(allocator,
1290 width, height, pixelFormatType, dataPtr, dataSize,
1291 numberOfPlanes, planeBaseAddress, planeWidth,
1292 planeHeight, planeBytesPerRow, releaseCallback,
1293 number, // potentially released by callback
1294 pixelBufferAttributes, pixelBufferOut) ;
1297 //===----------------------------------------------------------------------===//
1298 // <rdar://problem/7358899> False leak associated with
1299 // CGBitmapContextCreateWithData
1300 //===----------------------------------------------------------------------===//
1301 typedef uint32_t CGBitmapInfo;
1302 typedef void (*CGBitmapContextReleaseDataCallback)(void *releaseInfo, void *data);
1304 CGContextRef CGBitmapContextCreateWithData(void *data,
1305 size_t width, size_t height, size_t bitsPerComponent,
1306 size_t bytesPerRow, CGColorSpaceRef space, CGBitmapInfo bitmapInfo,
1307 CGBitmapContextReleaseDataCallback releaseCallback, void *releaseInfo) CF_RETURNS_RETAINED;
1309 void rdar_7358899(void *data,
1310 size_t width, size_t height, size_t bitsPerComponent,
1311 size_t bytesPerRow, CGColorSpaceRef space, CGBitmapInfo bitmapInfo,
1312 CGBitmapContextReleaseDataCallback releaseCallback) {
1314 // For the allocated object, it doesn't really matter what type it is
1315 // for the purpose of this test. All we want to show is that
1316 // this is freed later by the callback.
1317 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1319 CGBitmapContextCreateWithData(data, width, height, bitsPerComponent, // expected-warning{{leak}}
1320 bytesPerRow, space, bitmapInfo, releaseCallback, number);
1323 //===----------------------------------------------------------------------===//
1324 // <rdar://problem/7265711> allow 'new', 'copy', 'alloc', 'init' prefix to
1325 // start before '_' when determining Cocoa fundamental rule
1327 // Previously the retain/release checker just skipped prefixes before the
1328 // first '_' entirely. Now the checker honors the prefix if it results in a
1329 // recognizable naming convention (e.g., 'new', 'init').
1330 //===----------------------------------------------------------------------===//
1332 @interface RDar7265711 {}
1336 void rdar7265711_a(RDar7265711 *x) {
1337 id y = [x new_stuff]; // expected-warning{{leak}}
1340 void rdar7265711_b(RDar7265711 *x) {
1341 id y = [x new_stuff]; // no-warning
1345 //===----------------------------------------------------------------------===//
1346 // <rdar://problem/7306898> clang thinks [NSCursor dragCopyCursor] returns a
1347 // retained reference
1348 //===----------------------------------------------------------------------===//
1350 @interface NSCursor : NSObject
1351 + (NSCursor *)dragCopyCursor;
1354 void rdar7306898(void) {
1355 // 'dragCopyCursor' does not follow Cocoa's fundamental rule. It is a noun, not an sentence
1356 // implying a 'copy' of something.
1357 NSCursor *c = [NSCursor dragCopyCursor]; // no-warning
1358 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1361 //===----------------------------------------------------------------------===//
1362 // <rdar://problem/7252064> sending 'release', 'retain', etc. to a Class
1363 // directly is not likely what the user intended
1364 //===----------------------------------------------------------------------===//
1366 @interface RDar7252064 : NSObject @end
1367 void rdar7252064(void) {
1368 [RDar7252064 release]; // expected-warning{{The 'release' message should be sent to instances of class 'RDar7252064' and not the class directly}}
1369 [RDar7252064 retain]; // expected-warning{{The 'retain' message should be sent to instances of class 'RDar7252064' and not the class directly}}
1370 [RDar7252064 autorelease]; // expected-warning{{The 'autorelease' message should be sent to instances of class 'RDar7252064' and not the class directly}}
1371 [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}}
1374 //===----------------------------------------------------------------------===//
1375 // Tests of ownership attributes.
1376 //===----------------------------------------------------------------------===//
1378 typedef NSString* MyStringTy;
1382 @interface TestOwnershipAttr : NSObject
1383 - (NSString*) returnsAnOwnedString NS_RETURNS_RETAINED; // no-warning
1384 - (NSString*) returnsAnOwnedCFString CF_RETURNS_RETAINED; // no-warning
1385 - (MyStringTy) returnsAnOwnedTypedString NS_RETURNS_RETAINED; // no-warning
1386 - (NSString*) newString NS_RETURNS_NOT_RETAINED; // no-warning
1387 - (NSString*) newString_auto NS_RETURNS_AUTORELEASED; // no-warning
1388 - (NSString*) newStringNoAttr;
1389 - (int) returnsAnOwnedInt NS_RETURNS_RETAINED; // expected-warning{{'ns_returns_retained' attribute only applies to methods that return an Objective-C object}}
1390 - (id) pseudoInit NS_CONSUMES_SELF NS_RETURNS_RETAINED;
1391 + (void) consume:(id) NS_CONSUMED x;
1392 + (void) consume2:(id) CF_CONSUMED x;
1395 static int ownership_attribute_doesnt_go_here NS_RETURNS_RETAINED; // expected-warning{{'ns_returns_retained' attribute only applies to functions and methods}}
1397 void test_attr_1(TestOwnershipAttr *X) {
1398 NSString *str = [X returnsAnOwnedString]; // expected-warning{{leak}}
1401 void test_attr_1b(TestOwnershipAttr *X) {
1402 NSString *str = [X returnsAnOwnedCFString]; // expected-warning{{leak}}
1405 void test_attr1c(TestOwnershipAttr *X) {
1406 NSString *str = [X newString]; // no-warning
1407 NSString *str2 = [X newStringNoAttr]; // expected-warning{{leak}}
1408 NSString *str3 = [X newString_auto]; // no-warning
1409 NSString *str4 = [[X newString_auto] retain]; // expected-warning {{leak}}
1412 void testattr2_a() {
1413 TestOwnershipAttr *x = [TestOwnershipAttr alloc]; // expected-warning{{leak}}
1416 void testattr2_b() {
1417 TestOwnershipAttr *x = [[TestOwnershipAttr alloc] pseudoInit]; // expected-warning{{leak}}
1420 void testattr2_b_11358224_self_assign_looses_the_leak() {
1421 TestOwnershipAttr *x = [[TestOwnershipAttr alloc] pseudoInit];// expected-warning{{leak}}
1425 void testattr2_c() {
1426 TestOwnershipAttr *x = [[TestOwnershipAttr alloc] pseudoInit]; // no-warning
1431 TestOwnershipAttr *x = [TestOwnershipAttr alloc]; // no-warning
1432 [TestOwnershipAttr consume:x];
1433 TestOwnershipAttr *y = [TestOwnershipAttr alloc]; // no-warning
1434 [TestOwnershipAttr consume2:y];
1437 void consume_ns(id NS_CONSUMED x);
1438 void consume_cf(id CF_CONSUMED x);
1441 TestOwnershipAttr *x = [TestOwnershipAttr alloc]; // no-warning
1443 TestOwnershipAttr *y = [TestOwnershipAttr alloc]; // no-warning
1447 @interface TestOwnershipAttr2 : NSObject
1448 - (NSString*) newString NS_RETURNS_NOT_RETAINED; // no-warning
1451 @implementation TestOwnershipAttr2
1452 - (NSString*) newString {
1453 return [NSString alloc]; // expected-warning {{Potential leak of an object}}
1457 @interface MyClassTestCFAttr : NSObject {}
1458 - (NSDate*) returnsCFRetained CF_RETURNS_RETAINED;
1459 - (CFDateRef) returnsCFRetainedAsCF CF_RETURNS_RETAINED;
1460 - (CFDateRef) newCFRetainedAsCF CF_RETURNS_NOT_RETAINED;
1461 - (CFDateRef) newCFRetainedAsCFNoAttr CF_RETURNS_RETAINED;
1462 - (NSDate*) alsoReturnsRetained;
1463 - (CFDateRef) alsoReturnsRetainedAsCF CF_RETURNS_NOT_RETAINED;
1464 - (NSDate*) returnsNSRetained NS_RETURNS_RETAINED;
1468 CFDateRef returnsRetainedCFDate() {
1469 return CFDateCreate(0, CFAbsoluteTimeGetCurrent());
1472 @implementation MyClassTestCFAttr
1473 - (NSDate*) returnsCFRetained {
1474 return (NSDate*) returnsRetainedCFDate(); // No leak.
1477 - (CFDateRef) returnsCFRetainedAsCF {
1478 return returnsRetainedCFDate(); // No leak.
1481 - (CFDateRef) newCFRetainedAsCF {
1482 return (CFDateRef)[(id)[self returnsCFRetainedAsCF] autorelease];
1485 - (CFDateRef) newCFRetainedAsCFNoAttr {
1486 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}}
1489 - (NSDate*) alsoReturnsRetained {
1490 return (NSDate*) returnsRetainedCFDate(); // expected-warning{{leak}}
1493 - (CFDateRef) alsoReturnsRetainedAsCF {
1494 return returnsRetainedCFDate(); // expected-warning{{leak}}
1498 - (NSDate*) returnsNSRetained {
1499 return (NSDate*) returnsRetainedCFDate(); // no-warning
1503 //===----------------------------------------------------------------------===//
1504 // Test that leaks post-dominated by "panic" functions are not reported.
1506 // <rdar://problem/5905851> do not report a leak when post-dominated by a call
1507 // to a noreturn or panic function
1508 //===----------------------------------------------------------------------===//
1510 void panic() __attribute__((noreturn));
1511 void panic_not_in_hardcoded_list() __attribute__((noreturn));
1513 void test_panic_negative() {
1515 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // expected-warning{{leak}}
1518 void test_panic_positive() {
1520 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // no-warning
1524 void test_panic_neg_2(int x) {
1526 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // expected-warning{{leak}}
1531 void test_panic_pos_2(int x) {
1533 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // no-warning
1537 // This showed up in <rdar://problem/7796563>, where we silently missed checking
1538 // the function type for noreturn. "panic()" is a hard-coded known panic function
1539 // that isn't always noreturn.
1540 panic_not_in_hardcoded_list();
1544 //===----------------------------------------------------------------------===//
1545 // Test uses of blocks (closures)
1546 //===----------------------------------------------------------------------===//
1548 void test_blocks_1_pos(void) {
1549 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1553 void test_blocks_1_indirect_release(void) {
1554 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1555 ^{ [number release]; }();
1558 void test_blocks_1_indirect_retain(void) {
1559 // Eventually this should be reported as a leak.
1560 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1561 ^{ [number retain]; }();
1564 void test_blocks_1_indirect_release_via_call(void) {
1565 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1566 ^(NSObject *o){ [o release]; }(number);
1569 void test_blocks_1_indirect_retain_via_call(void) {
1570 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning {{leak}}
1571 ^(NSObject *o){ [o retain]; }(number);
1574 //===--------------------------------------------------------------------===//
1575 // Test sending message to super that returns an object alias. Previously
1576 // this caused a crash in the analyzer.
1577 //===--------------------------------------------------------------------===//
1579 @interface Rdar8015556 : NSObject {} @end
1580 @implementation Rdar8015556
1582 return [super retain];
1586 // <rdar://problem/8272168> - Correcly handle Class<...> in Cocoa Conventions
1589 @protocol Prot_R8272168 @end
1590 Class <Prot_R8272168> GetAClassThatImplementsProt_R8272168();
1592 GetAClassThatImplementsProt_R8272168();
1595 // Test case for <rdar://problem/8356342>, which in the past triggered
1596 // a false positive.
1597 @interface RDar8356342
1598 - (NSDate*) rdar8356342:(NSDate *)inValue;
1601 @implementation RDar8356342
1602 - (NSDate*) rdar8356342:(NSDate*)inValue {
1603 NSDate *outValue = inValue;
1605 outValue = [[NSDate alloc] init]; // no-warning
1607 if (outValue != inValue)
1608 [outValue autorelease];
1614 // <rdar://problem/8724287> - This test case previously crashed because
1615 // of a bug in BugReporter.
1616 extern const void *CFDictionaryGetValue(CFDictionaryRef theDict, const void *key) CF_RETURNS_NOT_RETAINED;
1617 typedef struct __CFError * CFErrorRef;
1618 extern const CFStringRef kCFErrorUnderlyingErrorKey;
1619 extern CFDictionaryRef CFErrorCopyUserInfo(CFErrorRef err) CF_RETURNS_RETAINED;
1620 static void rdar_8724287(CFErrorRef error)
1622 CFErrorRef error_to_dump;
1624 error_to_dump = error;
1625 while (error_to_dump != ((void*)0)) {
1626 CFDictionaryRef info;
1628 info = CFErrorCopyUserInfo(error_to_dump); // expected-warning{{Potential leak of an object}}
1630 if (info != ((void*)0)) {
1633 error_to_dump = (CFErrorRef) CFDictionaryGetValue(info, kCFErrorUnderlyingErrorKey);
1637 // <rdar://problem/9234108> - Make sure the model applies cf_consumed
1638 // correctly in argument positions besides the first.
1640 CF_IMPLICIT_BRIDGING_ENABLED
1642 extern void *CFStringCreate(void);
1644 CF_IMPLICIT_BRIDGING_DISABLED
1646 extern void rdar_9234108_helper(void *key, void * CF_CONSUMED value);
1647 void rdar_9234108() {
1648 rdar_9234108_helper(0, CFStringCreate());
1651 // <rdar://problem/9726279> - Make sure that objc_method_family works
1652 // to override naming conventions.
1657 typedef struct TwoDoubles TwoDoubles;
1659 @interface NSValue (Mine)
1660 - (id)_prefix_initWithTwoDoubles:(TwoDoubles)twoDoubles __attribute__((objc_method_family(init)));
1663 @implementation NSValue (Mine)
1664 - (id)_prefix_initWithTwoDoubles:(TwoDoubles)twoDoubles
1670 void rdar9726279() {
1671 TwoDoubles twoDoubles = { 0.0, 0.0 };
1672 NSValue *value = [[NSValue alloc] _prefix_initWithTwoDoubles:twoDoubles];
1676 // <rdar://problem/9732321>
1677 // Test camelcase support for CF conventions. While Core Foundation APIs
1678 // don't use camel casing, other code is allowed to use it.
1679 CFArrayRef camelcase_create_1() {
1680 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1683 CFArrayRef camelcase_createno() {
1684 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1687 CFArrayRef camelcase_copy() {
1688 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1691 CFArrayRef camelcase_copying() {
1692 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1695 CFArrayRef copyCamelCase() {
1696 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1699 CFArrayRef __copyCamelCase() {
1700 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1703 CFArrayRef __createCamelCase() {
1704 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1707 CFArrayRef camel_create() {
1708 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1712 CFArrayRef camel_creat() {
1713 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1716 CFArrayRef camel_copy() {
1717 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1720 CFArrayRef camel_copyMachine() {
1721 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1724 CFArrayRef camel_copymachine() {
1725 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1728 // rdar://problem/8024350
1732 @interface F18 : NSObject<F18P> @end
1734 - (id) clone NS_RETURNS_RETAINED;
1744 void rdar6582778(void) {
1745 CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
1746 CFTypeRef vals[] = { CFDateCreate(0, t) }; // expected-warning {{leak}}
1751 void rdar6582778_2(void) {
1752 CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
1753 global = CFDateCreate(0, t); // no-warning
1756 // <rdar://problem/10232019> - Test that objects passed to containers
1757 // are marked "escaped".
1759 void rdar10232019() {
1760 NSMutableArray *array = [NSMutableArray array];
1762 NSString *string = [[NSString alloc] initWithUTF8String:"foo"];
1763 [array addObject:string];
1766 NSString *otherString = [string stringByAppendingString:@"bar"]; // no-warning
1767 NSLog(@"%@", otherString);
1770 void rdar10232019_positive() {
1771 NSMutableArray *array = [NSMutableArray array];
1773 NSString *string = [[NSString alloc] initWithUTF8String:"foo"];
1776 NSString *otherString = [string stringByAppendingString:@"bar"]; // expected-warning {{Reference-counted object is used after it is release}}
1777 NSLog(@"%@", otherString);
1780 // RetainCountChecker support for XPC.
1781 // <rdar://problem/9658496>
1782 typedef void * xpc_object_t;
1783 xpc_object_t _CFXPCCreateXPCObjectFromCFObject(CFTypeRef cf);
1784 void xpc_release(xpc_object_t object);
1786 void rdar9658496() {
1789 cf = CFStringCreateWithCString( ((CFAllocatorRef)0), "test", kCFStringEncodingUTF8 ); // no-warning
1790 xpc = _CFXPCCreateXPCObjectFromCFObject( cf );
1795 // Support annotations with method families.
1796 @interface RDar10824732 : NSObject
1797 - (instancetype)initWithObj:(id CF_CONSUMED)obj;
1800 @implementation RDar10824732
1801 - (instancetype)initWithObj:(id)obj {
1803 return [super init];
1807 void rdar_10824732() {
1809 NSString *obj = @"test";
1810 RDar10824732 *foo = [[RDar10824732 alloc] initWithObj:obj]; // no-warning
1815 // Stop tracking objects passed to functions, which take callbacks as parameters.
1817 typedef int (*CloseCallback) (void *);
1818 void ReaderForIO(CloseCallback ioclose, void *ioctx);
1819 int IOClose(void *context);
1821 @protocol SInS <NSObject>
1824 @interface radar10973977 : NSObject
1829 @implementation radar10973977
1832 id<SInS> inputS = [[self inputS] retain];
1833 ReaderForIO(IOClose, inputS);
1841 // Object escapes through a selector callback: radar://11398514
1843 @interface MySheetController
1845 - (void)showDoSomethingSheetAction:(id)action;
1846 - (void)sheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo;
1849 @implementation MySheetController
1850 - (id<SInS>)inputS {
1853 - (void)showDoSomethingSheetAction:(id)action {
1854 id<SInS> inputS = [[self inputS] retain];
1858 didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:)
1859 contextInfo:(void *)inputS]; // no - warning
1861 - (void)sheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo {
1863 id contextObject = (id)contextInfo;
1864 [contextObject release];
1867 - (id)copyAutoreleaseRadar13081402 {
1868 id x = [[[NSString alloc] initWithUTF8String:"foo"] autorelease];
1870 return x; // no warning
1874 //===----------------------------------------------------------------------===//
1875 // Test returning allocated memory in a struct.
1877 // We currently don't have a general way to track pointers that "escape".
1878 // Here we test that RetainCountChecker doesn't get excited about returning
1879 // allocated CF objects in struct fields.
1880 //===----------------------------------------------------------------------===//
1881 void *malloc(size_t);
1882 struct rdar11104566 { CFStringRef myStr; };
1883 struct rdar11104566 test_rdar11104566() {
1884 CFStringRef cf = CFStringCreateWithCString( ((CFAllocatorRef)0), "test", kCFStringEncodingUTF8 ); // no-warning
1885 struct rdar11104566 V;
1887 return V; // no-warning
1890 struct rdar11104566 *test_2_rdar11104566() {
1891 CFStringRef cf = CFStringCreateWithCString( ((CFAllocatorRef)0), "test", kCFStringEncodingUTF8 ); // no-warning
1892 struct rdar11104566 *V = (struct rdar11104566 *) malloc(sizeof(*V));
1894 return V; // no-warning
1897 //===----------------------------------------------------------------------===//
1898 // ObjC literals support.
1899 //===----------------------------------------------------------------------===//
1901 void test_objc_arrays() {
1902 { // CASE ONE -- OBJECT IN ARRAY CREATED DIRECTLY
1903 NSObject *o = [[NSObject alloc] init];
1904 NSArray *a = [[NSArray alloc] initWithObjects:o, (void*)0]; // expected-warning {{leak}}
1910 { // CASE TWO -- OBJECT IN ARRAY CREATED BY DUPING AUTORELEASED ARRAY
1911 NSObject *o = [[NSObject alloc] init];
1912 NSArray *a1 = [NSArray arrayWithObjects:o, (void*)0];
1913 NSArray *a2 = [[NSArray alloc] initWithArray:a1]; // expected-warning {{leak}}
1919 { // CASE THREE -- OBJECT IN RETAINED @[]
1920 NSObject *o = [[NSObject alloc] init];
1921 NSArray *a3 = [@[o] retain]; // expected-warning {{leak}}
1927 { // CASE FOUR -- OBJECT IN ARRAY CREATED BY DUPING @[]
1928 NSObject *o = [[NSObject alloc] init];
1929 NSArray *a = [[NSArray alloc] initWithArray:@[o]]; // expected-warning {{leak}}
1936 { // CASE FIVE -- OBJECT IN RETAINED @{}
1937 NSValue *o = [[NSValue alloc] init];
1938 NSDictionary *a = [@{o : o} retain]; // expected-warning {{leak}}
1946 void test_objc_integer_literals() {
1947 id value = [@1 retain]; // expected-warning {{leak}}
1948 [value description];
1951 void test_objc_boxed_expressions(int x, const char *y) {
1952 id value = [@(x) retain]; // expected-warning {{leak}}
1953 [value description];
1955 value = [@(y) retain]; // expected-warning {{leak}}
1956 [value description];
1959 // Test NSLog doesn't escape tracked objects.
1960 void rdar11400885(int y)
1963 NSString *printString;
1965 printString = [[NSString alloc] init];
1967 printString = [[NSString alloc] init];
1968 NSLog(@"Once %@", printString);
1969 [printString release];
1970 NSLog(@"Again: %@", printString); // expected-warning {{Reference-counted object is used after it is released}}
1974 id makeCollectableNonLeak() {
1975 extern CFTypeRef CFCreateSomething();
1977 CFTypeRef object = CFCreateSomething(); // +1
1978 CFRetain(object); // +2
1979 id objCObject = NSMakeCollectable(object); // +2
1980 [objCObject release]; // +1
1981 return [objCObject autorelease]; // +0
1985 void consumeAndStopTracking(id NS_CONSUMED obj, void (^callback)(void));
1986 void CFConsumeAndStopTracking(CFTypeRef CF_CONSUMED obj, void (^callback)(void));
1988 void testConsumeAndStopTracking() {
1989 id retained = [@[] retain]; // +1
1990 consumeAndStopTracking(retained, ^{}); // no-warning
1992 id doubleRetained = [[@[] retain] retain]; // +2
1993 consumeAndStopTracking(doubleRetained, ^{
1994 [doubleRetained release];
1997 id unretained = @[]; // +0
1998 consumeAndStopTracking(unretained, ^{}); // expected-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
2001 void testCFConsumeAndStopTracking() {
2002 id retained = [@[] retain]; // +1
2003 CFConsumeAndStopTracking((CFTypeRef)retained, ^{}); // no-warning
2005 id doubleRetained = [[@[] retain] retain]; // +2
2006 CFConsumeAndStopTracking((CFTypeRef)doubleRetained, ^{
2007 [doubleRetained release];
2010 id unretained = @[]; // +0
2011 CFConsumeAndStopTracking((CFTypeRef)unretained, ^{}); // expected-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
2013 //===----------------------------------------------------------------------===//
2014 // Test 'pragma clang arc_cf_code_audited' support.
2015 //===----------------------------------------------------------------------===//
2017 typedef void *MyCFType;
2018 #pragma clang arc_cf_code_audited begin
2019 MyCFType CreateMyCFType();
2020 #pragma clang arc_cf_code_audited end
2022 void test_custom_cf() {
2023 MyCFType x = CreateMyCFType(); // expected-warning {{leak of an object stored into 'x'}}
2026 //===----------------------------------------------------------------------===//
2027 // Test calling CFPlugInInstanceCreate, which appears in CF but doesn't
2028 // return a CF object.
2029 //===----------------------------------------------------------------------===//
2031 void test_CFPlugInInstanceCreate(CFUUIDRef factoryUUID, CFUUIDRef typeUUID) {
2032 CFPlugInInstanceCreate(kCFAllocatorDefault, factoryUUID, typeUUID); // no-warning
2035 //===----------------------------------------------------------------------===//
2036 // PR14927: -drain only has retain-count semantics on NSAutoreleasePool.
2037 //===----------------------------------------------------------------------===//
2039 @interface PR14927 : NSObject
2044 PR14927 *obj = [[PR14927 alloc] init];
2046 [obj release]; // no-warning
2049 //===----------------------------------------------------------------------===//
2050 // Allow cf_returns_retained and cf_returns_not_retained to mark a return
2051 // value as tracked, even if the object isn't a known CF type.
2052 //===----------------------------------------------------------------------===//
2054 MyCFType getCustom() __attribute__((cf_returns_not_retained));
2055 MyCFType makeCustom() __attribute__((cf_returns_retained));
2057 void testCustomReturnsRetained() {
2058 MyCFType obj = makeCustom(); // expected-warning {{leak of an object stored into 'obj'}}
2061 void testCustomReturnsNotRetained() {
2062 CFRelease(getCustom()); // expected-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
2065 //===----------------------------------------------------------------------===//
2066 // Don't print variables which are out of the current scope.
2067 //===----------------------------------------------------------------------===//
2068 @interface MyObj12706177 : NSObject
2069 -(instancetype)initX;
2070 +(void)test12706177;
2073 @implementation MyObj12706177
2074 -(instancetype)initX {
2077 self = [super init];
2080 +(void)test12706177 {
2081 id x = [[MyObj12706177 alloc] initX]; //expected-warning {{Potential leak of an object}}
2086 //===----------------------------------------------------------------------===//
2087 // <rdar://problem/13783514> xpc_connection_set_finalizer_f
2088 //===----------------------------------------------------------------------===//
2090 typedef xpc_object_t xpc_connection_t;
2091 typedef void (*xpc_finalizer_t)(void *value);
2092 void xpc_connection_set_context(xpc_connection_t connection, void *ctx);
2093 void xpc_connection_set_finalizer_f(xpc_connection_t connection,
2094 xpc_finalizer_t finalizer);
2095 void releaseAfterXPC(void *context) {
2096 [(NSArray *)context release];
2099 void rdar13783514(xpc_connection_t connection) {
2100 xpc_connection_set_context(connection, [[NSMutableArray alloc] init]);
2101 xpc_connection_set_finalizer_f(connection, releaseAfterXPC);
2104 CFAttributedStringRef CFAttributedCreate(void *CFObj CF_CONSUMED) CF_RETURNS_RETAINED;
2107 @property (nonatomic) SEL action;
2108 @property (nonatomic, assign) id target;