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 CFAutorelease(CFTypeRef cf);
90 extern CFTypeRef CFMakeCollectable(CFTypeRef cf);
94 extern const CFArrayCallBacks kCFTypeArrayCallBacks;
95 typedef const struct __CFArray * CFArrayRef;
96 typedef struct __CFArray * CFMutableArrayRef;
97 extern CFMutableArrayRef CFArrayCreateMutable(CFAllocatorRef allocator, CFIndex capacity, const CFArrayCallBacks *callBacks) CF_RETURNS_RETAINED;
98 extern const void *CFArrayGetValueAtIndex(CFArrayRef theArray, CFIndex idx) CF_RETURNS_NOT_RETAINED;
99 extern void CFArrayAppendValue(CFMutableArrayRef theArray, const void *value);
102 CFDictionaryKeyCallBacks;
103 extern const CFDictionaryKeyCallBacks kCFTypeDictionaryKeyCallBacks;
106 CFDictionaryValueCallBacks;
107 extern const CFDictionaryValueCallBacks kCFTypeDictionaryValueCallBacks;
108 typedef const struct __CFDictionary * CFDictionaryRef;
109 typedef struct __CFDictionary * CFMutableDictionaryRef;
110 extern CFMutableDictionaryRef CFDictionaryCreateMutable(CFAllocatorRef allocator, CFIndex capacity, const CFDictionaryKeyCallBacks *keyCallBacks, const CFDictionaryValueCallBacks *valueCallBacks) CF_RETURNS_RETAINED;
111 typedef UInt32 CFStringEncoding;
113 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 };
114 extern CFStringRef CFStringCreateWithCString(CFAllocatorRef alloc, const char *cStr, CFStringEncoding encoding) CF_RETURNS_RETAINED;
115 typedef double CFTimeInterval;
116 typedef CFTimeInterval CFAbsoluteTime;
117 extern CFAbsoluteTime CFAbsoluteTimeGetCurrent(void);
118 typedef const struct __CFDate * CFDateRef;
119 extern CFDateRef CFDateCreate(CFAllocatorRef allocator, CFAbsoluteTime at) CF_RETURNS_RETAINED;
120 extern CFAbsoluteTime CFDateGetAbsoluteTime(CFDateRef theDate);
121 typedef __darwin_natural_t natural_t;
122 typedef natural_t mach_port_name_t;
123 typedef mach_port_name_t mach_port_t;
124 typedef int kern_return_t;
125 typedef kern_return_t mach_error_t;
127 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 };
128 typedef CFIndex CFNumberType;
129 typedef const struct __CFNumber * CFNumberRef;
130 extern CFNumberRef CFNumberCreate(CFAllocatorRef allocator, CFNumberType theType, const void *valuePtr) CF_RETURNS_RETAINED;
131 typedef const struct __CFAttributedString *CFAttributedStringRef;
132 typedef struct __CFAttributedString *CFMutableAttributedStringRef;
133 extern CFAttributedStringRef CFAttributedStringCreate(CFAllocatorRef alloc, CFStringRef str, CFDictionaryRef attributes) CF_RETURNS_RETAINED ;
134 extern CFMutableAttributedStringRef CFAttributedStringCreateMutableCopy(CFAllocatorRef alloc, CFIndex maxLength, CFAttributedStringRef aStr) CF_RETURNS_RETAINED ;
135 extern void CFAttributedStringSetAttribute(CFMutableAttributedStringRef aStr, CFRange range, CFStringRef attrName, CFTypeRef value) ;
136 typedef signed char BOOL;
137 typedef unsigned long NSUInteger;
138 @class NSString, Protocol;
139 extern void NSLog(NSString *format, ...) __attribute__((format(__NSString__, 1, 2)));
140 typedef struct _NSZone NSZone;
141 @class NSInvocation, NSMethodSignature, NSCoder, NSString, NSEnumerator;
143 - (BOOL)isEqual:(id)object;
145 - (oneway void)release;
147 - (NSString *)description;
148 - (instancetype)init;
151 - (id)copyWithZone:(NSZone *)zone;
153 @protocol NSMutableCopying - (id)mutableCopyWithZone:(NSZone *)zone;
155 @protocol NSCoding - (void)encodeWithCoder:(NSCoder *)aCoder;
157 @interface NSObject <NSObject> {}
158 + (id)allocWithZone:(NSZone *)zone;
163 @interface NSObject (NSCoderMethods)
164 - (id)awakeAfterUsingCoder:(NSCoder *)aDecoder;
166 extern id NSAllocateObject(Class aClass, NSUInteger extraBytes, NSZone *zone);
169 NSFastEnumerationState;
170 @protocol NSFastEnumeration
171 - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len;
173 @class NSString, NSDictionary;
174 @interface NSValue : NSObject <NSCopying, NSCoding> - (void)getValue:(void *)value;
176 @interface NSNumber : NSValue
178 - (instancetype)initWithInt:(int)value;
179 + (NSNumber *)numberWithInt:(int)value;
182 @interface NSArray : NSObject <NSCopying, NSMutableCopying, NSCoding, NSFastEnumeration>
184 - (instancetype)initWithObjects:(const id [])objects count:(NSUInteger)cnt;
185 + (instancetype)arrayWithObject:(id)anObject;
186 + (instancetype)arrayWithObjects:(const id [])objects count:(NSUInteger)cnt;
187 + (instancetype)arrayWithObjects:(id)firstObj, ... __attribute__((sentinel(0,1)));
188 - (instancetype)initWithObjects:(id)firstObj, ... __attribute__((sentinel(0,1)));
189 - (instancetype)initWithArray:(NSArray *)array;
190 @end @interface NSArray (NSArrayCreation) + (instancetype)array;
191 @end @interface NSAutoreleasePool : NSObject {
194 @end extern NSString * const NSBundleDidLoadNotification;
195 typedef double NSTimeInterval;
196 @interface NSDate : NSObject <NSCopying, NSCoding> - (NSTimeInterval)timeIntervalSinceReferenceDate;
197 @end typedef unsigned short unichar;
198 @interface NSString : NSObject <NSCopying, NSMutableCopying, NSCoding>
199 - (NSUInteger)length;
200 - (NSString *)stringByAppendingString:(NSString *)aString;
201 - ( const char *)UTF8String;
202 - (instancetype)initWithUTF8String:(const char *)nullTerminatedCString;
203 + (instancetype)stringWithUTF8String:(const char *)nullTerminatedCString;
204 @end @class NSString, NSURL, NSError;
205 @interface NSData : NSObject <NSCopying, NSMutableCopying, NSCoding> - (NSUInteger)length;
206 + (instancetype)dataWithBytesNoCopy:(void *)bytes length:(NSUInteger)length;
207 + (instancetype)dataWithBytesNoCopy:(void *)bytes length:(NSUInteger)length freeWhenDone:(BOOL)b;
208 @end @class NSLocale, NSDate, NSCalendar, NSTimeZone, NSError, NSArray, NSMutableDictionary;
209 @interface NSDictionary : NSObject <NSCopying, NSMutableCopying, NSCoding, NSFastEnumeration>
211 + (instancetype)dictionaryWithObjects:(NSArray *)objects forKeys:(NSArray *)keys;
212 + (instancetype)dictionaryWithObjects:(const id [])objects forKeys:(const id <NSCopying> [])keys count:(NSUInteger)cnt;
214 @interface NSMutableDictionary : NSDictionary - (void)removeObjectForKey:(id)aKey;
215 - (void)setObject:(id)anObject forKey:(id)aKey;
216 @end @interface NSMutableDictionary (NSMutableDictionaryCreation) + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
217 @end typedef double CGFloat;
220 typedef struct CGSize CGSize;
223 typedef struct CGRect CGRect;
224 typedef mach_port_t io_object_t;
225 typedef char io_name_t[128];
226 typedef io_object_t io_iterator_t;
227 typedef io_object_t io_service_t;
228 typedef struct IONotificationPort * IONotificationPortRef;
229 typedef void (*IOServiceMatchingCallback)( void * refcon, io_iterator_t iterator );
231 CF_IMPLICIT_BRIDGING_ENABLED
233 io_service_t IOServiceGetMatchingService( mach_port_t mainPort, CFDictionaryRef matching );
234 kern_return_t IOServiceGetMatchingServices( mach_port_t mainPort, CFDictionaryRef matching, io_iterator_t * existing );
236 CF_IMPLICIT_BRIDGING_DISABLED
238 kern_return_t IOServiceAddNotification( mach_port_t mainPort, const io_name_t notificationType, CFDictionaryRef matching, mach_port_t wakePort, uintptr_t reference, io_iterator_t * notification ) __attribute__((deprecated)); // expected-note {{'IOServiceAddNotification' declared here}}
239 kern_return_t IOServiceAddMatchingNotification( IONotificationPortRef notifyPort, const io_name_t notificationType, CFDictionaryRef CF_CONSUMED matching, IOServiceMatchingCallback callback, void * refCon, io_iterator_t * notification );
241 CF_IMPLICIT_BRIDGING_ENABLED
243 CFMutableDictionaryRef IOServiceMatching( const char * name );
244 CFMutableDictionaryRef IOServiceNameMatching( const char * name );
245 CFMutableDictionaryRef IOBSDNameMatching( mach_port_t mainPort, uint32_t options, const char * bsdName );
246 CFMutableDictionaryRef IOOpenFirmwarePathMatching( mach_port_t mainPort, uint32_t options, const char * path );
247 CFMutableDictionaryRef IORegistryEntryIDMatching( uint64_t entryID );
249 CF_IMPLICIT_BRIDGING_DISABLED
251 typedef struct __DASession * DASessionRef;
252 extern DASessionRef DASessionCreate( CFAllocatorRef allocator ) CF_RETURNS_RETAINED;
253 typedef struct __DADisk * DADiskRef;
254 extern DADiskRef DADiskCreateFromBSDName( CFAllocatorRef allocator, DASessionRef session, const char * name ) CF_RETURNS_RETAINED;
255 extern DADiskRef DADiskCreateFromIOMedia( CFAllocatorRef allocator, DASessionRef session, io_service_t media ) CF_RETURNS_RETAINED;
256 extern CFDictionaryRef DADiskCopyDescription( DADiskRef disk ) CF_RETURNS_RETAINED;
257 extern DADiskRef DADiskCopyWholeDisk( DADiskRef disk ) CF_RETURNS_RETAINED;
258 @interface NSTask : NSObject - (instancetype)init;
259 @end typedef struct CGColorSpace *CGColorSpaceRef;
260 typedef struct CGImage *CGImageRef;
261 typedef struct CGLayer *CGLayerRef;
262 @interface NSResponder : NSObject <NSCoding> {
264 @end @protocol NSAnimatablePropertyContainer - (id)animator;
265 @end extern NSString *NSAnimationTriggerOrderIn ;
266 @interface NSView : NSResponder <NSAnimatablePropertyContainer> {
268 @end @protocol NSValidatedUserInterfaceItem - (SEL)action;
269 @end @protocol NSUserInterfaceValidations - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)anItem;
270 @end @class NSDate, NSDictionary, NSError, NSException, NSNotification;
271 @class NSTextField, NSPanel, NSArray, NSWindow, NSImage, NSButton, NSError;
272 @interface NSApplication : NSResponder <NSUserInterfaceValidations> {
274 - (void)beginSheet:(NSWindow *)sheet modalForWindow:(NSWindow *)docWindow modalDelegate:(id)modalDelegate didEndSelector:(SEL)didEndSelector contextInfo:(void *)contextInfo;
276 NSTerminateCancel = 0, NSTerminateNow = 1, NSTerminateLater = 2 };
277 typedef NSUInteger NSApplicationTerminateReply;
278 @protocol NSApplicationDelegate <NSObject> @optional - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender;
279 @end @class NSAttributedString, NSEvent, NSFont, NSFormatter, NSImage, NSMenu, NSText, NSView, NSTextView;
280 @interface NSCell : NSObject <NSCopying, NSCoding> {
286 @interface CIImage : NSObject <NSCoding, NSCopying> {
288 typedef int CIFormat;
290 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 };
291 typedef mach_error_t DAReturn;
292 typedef const struct __DADissenter * DADissenterRef;
293 extern DADissenterRef DADissenterCreate( CFAllocatorRef allocator, DAReturn status, CFStringRef string ) CF_RETURNS_RETAINED;
294 @interface CIContext: NSObject {
296 - (CGImageRef)createCGImage:(CIImage *)im fromRect:(CGRect)r CF_RETURNS_RETAINED;
297 - (CGImageRef)createCGImage:(CIImage *)im fromRect:(CGRect)r format:(CIFormat)f colorSpace:(CGColorSpaceRef)cs CF_RETURNS_RETAINED;
298 - (CGLayerRef)createCGLayerWithSize:(CGSize)size info:(CFDictionaryRef)d CF_RETURNS_RETAINED;
299 @end extern NSString* const QCRendererEventKey;
300 @protocol QCCompositionRenderer - (NSDictionary*) attributes;
301 @end @interface QCRenderer : NSObject <QCCompositionRenderer> {
303 - (id) createSnapshotImageOfType:(NSString*)type NS_RETURNS_RETAINED;
304 @end extern NSString* const QCViewDidStartRenderingNotification;
305 @interface QCView : NSView <QCCompositionRenderer> {
307 - (id) createSnapshotImageOfType:(NSString*)type NS_RETURNS_RETAINED;
309 ICEXIFOrientation1 = 1, ICEXIFOrientation2 = 2, ICEXIFOrientation3 = 3, ICEXIFOrientation4 = 4, ICEXIFOrientation5 = 5, ICEXIFOrientation6 = 6, ICEXIFOrientation7 = 7, ICEXIFOrientation8 = 8, };
311 @protocol ICDeviceDelegate <NSObject> @required - (void)didRemoveDevice:(ICDevice*)device;
312 @end extern NSString *const ICScannerStatusWarmingUp;
313 @class ICScannerDevice;
314 @protocol ICScannerDeviceDelegate <ICDeviceDelegate> @optional - (void)scannerDeviceDidBecomeAvailable:(ICScannerDevice*)scanner;
317 typedef long unsigned int __darwin_size_t;
318 typedef __darwin_size_t size_t;
319 typedef unsigned long CFTypeID;
324 typedef struct CGPoint CGPoint;
325 typedef struct CGGradient *CGGradientRef;
326 typedef uint32_t CGGradientDrawingOptions;
327 extern CFTypeID CGGradientGetTypeID(void);
328 extern CGGradientRef CGGradientCreateWithColorComponents(CGColorSpaceRef
329 space, const CGFloat components[], const CGFloat locations[], size_t count) CF_RETURNS_RETAINED;
330 extern CGGradientRef CGGradientCreateWithColors(CGColorSpaceRef space,
331 CFArrayRef colors, const CGFloat locations[]) CF_RETURNS_RETAINED;
332 extern CGGradientRef CGGradientRetain(CGGradientRef gradient);
334 CF_IMPLICIT_BRIDGING_ENABLED
336 extern void CGGradientRelease(CGGradientRef gradient);
338 CF_IMPLICIT_BRIDGING_DISABLED
340 typedef struct CGContext *CGContextRef;
341 extern void CGContextDrawLinearGradient(CGContextRef context,
342 CGGradientRef gradient, CGPoint startPoint, CGPoint endPoint,
343 CGGradientDrawingOptions options);
345 CF_IMPLICIT_BRIDGING_ENABLED
347 extern CGColorSpaceRef CGColorSpaceCreateDeviceRGB(void);
349 CF_IMPLICIT_BRIDGING_DISABLED
352 @interface NSMutableArray : NSObject
353 - (void)addObject:(id)object;
354 + (instancetype)array;
357 // This is how NSMakeCollectable is declared in the OS X 10.8 headers.
358 id NSMakeCollectable(CFTypeRef __attribute__((cf_consumed))) __attribute__((ns_returns_retained));
360 typedef const struct __CFUUID * CFUUIDRef;
363 void *CFPlugInInstanceCreate(CFAllocatorRef allocator, CFUUIDRef factoryUUID, CFUUIDRef typeUUID);
365 //===----------------------------------------------------------------------===//
367 //===----------------------------------------------------------------------===//
369 CFAbsoluteTime f1(void) {
370 CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
371 CFDateRef date = CFDateCreate(0, t);
374 CFDateGetAbsoluteTime(date); // no-warning
376 t = CFDateGetAbsoluteTime(date); // expected-warning{{Reference-counted object is used after it is released}}
380 CFAbsoluteTime f2(void) {
381 CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
382 CFDateRef date = CFDateCreate(0, t);
383 [((NSDate*) date) retain];
385 CFDateGetAbsoluteTime(date); // no-warning
386 [((NSDate*) date) release];
387 t = CFDateGetAbsoluteTime(date); // expected-warning{{Reference-counted object is used after it is released}}
394 // Test to see if we suppress an error when we store the pointer
397 CFAbsoluteTime f3(void) {
398 CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
399 CFDateRef date = CFDateCreate(0, t);
400 [((NSDate*) date) retain];
402 CFDateGetAbsoluteTime(date); // no-warning
403 global_x = (NSDate*) date;
404 [((NSDate*) date) release];
405 t = CFDateGetAbsoluteTime(date); // no-warning
409 //---------------------------------------------------------------------------
410 // Test case 'f4' differs for region store and basic store. See
411 // retain-release-region-store.m and retain-release-basic-store.m.
412 //---------------------------------------------------------------------------
416 CFAbsoluteTime f5(int x) {
417 CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
418 CFDateRef date = CFDateCreate(0, t); // expected-warning{{leak}}
426 // Test a leak involving the return.
428 CFDateRef f6(int x) {
429 CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent()); // expected-warning{{leak}}
434 // Test a leak involving an overwrite.
437 CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent()); //expected-warning{{leak}}
439 date = CFDateCreate(0, CFAbsoluteTimeGetCurrent()); // expected-warning {{leak}}
443 // Generalization of Create rule. MyDateCreate returns a CFXXXTypeRef, and
444 // has the word create.
446 CF_IMPLICIT_BRIDGING_ENABLED
448 CFDateRef MyDateCreate(void);
450 CF_IMPLICIT_BRIDGING_DISABLED
454 CFDateRef date = MyDateCreate(); // expected-warning{{leak}}
459 __attribute__((cf_returns_retained)) CFDateRef f9(void) {
460 CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent()); // no-warning
462 // When allocations fail, CFDateCreate can return null.
463 if (!date) *p = 1; // expected-warning{{null}}
467 // Handle DiskArbitration API:
469 // http://developer.apple.com/DOCUMENTATION/DARWIN/Reference/DiscArbitrationFramework/
471 void f10(io_service_t media, DADiskRef d, CFStringRef s) {
472 DADiskRef disk = DADiskCreateFromBSDName(kCFAllocatorDefault, 0, "hello"); // expected-warning{{leak}}
473 if (disk) NSLog(@"ok");
475 disk = DADiskCreateFromIOMedia(kCFAllocatorDefault, 0, media); // expected-warning{{leak}}
476 if (disk) NSLog(@"ok");
478 CFDictionaryRef dict = DADiskCopyDescription(d); // expected-warning{{leak}}
479 if (dict) NSLog(@"ok");
481 disk = DADiskCopyWholeDisk(d); // expected-warning{{leak}}
482 if (disk) NSLog(@"ok");
484 DADissenterRef dissenter = DADissenterCreate(kCFAllocatorDefault, // expected-warning{{leak}}
485 kDAReturnSuccess, s);
486 if (dissenter) NSLog(@"ok");
488 DASessionRef session = DASessionCreate(kCFAllocatorDefault); // expected-warning{{leak}}
489 if (session) NSLog(@"ok");
492 // Test retain/release checker with CFString and CFMutableArray.
495 CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
498 CFStringRef s1 = CFStringCreateWithCString(0, "hello world",
499 kCFStringEncodingUTF8);
501 // Add the string to the array.
502 CFArrayAppendValue(A, s1);
504 // Decrement the reference count.
505 CFRelease(s1); // no-warning
507 // Get the string. We don't own it.
508 s1 = (CFStringRef) CFArrayGetValueAtIndex(A, 0);
510 // Release the array.
511 CFRelease(A); // no-warning
513 // Release the string. This is a bug.
514 CFRelease(s1); // expected-warning{{Incorrect decrement of the reference count}}
517 // PR 3337: Handle functions declared using typedefs.
518 typedef CFTypeRef CREATEFUN(void);
520 CF_IMPLICIT_BRIDGING_ENABLED
522 CFTypeRef MyCreateFun(void);
524 CF_IMPLICIT_BRIDGING_DISABLED
528 CFTypeRef o = MyCreateFun(); // expected-warning {{leak}}
531 void f13_autorelease(void) {
532 CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
533 [(id) A autorelease]; // no-warning
536 void f13_autorelease_b(void) {
537 CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
538 [(id) A autorelease];
539 [(id) A autorelease];
540 } // expected-warning{{Object autoreleased too many times}}
542 CFMutableArrayRef f13_autorelease_c(void) {
543 CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
544 [(id) A autorelease];
545 [(id) A autorelease];
546 return A; // expected-warning{{Object autoreleased too many times}}
549 CFMutableArrayRef f13_autorelease_d(void) {
550 CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
551 [(id) A autorelease];
552 [(id) A autorelease];
553 CFMutableArrayRef B = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning{{Object autoreleased too many times}}
554 CFRelease(B); // no-warning
559 // This case exercises the logic where the leak site is the same as the allocation site.
560 void f14_leakimmediately(void) {
561 CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning{{leak}}
564 // Test that we track an allocated object beyond the point where the *name*
565 // of the variable storing the reference is no longer live.
568 CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
569 CFMutableArrayRef *B = &A;
570 // At this point, the name 'A' is no longer live.
571 CFRelease(*B); // no-warning
574 // Test when we pass NULL to CFRetain/CFRelease/CFMakeCollectable/CFAutorelease.
575 void f16(int x, CFTypeRef p) {
587 CFMakeCollectable(p);
597 // Test that an object is non-null after CFRetain/CFRelease/CFMakeCollectable/CFAutorelease.
598 void f17(int x, CFTypeRef p) {
603 CFRelease(0); // no-warning
608 CFRetain(0); // no-warning
611 CFMakeCollectable(p);
613 CFMakeCollectable(0); // no-warning
618 CFAutorelease(0); // no-warning
625 // Test basic tracking of ivars associated with 'self'. For the retain/release
626 // checker we currently do not want to flag leaks associated with stores
627 // of tracked objects to ivars.
628 @interface SelfIvarTest : NSObject {
631 - (void)test_self_tracking;
634 @implementation SelfIvarTest
635 - (void)test_self_tracking {
636 myObj = (id) CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
640 // Test return of non-owned objects in contexts where an owned object
642 @interface TestReturnNotOwnedWhenExpectedOwned
643 - (NSString*)newString;
646 @implementation TestReturnNotOwnedWhenExpectedOwned
647 - (NSString*)newString {
648 NSString *s = [NSString stringWithUTF8String:"hello"];
649 return s; // expected-warning{{Object with a +0 retain count returned to caller where a +1 (owning) retain count is expected}}
653 // <rdar://problem/6659160>
656 static void rdar_6659160(char *inkind, char *inname)
658 // We currently expect that [NSObject alloc] cannot fail. This
659 // will be a toggled flag in the future. It can indeed return null, but
660 // Cocoa programmers generally aren't expected to reason about out-of-memory
662 NSString *kind = [[NSString alloc] initWithUTF8String:inkind]; // expected-warning{{leak}}
664 // We do allow stringWithUTF8String to fail. This isn't really correct, as
665 // far as returning 0. In most error conditions it will throw an exception.
666 // If allocation fails it could return 0, but again this
668 NSString *name = [NSString stringWithUTF8String:inname];
672 const char *kindC = 0;
673 const char *nameC = 0;
675 // In both cases, we cannot reach a point down below where we
676 // dereference kindC or nameC with either being null. This is because
677 // we assume that [NSObject alloc] doesn't fail and that we have the guard
681 kindC = [kind UTF8String];
683 nameC = [name UTF8String];
684 if(!isFoo(kindC[0])) // expected-warning{{null}}
686 if(!isFoo(nameC[0])) // no-warning
690 [name release]; // expected-warning{{Incorrect decrement of the reference count}}
693 // PR 3677 - 'allocWithZone' should be treated as following the Cocoa naming
694 // conventions with respect to 'return'ing ownership.
695 @interface PR3677: NSObject @end
696 @implementation PR3677
697 + (id)allocWithZone:(NSZone *)inZone {
698 return [super allocWithZone:inZone]; // no-warning
702 // PR 3820 - Reason about calls to -dealloc
703 void pr3820_DeallocInsteadOfRelease(void)
705 id foo = [[NSString alloc] init]; // no-warning
707 // foo is not leaked, since it has been deallocated.
710 void pr3820_ReleaseAfterDealloc(void)
712 id foo = [[NSString alloc] init];
714 [foo release]; // expected-warning{{used after it is release}}
715 // NSInternalInconsistencyException: message sent to deallocated object
718 void pr3820_DeallocAfterRelease(void)
720 NSLog(@"\n\n[%s]", __FUNCTION__);
721 id foo = [[NSString alloc] init];
723 [foo dealloc]; // expected-warning{{used after it is released}}
724 // message sent to released object
727 // From <rdar://problem/6704930>. The problem here is that 'length' binds to
728 // '($0 - 1)' after '--length', but SimpleConstraintManager doesn't know how to
729 // reason about '($0 - 1) > constant'. As a temporary hack, we drop the value
730 // of '($0 - 1)' and conjure a new symbol.
731 void rdar6704930(unsigned char *s, unsigned int length) {
739 name = [[NSString alloc] init]; // no-warning
745 if ((length == 0) && (name != 0)) {
749 if (length == 0) { // no ':' found -> use it all as name
750 name = [[NSString alloc] init]; // no-warning
760 //===----------------------------------------------------------------------===//
761 // <rdar://problem/6833332>
762 // One build of the analyzer accidentally stopped tracking the allocated
763 // object after the 'retain'.
764 //===----------------------------------------------------------------------===//
766 @interface rdar_6833332 : NSObject <NSApplicationDelegate> {
769 @property (nonatomic, retain) NSWindow *window;
772 @implementation rdar_6833332
774 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
775 NSMutableDictionary *dict = [[NSMutableDictionary dictionaryWithCapacity:4] retain]; // expected-warning{{leak}}
777 [dict setObject:@"foo" forKey:@"bar"];
786 - (void)radar10102244 {
787 NSMutableDictionary *dict = [[NSMutableDictionary dictionaryWithCapacity:4] retain]; // expected-warning{{leak}}
789 NSLog(@"%@", window);
793 //===----------------------------------------------------------------------===//
794 // <rdar://problem/6257780> clang checker fails to catch use-after-release
795 //===----------------------------------------------------------------------===//
797 int rdar_6257780_Case1(void) {
798 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
799 NSArray *array = [NSArray array];
800 [array release]; // expected-warning{{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
805 //===----------------------------------------------------------------------===//
806 // <rdar://problem/10640253> Analyzer is confused about NSAutoreleasePool -allocWithZone:.
807 //===----------------------------------------------------------------------===//
809 void rdar_10640253_autorelease_allocWithZone(void) {
810 NSAutoreleasePool *pool = [[NSAutoreleasePool allocWithZone:(NSZone*)0] init];
814 //===----------------------------------------------------------------------===//
815 // <rdar://problem/6866843> Checker should understand new/setObject:/release constructs
816 //===----------------------------------------------------------------------===//
818 void rdar_6866843(void) {
819 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
820 NSMutableDictionary* dictionary = [[NSMutableDictionary alloc] init];
821 NSArray* array = [[NSArray alloc] init];
822 [dictionary setObject:array forKey:@"key"];
824 // Using 'array' here should be fine
825 NSLog(@"array = %@\n", array); // no-warning
826 // Now the array is released
827 [dictionary release];
832 //===----------------------------------------------------------------------===//
833 // <rdar://problem/6877235> Classes typedef-ed to CF objects should get the same treatment as CF objects
834 //===----------------------------------------------------------------------===//
836 typedef CFTypeRef OtherRef;
838 @interface RDar6877235 : NSObject {}
839 - (CFTypeRef)_copyCFTypeRef CF_RETURNS_RETAINED;
840 - (OtherRef)_copyOtherRef CF_RETURNS_RETAINED;
843 @implementation RDar6877235
844 - (CFTypeRef)_copyCFTypeRef {
845 return [[NSString alloc] init]; // no-warning
847 - (OtherRef)_copyOtherRef {
848 return [[NSString alloc] init]; // no-warning
852 //===----------------------------------------------------------------------===//
853 // <rdar://problem/6320065> false positive - init method returns an object
855 //===----------------------------------------------------------------------===//
857 @interface RDar6320065 : NSObject {
860 - (instancetype)initReturningNewClass;
861 - (id)_initReturningNewClassBad;
862 - (instancetype)initReturningNewClassBad2;
865 @interface RDar6320065Subclass : RDar6320065
868 @implementation RDar6320065
869 - (instancetype)initReturningNewClass {
871 self = [[RDar6320065Subclass alloc] init]; // no-warning
874 - (id)_initReturningNewClassBad {
876 [[RDar6320065Subclass alloc] init]; // expected-warning {{leak}}
879 - (instancetype)initReturningNewClassBad2 {
881 self = [[RDar6320065Subclass alloc] init];
882 return [self autorelease]; // expected-warning{{Object with a +0 retain count returned to caller where a +1 (owning) retain count is expected}}
887 @implementation RDar6320065Subclass
890 int RDar6320065_test(void) {
891 RDar6320065 *test = [[RDar6320065 alloc] init]; // no-warning
896 //===----------------------------------------------------------------------===//
897 // <rdar://problem/7129086> -awakeAfterUsingCoder: returns an owned object
898 // and claims the receiver
899 //===----------------------------------------------------------------------===//
901 @interface RDar7129086 : NSObject {} @end
902 @implementation RDar7129086
903 - (id)awakeAfterUsingCoder:(NSCoder *)aDecoder {
904 [self release]; // no-warning
905 return [NSString alloc]; // no-warning
909 //===----------------------------------------------------------------------===//
910 // <rdar://problem/6859457> [NSData dataWithBytesNoCopy] does not return a
912 //===----------------------------------------------------------------------===//
914 @interface RDar6859457 : NSObject {}
915 - (NSString*) NoCopyString;
916 - (NSString*) noCopyString;
919 @implementation RDar6859457
920 - (NSString*) NoCopyString { return [[NSString alloc] init]; } // expected-warning{{leak}}
921 - (NSString*) noCopyString { return [[NSString alloc] init]; } // expected-warning{{leak}}
924 void test_RDar6859457(RDar6859457 *x, void *bytes, NSUInteger dataLength) {
925 [x NoCopyString]; // expected-warning{{leak}}
926 [x noCopyString]; // expected-warning{{leak}}
927 [NSData dataWithBytesNoCopy:bytes length:dataLength]; // no-warning
928 [NSData dataWithBytesNoCopy:bytes length:dataLength freeWhenDone:1]; // no-warning
931 //===----------------------------------------------------------------------===//
932 // PR 4230 - an autorelease pool is not necessarily leaked during a premature
934 //===----------------------------------------------------------------------===//
936 static void PR4230(void)
938 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // no-warning
939 NSString *object = [[[NSString alloc] init] autorelease]; // no-warning
943 static void PR4230_new(void)
945 NSAutoreleasePool *pool = [NSAutoreleasePool new]; // no-warning
946 NSString *object = [[[NSString alloc] init] autorelease]; // no-warning
950 //===----------------------------------------------------------------------===//
951 // Method name that has a null IdentifierInfo* for its first selector slot.
952 // This test just makes sure that we handle it.
953 //===----------------------------------------------------------------------===//
955 @interface TestNullIdentifier
958 @implementation TestNullIdentifier
960 return [[NSString alloc] init]; // expected-warning{{leak}}
964 //===----------------------------------------------------------------------===//
965 // <rdar://problem/6893565> don't flag leaks for return types that cannot be
966 // determined to be CF types
967 //===----------------------------------------------------------------------===//
969 // We don't know if 'struct s6893565' represents a Core Foundation type, so
970 // we shouldn't emit an error here.
971 typedef struct s6893565* TD6893565;
973 @interface RDar6893565 {}
974 -(TD6893565)newThing;
977 @implementation RDar6893565
978 -(TD6893565)newThing {
979 return (TD6893565) [[NSString alloc] init]; // no-warning
983 //===----------------------------------------------------------------------===//
984 // <rdar://problem/6902710> clang: false positives w/QC and CoreImage methods
985 //===----------------------------------------------------------------------===//
987 void rdar6902710(QCView *view, QCRenderer *renderer, CIContext *context,
988 NSString *str, CIImage *img, CGRect rect,
989 CIFormat form, CGColorSpaceRef cs) {
990 [view createSnapshotImageOfType:str]; // expected-warning{{leak}}
991 [renderer createSnapshotImageOfType:str]; // expected-warning{{leak}}
992 [context createCGImage:img fromRect:rect]; // expected-warning{{leak}}
993 [context createCGImage:img fromRect:rect format:form colorSpace:cs]; // expected-warning{{leak}}
996 //===----------------------------------------------------------------------===//
997 // <rdar://problem/6945561> -[CIContext createCGLayerWithSize:info:]
998 // misinterpreted by clang scan-build
999 //===----------------------------------------------------------------------===//
1001 void rdar6945561(CIContext *context, CGSize size, CFDictionaryRef d) {
1002 [context createCGLayerWithSize:size info:d]; // expected-warning{{leak}}
1005 //===----------------------------------------------------------------------===//
1006 // <rdar://problem/6961230> add knowledge of IOKit functions to retain/release
1008 //===----------------------------------------------------------------------===//
1010 void IOBSDNameMatching_wrapper(mach_port_t mainPort, uint32_t options, const char * bsdName) {
1011 IOBSDNameMatching(mainPort, options, bsdName); // expected-warning{{leak}}
1014 void IOServiceMatching_wrapper(const char * name) {
1015 IOServiceMatching(name); // expected-warning{{leak}}
1018 void IOServiceNameMatching_wrapper(const char * name) {
1019 IOServiceNameMatching(name); // expected-warning{{leak}}
1022 CF_RETURNS_RETAINED CFDictionaryRef CreateDict(void);
1024 void IOServiceAddNotification_wrapper(mach_port_t mainPort, const io_name_t notificationType,
1025 mach_port_t wakePort, uintptr_t reference, io_iterator_t * notification ) {
1027 CFDictionaryRef matching = CreateDict();
1028 CFRelease(matching);
1029 IOServiceAddNotification(mainPort, notificationType, matching, // expected-warning{{used after it is released}} expected-warning{{deprecated}}
1030 wakePort, reference, notification);
1033 void IORegistryEntryIDMatching_wrapper(uint64_t entryID ) {
1034 IORegistryEntryIDMatching(entryID); // expected-warning{{leak}}
1037 void IOOpenFirmwarePathMatching_wrapper(mach_port_t mainPort, uint32_t options,
1038 const char * path) {
1039 IOOpenFirmwarePathMatching(mainPort, options, path); // expected-warning{{leak}}
1042 void IOServiceGetMatchingService_wrapper(mach_port_t mainPort) {
1043 CFDictionaryRef matching = CreateDict();
1044 IOServiceGetMatchingService(mainPort, matching);
1045 CFRelease(matching); // expected-warning{{used after it is released}}
1048 void IOServiceGetMatchingServices_wrapper(mach_port_t mainPort, io_iterator_t *existing) {
1049 CFDictionaryRef matching = CreateDict();
1050 IOServiceGetMatchingServices(mainPort, matching, existing);
1051 CFRelease(matching); // expected-warning{{used after it is released}}
1054 void IOServiceAddMatchingNotification_wrapper(IONotificationPortRef notifyPort, const io_name_t notificationType,
1055 IOServiceMatchingCallback callback, void * refCon, io_iterator_t * notification) {
1057 CFDictionaryRef matching = CreateDict();
1058 IOServiceAddMatchingNotification(notifyPort, notificationType, matching, callback, refCon, notification);
1059 CFRelease(matching); // expected-warning{{used after it is released}}
1062 //===----------------------------------------------------------------------===//
1063 // Test of handling objects whose references "escape" to containers.
1064 //===----------------------------------------------------------------------===//
1066 void CFDictionaryAddValue(CFMutableDictionaryRef, void *, void *);
1068 // <rdar://problem/6539791>
1069 void rdar_6539791(CFMutableDictionaryRef y, void* key, void* val_key) {
1070 CFMutableDictionaryRef x = CFDictionaryCreateMutable(kCFAllocatorDefault, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
1071 CFDictionaryAddValue(y, key, x);
1072 CFRelease(x); // the dictionary keeps a reference, so the object isn't deallocated yet
1074 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z);
1076 CFDictionaryAddValue(x, val_key, (void*)value); // no-warning
1078 CFDictionaryAddValue(y, val_key, (void*)value); // no-warning
1082 // <rdar://problem/6560661>
1083 // Same issue, except with "AppendValue" functions.
1084 void rdar_6560661(CFMutableArrayRef x) {
1086 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z);
1087 // CFArrayAppendValue keeps a reference to value.
1088 CFArrayAppendValue(x, value);
1091 CFRelease(value); // no-warning
1094 // <rdar://problem/7152619>
1095 // Same issue, excwept with "CFAttributeStringSetAttribute".
1096 void rdar_7152619(CFStringRef str) {
1097 CFAttributedStringRef string = CFAttributedStringCreate(kCFAllocatorDefault, str, 0);
1098 CFMutableAttributedStringRef attrString = CFAttributedStringCreateMutableCopy(kCFAllocatorDefault, 100, string);
1100 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1101 CFAttributedStringSetAttribute(attrString, CFRangeMake(0, 1), str, number);
1104 CFRelease(attrString);
1107 //===----------------------------------------------------------------------===//
1108 // Test of handling CGGradientXXX functions.
1109 //===----------------------------------------------------------------------===//
1111 void rdar_7184450(CGContextRef myContext, CGFloat x, CGPoint myStartPoint,
1112 CGPoint myEndPoint) {
1113 size_t num_locations = 6;
1114 CGFloat locations[6] = { 0.0, 0.265, 0.28, 0.31, 0.36, 1.0 };
1115 CGFloat components[28] = { 239.0/256.0, 167.0/256.0, 170.0/256.0,
1117 207.0/255.0, 39.0/255.0, 39.0/255.0, x,
1118 147.0/255.0, 21.0/255.0, 22.0/255.0, x,
1119 175.0/255.0, 175.0/255.0, 175.0/255.0, x,
1120 255.0/255.0,255.0/255.0, 255.0/255.0, x,
1121 255.0/255.0,255.0/255.0, 255.0/255.0, x
1124 CGGradientRef myGradient =
1125 CGGradientCreateWithColorComponents(CGColorSpaceCreateDeviceRGB(), // expected-warning{{leak}}
1126 components, locations, num_locations);
1128 CGContextDrawLinearGradient(myContext, myGradient, myStartPoint, myEndPoint,
1130 CGGradientRelease(myGradient);
1133 void rdar_7184450_pos(CGContextRef myContext, CGFloat x, CGPoint myStartPoint,
1134 CGPoint myEndPoint) {
1135 size_t num_locations = 6;
1136 CGFloat locations[6] = { 0.0, 0.265, 0.28, 0.31, 0.36, 1.0 };
1137 CGFloat components[28] = { 239.0/256.0, 167.0/256.0, 170.0/256.0,
1139 207.0/255.0, 39.0/255.0, 39.0/255.0, x,
1140 147.0/255.0, 21.0/255.0, 22.0/255.0, x,
1141 175.0/255.0, 175.0/255.0, 175.0/255.0, x,
1142 255.0/255.0,255.0/255.0, 255.0/255.0, x,
1143 255.0/255.0,255.0/255.0, 255.0/255.0, x
1146 CGGradientRef myGradient =
1147 CGGradientCreateWithColorComponents(CGColorSpaceCreateDeviceRGB(), components, locations, num_locations); // expected-warning 2 {{leak}}
1149 CGContextDrawLinearGradient(myContext, myGradient, myStartPoint, myEndPoint,
1153 //===----------------------------------------------------------------------===//
1154 // <rdar://problem/7299394> clang false positive: retained instance passed to
1155 // thread in pthread_create marked as leak
1157 // Until we have full IPA, the analyzer should stop tracking the reference
1158 // count of objects passed to pthread_create.
1160 //===----------------------------------------------------------------------===//
1162 struct _opaque_pthread_t {};
1163 struct _opaque_pthread_attr_t {};
1164 typedef struct _opaque_pthread_t *__darwin_pthread_t;
1165 typedef struct _opaque_pthread_attr_t __darwin_pthread_attr_t;
1166 typedef __darwin_pthread_t pthread_t;
1167 typedef __darwin_pthread_attr_t pthread_attr_t;
1168 typedef unsigned long __darwin_pthread_key_t;
1169 typedef __darwin_pthread_key_t pthread_key_t;
1171 int pthread_create(pthread_t *, const pthread_attr_t *,
1172 void *(*)(void *), void *);
1174 int pthread_setspecific(pthread_key_t key, const void *value);
1176 void *rdar_7299394_start_routine(void *p) {
1180 void rdar_7299394(pthread_attr_t *attr, pthread_t *thread, void *args) {
1181 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1182 pthread_create(thread, attr, rdar_7299394_start_routine, number);
1184 void rdar_7299394_positive(pthread_attr_t *attr, pthread_t *thread) {
1185 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1188 //===----------------------------------------------------------------------===//
1189 // <rdar://problem/11282706> false positive with not understanding thread
1191 //===----------------------------------------------------------------------===//
1193 void rdar11282706(pthread_key_t key) {
1194 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1195 pthread_setspecific(key, (void*) number);
1198 //===----------------------------------------------------------------------===//
1199 // <rdar://problem/7283567> False leak associated with call to
1200 // CVPixelBufferCreateWithBytes ()
1202 // According to the Core Video Reference (ADC), CVPixelBufferCreateWithBytes and
1203 // CVPixelBufferCreateWithPlanarBytes can release (via a callback) the
1204 // pixel buffer object. These test cases show how the analyzer stops tracking
1205 // the reference count for the objects passed for this argument. This
1206 // could be made smarter.
1207 //===----------------------------------------------------------------------===//
1209 typedef int int32_t;
1210 typedef UInt32 FourCharCode;
1211 typedef FourCharCode OSType;
1212 typedef uint64_t CVOptionFlags;
1213 typedef int32_t CVReturn;
1214 typedef struct __CVBuffer *CVBufferRef;
1215 typedef CVBufferRef CVImageBufferRef;
1216 typedef CVImageBufferRef CVPixelBufferRef;
1217 typedef void (*CVPixelBufferReleaseBytesCallback)( void *releaseRefCon, const void *baseAddress );
1219 extern CVReturn CVPixelBufferCreateWithBytes(CFAllocatorRef allocator,
1222 OSType pixelFormatType,
1225 CVPixelBufferReleaseBytesCallback releaseCallback,
1226 void *releaseRefCon,
1227 CFDictionaryRef pixelBufferAttributes,
1228 CVPixelBufferRef *pixelBufferOut) ;
1230 typedef void (*CVPixelBufferReleasePlanarBytesCallback)( void *releaseRefCon, const void *dataPtr, size_t dataSize, size_t numberOfPlanes, const void *planeAddresses[] );
1232 extern CVReturn CVPixelBufferCreateWithPlanarBytes(CFAllocatorRef allocator,
1235 OSType pixelFormatType,
1238 size_t numberOfPlanes,
1239 void *planeBaseAddress[],
1240 size_t planeWidth[],
1241 size_t planeHeight[],
1242 size_t planeBytesPerRow[],
1243 CVPixelBufferReleasePlanarBytesCallback releaseCallback,
1244 void *releaseRefCon,
1245 CFDictionaryRef pixelBufferAttributes,
1246 CVPixelBufferRef *pixelBufferOut) ;
1248 extern CVReturn CVPixelBufferCreateWithBytes(CFAllocatorRef allocator,
1251 OSType pixelFormatType,
1254 CVPixelBufferReleaseBytesCallback releaseCallback,
1255 void *releaseRefCon,
1256 CFDictionaryRef pixelBufferAttributes,
1257 CVPixelBufferRef *pixelBufferOut) ;
1259 CVReturn rdar_7283567(CFAllocatorRef allocator, size_t width, size_t height,
1260 OSType pixelFormatType, void *baseAddress,
1262 CVPixelBufferReleaseBytesCallback releaseCallback,
1263 CFDictionaryRef pixelBufferAttributes,
1264 CVPixelBufferRef *pixelBufferOut) {
1266 // For the allocated object, it doesn't really matter what type it is
1267 // for the purpose of this test. All we want to show is that
1268 // this is freed later by the callback.
1269 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1271 return CVPixelBufferCreateWithBytes(allocator, width, height, pixelFormatType,
1272 baseAddress, bytesPerRow, releaseCallback,
1273 number, // potentially released by callback
1274 pixelBufferAttributes, pixelBufferOut) ;
1277 CVReturn rdar_7283567_2(CFAllocatorRef allocator, size_t width, size_t height,
1278 OSType pixelFormatType, void *dataPtr, size_t dataSize,
1279 size_t numberOfPlanes, void *planeBaseAddress[],
1280 size_t planeWidth[], size_t planeHeight[], size_t planeBytesPerRow[],
1281 CVPixelBufferReleasePlanarBytesCallback releaseCallback,
1282 CFDictionaryRef pixelBufferAttributes,
1283 CVPixelBufferRef *pixelBufferOut) {
1285 // For the allocated object, it doesn't really matter what type it is
1286 // for the purpose of this test. All we want to show is that
1287 // this is freed later by the callback.
1288 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1290 return CVPixelBufferCreateWithPlanarBytes(allocator,
1291 width, height, pixelFormatType, dataPtr, dataSize,
1292 numberOfPlanes, planeBaseAddress, planeWidth,
1293 planeHeight, planeBytesPerRow, releaseCallback,
1294 number, // potentially released by callback
1295 pixelBufferAttributes, pixelBufferOut) ;
1298 //===----------------------------------------------------------------------===//
1299 // <rdar://problem/7358899> False leak associated with
1300 // CGBitmapContextCreateWithData
1301 //===----------------------------------------------------------------------===//
1302 typedef uint32_t CGBitmapInfo;
1303 typedef void (*CGBitmapContextReleaseDataCallback)(void *releaseInfo, void *data);
1305 CGContextRef CGBitmapContextCreateWithData(void *data,
1306 size_t width, size_t height, size_t bitsPerComponent,
1307 size_t bytesPerRow, CGColorSpaceRef space, CGBitmapInfo bitmapInfo,
1308 CGBitmapContextReleaseDataCallback releaseCallback, void *releaseInfo) CF_RETURNS_RETAINED;
1310 void rdar_7358899(void *data,
1311 size_t width, size_t height, size_t bitsPerComponent,
1312 size_t bytesPerRow, CGColorSpaceRef space, CGBitmapInfo bitmapInfo,
1313 CGBitmapContextReleaseDataCallback releaseCallback) {
1315 // For the allocated object, it doesn't really matter what type it is
1316 // for the purpose of this test. All we want to show is that
1317 // this is freed later by the callback.
1318 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1320 CGBitmapContextCreateWithData(data, width, height, bitsPerComponent, // expected-warning{{leak}}
1321 bytesPerRow, space, bitmapInfo, releaseCallback, number);
1324 //===----------------------------------------------------------------------===//
1325 // <rdar://problem/7265711> allow 'new', 'copy', 'alloc', 'init' prefix to
1326 // start before '_' when determining Cocoa fundamental rule
1328 // Previously the retain/release checker just skipped prefixes before the
1329 // first '_' entirely. Now the checker honors the prefix if it results in a
1330 // recognizable naming convention (e.g., 'new', 'init').
1331 //===----------------------------------------------------------------------===//
1333 @interface RDar7265711 {}
1337 void rdar7265711_a(RDar7265711 *x) {
1338 id y = [x new_stuff]; // expected-warning{{leak}}
1341 void rdar7265711_b(RDar7265711 *x) {
1342 id y = [x new_stuff]; // no-warning
1346 //===----------------------------------------------------------------------===//
1347 // <rdar://problem/7306898> clang thinks [NSCursor dragCopyCursor] returns a
1348 // retained reference
1349 //===----------------------------------------------------------------------===//
1351 @interface NSCursor : NSObject
1352 + (NSCursor *)dragCopyCursor;
1355 void rdar7306898(void) {
1356 // 'dragCopyCursor' does not follow Cocoa's fundamental rule. It is a noun, not an sentence
1357 // implying a 'copy' of something.
1358 NSCursor *c = [NSCursor dragCopyCursor]; // no-warning
1359 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1362 //===----------------------------------------------------------------------===//
1363 // <rdar://problem/7252064> sending 'release', 'retain', etc. to a Class
1364 // directly is not likely what the user intended
1365 //===----------------------------------------------------------------------===//
1367 @interface RDar7252064 : NSObject @end
1368 void rdar7252064(void) {
1369 [RDar7252064 release]; // expected-warning{{The 'release' message should be sent to instances of class 'RDar7252064' and not the class directly}}
1370 [RDar7252064 retain]; // expected-warning{{The 'retain' message should be sent to instances of class 'RDar7252064' and not the class directly}}
1371 [RDar7252064 autorelease]; // expected-warning{{The 'autorelease' message should be sent to instances of class 'RDar7252064' and not the class directly}}
1372 [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}}
1375 //===----------------------------------------------------------------------===//
1376 // Tests of ownership attributes.
1377 //===----------------------------------------------------------------------===//
1379 typedef NSString* MyStringTy;
1383 @interface TestOwnershipAttr : NSObject
1384 - (NSString*) returnsAnOwnedString NS_RETURNS_RETAINED; // no-warning
1385 - (NSString*) returnsAnOwnedCFString CF_RETURNS_RETAINED; // no-warning
1386 - (MyStringTy) returnsAnOwnedTypedString NS_RETURNS_RETAINED; // no-warning
1387 - (NSString*) newString NS_RETURNS_NOT_RETAINED; // no-warning
1388 - (NSString*) newString_auto NS_RETURNS_AUTORELEASED; // no-warning
1389 - (NSString*) newStringNoAttr;
1390 - (int) returnsAnOwnedInt NS_RETURNS_RETAINED; // expected-warning{{'ns_returns_retained' attribute only applies to methods that return an Objective-C object}}
1391 - (id) pseudoInit NS_CONSUMES_SELF NS_RETURNS_RETAINED;
1392 + (void) consume:(id) NS_CONSUMED x;
1393 + (void) consume2:(id) CF_CONSUMED x;
1396 static int ownership_attribute_doesnt_go_here NS_RETURNS_RETAINED; // expected-warning{{'ns_returns_retained' attribute only applies to functions and methods}}
1398 void test_attr_1(TestOwnershipAttr *X) {
1399 NSString *str = [X returnsAnOwnedString]; // expected-warning{{leak}}
1402 void test_attr_1b(TestOwnershipAttr *X) {
1403 NSString *str = [X returnsAnOwnedCFString]; // expected-warning{{leak}}
1406 void test_attr1c(TestOwnershipAttr *X) {
1407 NSString *str = [X newString]; // no-warning
1408 NSString *str2 = [X newStringNoAttr]; // expected-warning{{leak}}
1409 NSString *str3 = [X newString_auto]; // no-warning
1410 NSString *str4 = [[X newString_auto] retain]; // expected-warning {{leak}}
1413 void testattr2_a(void) {
1414 TestOwnershipAttr *x = [TestOwnershipAttr alloc]; // expected-warning{{leak}}
1417 void testattr2_b(void) {
1418 TestOwnershipAttr *x = [[TestOwnershipAttr alloc] pseudoInit]; // expected-warning{{leak}}
1421 void testattr2_b_11358224_self_assign_looses_the_leak(void) {
1422 TestOwnershipAttr *x = [[TestOwnershipAttr alloc] pseudoInit];// expected-warning{{leak}}
1426 void testattr2_c(void) {
1427 TestOwnershipAttr *x = [[TestOwnershipAttr alloc] pseudoInit]; // no-warning
1431 void testattr3(void) {
1432 TestOwnershipAttr *x = [TestOwnershipAttr alloc]; // no-warning
1433 [TestOwnershipAttr consume:x];
1434 TestOwnershipAttr *y = [TestOwnershipAttr alloc]; // no-warning
1435 [TestOwnershipAttr consume2:y];
1438 void consume_ns(id NS_CONSUMED x);
1439 void consume_cf(id CF_CONSUMED x);
1441 void testattr4(void) {
1442 TestOwnershipAttr *x = [TestOwnershipAttr alloc]; // no-warning
1444 TestOwnershipAttr *y = [TestOwnershipAttr alloc]; // no-warning
1448 @interface TestOwnershipAttr2 : NSObject
1449 - (NSString*) newString NS_RETURNS_NOT_RETAINED; // no-warning
1452 @implementation TestOwnershipAttr2
1453 - (NSString*) newString {
1454 return [NSString alloc]; // expected-warning {{Potential leak of an object}}
1458 @interface MyClassTestCFAttr : NSObject {}
1459 - (NSDate*) returnsCFRetained CF_RETURNS_RETAINED;
1460 - (CFDateRef) returnsCFRetainedAsCF CF_RETURNS_RETAINED;
1461 - (CFDateRef) newCFRetainedAsCF CF_RETURNS_NOT_RETAINED;
1462 - (CFDateRef) newCFRetainedAsCFNoAttr CF_RETURNS_RETAINED;
1463 - (NSDate*) alsoReturnsRetained;
1464 - (CFDateRef) alsoReturnsRetainedAsCF CF_RETURNS_NOT_RETAINED;
1465 - (NSDate*) returnsNSRetained NS_RETURNS_RETAINED;
1469 CFDateRef returnsRetainedCFDate(void) {
1470 return CFDateCreate(0, CFAbsoluteTimeGetCurrent());
1473 @implementation MyClassTestCFAttr
1474 - (NSDate*) returnsCFRetained {
1475 return (NSDate*) returnsRetainedCFDate(); // No leak.
1478 - (CFDateRef) returnsCFRetainedAsCF {
1479 return returnsRetainedCFDate(); // No leak.
1482 - (CFDateRef) newCFRetainedAsCF {
1483 return (CFDateRef)[(id)[self returnsCFRetainedAsCF] autorelease];
1486 - (CFDateRef) newCFRetainedAsCFNoAttr {
1487 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}}
1490 - (NSDate*) alsoReturnsRetained {
1491 return (NSDate*) returnsRetainedCFDate(); // expected-warning{{leak}}
1494 - (CFDateRef) alsoReturnsRetainedAsCF {
1495 return returnsRetainedCFDate(); // expected-warning{{leak}}
1499 - (NSDate*) returnsNSRetained {
1500 return (NSDate*) returnsRetainedCFDate(); // no-warning
1504 //===----------------------------------------------------------------------===//
1505 // Test that leaks post-dominated by "panic" functions are not reported.
1507 // <rdar://problem/5905851> do not report a leak when post-dominated by a call
1508 // to a noreturn or panic function
1509 //===----------------------------------------------------------------------===//
1511 void panic(void) __attribute__((noreturn));
1512 void panic_not_in_hardcoded_list(void) __attribute__((noreturn));
1514 void test_panic_negative(void) {
1516 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // expected-warning{{leak}}
1519 void test_panic_positive(void) {
1521 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // no-warning
1525 void test_panic_neg_2(int x) {
1527 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // expected-warning{{leak}}
1532 void test_panic_pos_2(int x) {
1534 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // no-warning
1538 // This showed up in <rdar://problem/7796563>, where we silently missed checking
1539 // the function type for noreturn. "panic()" is a hard-coded known panic function
1540 // that isn't always noreturn.
1541 panic_not_in_hardcoded_list();
1545 //===----------------------------------------------------------------------===//
1546 // Test uses of blocks (closures)
1547 //===----------------------------------------------------------------------===//
1549 void test_blocks_1_pos(void) {
1550 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1554 void test_blocks_1_indirect_release(void) {
1555 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1556 ^{ [number release]; }();
1559 void test_blocks_1_indirect_retain(void) {
1560 // Eventually this should be reported as a leak.
1561 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1562 ^{ [number retain]; }();
1565 void test_blocks_1_indirect_release_via_call(void) {
1566 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1567 ^(NSObject *o){ [o release]; }(number);
1570 void test_blocks_1_indirect_retain_via_call(void) {
1571 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning {{leak}}
1572 ^(NSObject *o){ [o retain]; }(number);
1575 //===--------------------------------------------------------------------===//
1576 // Test sending message to super that returns an object alias. Previously
1577 // this caused a crash in the analyzer.
1578 //===--------------------------------------------------------------------===//
1580 @interface Rdar8015556 : NSObject {} @end
1581 @implementation Rdar8015556
1583 return [super retain];
1587 // <rdar://problem/8272168> - Correcly handle Class<...> in Cocoa Conventions
1590 @protocol Prot_R8272168 @end
1591 Class <Prot_R8272168> GetAClassThatImplementsProt_R8272168(void);
1592 void r8272168(void) {
1593 GetAClassThatImplementsProt_R8272168();
1596 // Test case for <rdar://problem/8356342>, which in the past triggered
1597 // a false positive.
1598 @interface RDar8356342
1599 - (NSDate*) rdar8356342:(NSDate *)inValue;
1602 @implementation RDar8356342
1603 - (NSDate*) rdar8356342:(NSDate*)inValue {
1604 NSDate *outValue = inValue;
1606 outValue = [[NSDate alloc] init]; // no-warning
1608 if (outValue != inValue)
1609 [outValue autorelease];
1615 // <rdar://problem/8724287> - This test case previously crashed because
1616 // of a bug in BugReporter.
1617 extern const void *CFDictionaryGetValue(CFDictionaryRef theDict, const void *key) CF_RETURNS_NOT_RETAINED;
1618 typedef struct __CFError * CFErrorRef;
1619 extern const CFStringRef kCFErrorUnderlyingErrorKey;
1620 extern CFDictionaryRef CFErrorCopyUserInfo(CFErrorRef err) CF_RETURNS_RETAINED;
1621 static void rdar_8724287(CFErrorRef error)
1623 CFErrorRef error_to_dump;
1625 error_to_dump = error;
1626 while (error_to_dump != ((void*)0)) {
1627 CFDictionaryRef info;
1629 info = CFErrorCopyUserInfo(error_to_dump); // expected-warning{{Potential leak of an object}}
1631 if (info != ((void*)0)) {
1634 error_to_dump = (CFErrorRef) CFDictionaryGetValue(info, kCFErrorUnderlyingErrorKey);
1638 // <rdar://problem/9234108> - Make sure the model applies cf_consumed
1639 // correctly in argument positions besides the first.
1641 CF_IMPLICIT_BRIDGING_ENABLED
1643 extern void *CFStringCreate(void);
1645 CF_IMPLICIT_BRIDGING_DISABLED
1647 extern void rdar_9234108_helper(void *key, void * CF_CONSUMED value);
1648 void rdar_9234108(void) {
1649 rdar_9234108_helper(0, CFStringCreate());
1652 // <rdar://problem/9726279> - Make sure that objc_method_family works
1653 // to override naming conventions.
1658 typedef struct TwoDoubles TwoDoubles;
1660 @interface NSValue (Mine)
1661 - (id)_prefix_initWithTwoDoubles:(TwoDoubles)twoDoubles __attribute__((objc_method_family(init)));
1664 @implementation NSValue (Mine)
1665 - (id)_prefix_initWithTwoDoubles:(TwoDoubles)twoDoubles
1671 void rdar9726279(void) {
1672 TwoDoubles twoDoubles = { 0.0, 0.0 };
1673 NSValue *value = [[NSValue alloc] _prefix_initWithTwoDoubles:twoDoubles];
1677 // <rdar://problem/9732321>
1678 // Test camelcase support for CF conventions. While Core Foundation APIs
1679 // don't use camel casing, other code is allowed to use it.
1680 CFArrayRef camelcase_create_1(void) {
1681 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1684 CFArrayRef camelcase_createno(void) {
1685 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1688 CFArrayRef camelcase_copy(void) {
1689 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1692 CFArrayRef camelcase_copying(void) {
1693 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1696 CFArrayRef copyCamelCase(void) {
1697 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1700 CFArrayRef __copyCamelCase(void) {
1701 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1704 CFArrayRef __createCamelCase(void) {
1705 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1708 CFArrayRef camel_create(void) {
1709 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1713 CFArrayRef camel_creat(void) {
1714 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1717 CFArrayRef camel_copy(void) {
1718 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1721 CFArrayRef camel_copyMachine(void) {
1722 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1725 CFArrayRef camel_copymachine(void) {
1726 return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1729 // rdar://problem/8024350
1733 @interface F18 : NSObject<F18P> @end
1735 - (id) clone NS_RETURNS_RETAINED;
1745 void rdar6582778(void) {
1746 CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
1747 CFTypeRef vals[] = { CFDateCreate(0, t) }; // expected-warning {{leak}}
1752 void rdar6582778_2(void) {
1753 CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
1754 global = CFDateCreate(0, t); // no-warning
1757 // <rdar://problem/10232019> - Test that objects passed to containers
1758 // are marked "escaped".
1760 void rdar10232019(void) {
1761 NSMutableArray *array = [NSMutableArray array];
1763 NSString *string = [[NSString alloc] initWithUTF8String:"foo"];
1764 [array addObject:string];
1767 NSString *otherString = [string stringByAppendingString:@"bar"]; // no-warning
1768 NSLog(@"%@", otherString);
1771 void rdar10232019_positive(void) {
1772 NSMutableArray *array = [NSMutableArray array];
1774 NSString *string = [[NSString alloc] initWithUTF8String:"foo"];
1777 NSString *otherString = [string stringByAppendingString:@"bar"]; // expected-warning {{Reference-counted object is used after it is release}}
1778 NSLog(@"%@", otherString);
1781 // RetainCountChecker support for XPC.
1782 // <rdar://problem/9658496>
1783 typedef void * xpc_object_t;
1784 xpc_object_t _CFXPCCreateXPCObjectFromCFObject(CFTypeRef cf);
1785 void xpc_release(xpc_object_t object);
1787 void rdar9658496(void) {
1790 cf = CFStringCreateWithCString( ((CFAllocatorRef)0), "test", kCFStringEncodingUTF8 ); // no-warning
1791 xpc = _CFXPCCreateXPCObjectFromCFObject( cf );
1796 // Support annotations with method families.
1797 @interface RDar10824732 : NSObject
1798 - (instancetype)initWithObj:(id CF_CONSUMED)obj;
1801 @implementation RDar10824732
1802 - (instancetype)initWithObj:(id)obj {
1804 return [super init];
1808 void rdar_10824732(void) {
1810 NSString *obj = @"test";
1811 RDar10824732 *foo = [[RDar10824732 alloc] initWithObj:obj]; // no-warning
1816 // Stop tracking objects passed to functions, which take callbacks as parameters.
1818 typedef int (*CloseCallback) (void *);
1819 void ReaderForIO(CloseCallback ioclose, void *ioctx);
1820 int IOClose(void *context);
1822 @protocol SInS <NSObject>
1825 @interface radar10973977 : NSObject
1830 @implementation radar10973977
1833 id<SInS> inputS = [[self inputS] retain];
1834 ReaderForIO(IOClose, inputS);
1842 // Object escapes through a selector callback: radar://11398514
1844 @interface MySheetController
1846 - (void)showDoSomethingSheetAction:(id)action;
1847 - (void)sheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo;
1850 @implementation MySheetController
1851 - (id<SInS>)inputS {
1854 - (void)showDoSomethingSheetAction:(id)action {
1855 id<SInS> inputS = [[self inputS] retain];
1859 didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:)
1860 contextInfo:(void *)inputS]; // no - warning
1862 - (void)sheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo {
1864 id contextObject = (id)contextInfo;
1865 [contextObject release];
1868 - (id)copyAutoreleaseRadar13081402 {
1869 id x = [[[NSString alloc] initWithUTF8String:"foo"] autorelease];
1871 return x; // no warning
1875 //===----------------------------------------------------------------------===//
1876 // Test returning allocated memory in a struct.
1878 // We currently don't have a general way to track pointers that "escape".
1879 // Here we test that RetainCountChecker doesn't get excited about returning
1880 // allocated CF objects in struct fields.
1881 //===----------------------------------------------------------------------===//
1882 void *malloc(size_t);
1883 struct rdar11104566 { CFStringRef myStr; };
1884 struct rdar11104566 test_rdar11104566(void) {
1885 CFStringRef cf = CFStringCreateWithCString( ((CFAllocatorRef)0), "test", kCFStringEncodingUTF8 ); // no-warning
1886 struct rdar11104566 V;
1888 return V; // no-warning
1891 struct rdar11104566 *test_2_rdar11104566(void) {
1892 CFStringRef cf = CFStringCreateWithCString( ((CFAllocatorRef)0), "test", kCFStringEncodingUTF8 ); // no-warning
1893 struct rdar11104566 *V = (struct rdar11104566 *) malloc(sizeof(*V));
1895 return V; // no-warning
1898 //===----------------------------------------------------------------------===//
1899 // ObjC literals support.
1900 //===----------------------------------------------------------------------===//
1902 void test_objc_arrays(void) {
1903 { // CASE ONE -- OBJECT IN ARRAY CREATED DIRECTLY
1904 NSObject *o = [[NSObject alloc] init];
1905 NSArray *a = [[NSArray alloc] initWithObjects:o, (void*)0]; // expected-warning {{leak}}
1911 { // CASE TWO -- OBJECT IN ARRAY CREATED BY DUPING AUTORELEASED ARRAY
1912 NSObject *o = [[NSObject alloc] init];
1913 NSArray *a1 = [NSArray arrayWithObjects:o, (void*)0];
1914 NSArray *a2 = [[NSArray alloc] initWithArray:a1]; // expected-warning {{leak}}
1920 { // CASE THREE -- OBJECT IN RETAINED @[]
1921 NSObject *o = [[NSObject alloc] init];
1922 NSArray *a3 = [@[o] retain]; // expected-warning {{leak}}
1928 { // CASE FOUR -- OBJECT IN ARRAY CREATED BY DUPING @[]
1929 NSObject *o = [[NSObject alloc] init];
1930 NSArray *a = [[NSArray alloc] initWithArray:@[o]]; // expected-warning {{leak}}
1937 { // CASE FIVE -- OBJECT IN RETAINED @{}
1938 NSValue *o = [[NSValue alloc] init];
1939 NSDictionary *a = [@{o : o} retain]; // expected-warning {{leak}}
1947 void test_objc_integer_literals(void) {
1948 id value = [@1 retain]; // expected-warning {{leak}}
1949 [value description];
1952 void test_objc_boxed_expressions(int x, const char *y) {
1953 id value = [@(x) retain]; // expected-warning {{leak}}
1954 [value description];
1956 value = [@(y) retain]; // expected-warning {{leak}}
1957 [value description];
1960 // Test NSLog doesn't escape tracked objects.
1961 void rdar11400885(int y)
1964 NSString *printString;
1966 printString = [[NSString alloc] init];
1968 printString = [[NSString alloc] init];
1969 NSLog(@"Once %@", printString);
1970 [printString release];
1971 NSLog(@"Again: %@", printString); // expected-warning {{Reference-counted object is used after it is released}}
1975 id makeCollectableNonLeak(void) {
1976 extern CFTypeRef CFCreateSomething(void);
1978 CFTypeRef object = CFCreateSomething(); // +1
1979 CFRetain(object); // +2
1980 id objCObject = NSMakeCollectable(object); // +2
1981 [objCObject release]; // +1
1982 return [objCObject autorelease]; // +0
1986 void consumeAndStopTracking(id NS_CONSUMED obj, void (^callback)(void));
1987 void CFConsumeAndStopTracking(CFTypeRef CF_CONSUMED obj, void (^callback)(void));
1989 void testConsumeAndStopTracking(void) {
1990 id retained = [@[] retain]; // +1
1991 consumeAndStopTracking(retained, ^{}); // no-warning
1993 id doubleRetained = [[@[] retain] retain]; // +2
1994 consumeAndStopTracking(doubleRetained, ^{
1995 [doubleRetained release];
1998 id unretained = @[]; // +0
1999 consumeAndStopTracking(unretained, ^{}); // expected-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
2002 void testCFConsumeAndStopTracking(void) {
2003 id retained = [@[] retain]; // +1
2004 CFConsumeAndStopTracking((CFTypeRef)retained, ^{}); // no-warning
2006 id doubleRetained = [[@[] retain] retain]; // +2
2007 CFConsumeAndStopTracking((CFTypeRef)doubleRetained, ^{
2008 [doubleRetained release];
2011 id unretained = @[]; // +0
2012 CFConsumeAndStopTracking((CFTypeRef)unretained, ^{}); // expected-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
2014 //===----------------------------------------------------------------------===//
2015 // Test 'pragma clang arc_cf_code_audited' support.
2016 //===----------------------------------------------------------------------===//
2018 typedef void *MyCFType;
2019 #pragma clang arc_cf_code_audited begin
2020 MyCFType CreateMyCFType(void);
2021 #pragma clang arc_cf_code_audited end
2023 void test_custom_cf(void) {
2024 MyCFType x = CreateMyCFType(); // expected-warning {{leak of an object stored into 'x'}}
2027 //===----------------------------------------------------------------------===//
2028 // Test calling CFPlugInInstanceCreate, which appears in CF but doesn't
2029 // return a CF object.
2030 //===----------------------------------------------------------------------===//
2032 void test_CFPlugInInstanceCreate(CFUUIDRef factoryUUID, CFUUIDRef typeUUID) {
2033 CFPlugInInstanceCreate(kCFAllocatorDefault, factoryUUID, typeUUID); // no-warning
2036 //===----------------------------------------------------------------------===//
2037 // PR14927: -drain only has retain-count semantics on NSAutoreleasePool.
2038 //===----------------------------------------------------------------------===//
2040 @interface PR14927 : NSObject
2044 void test_drain(void) {
2045 PR14927 *obj = [[PR14927 alloc] init];
2047 [obj release]; // no-warning
2050 //===----------------------------------------------------------------------===//
2051 // Allow cf_returns_retained and cf_returns_not_retained to mark a return
2052 // value as tracked, even if the object isn't a known CF type.
2053 //===----------------------------------------------------------------------===//
2055 MyCFType getCustom(void) __attribute__((cf_returns_not_retained));
2056 MyCFType makeCustom(void) __attribute__((cf_returns_retained));
2058 void testCustomReturnsRetained(void) {
2059 MyCFType obj = makeCustom(); // expected-warning {{leak of an object stored into 'obj'}}
2062 void testCustomReturnsNotRetained(void) {
2063 CFRelease(getCustom()); // expected-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
2066 //===----------------------------------------------------------------------===//
2067 // Don't print variables which are out of the current scope.
2068 //===----------------------------------------------------------------------===//
2069 @interface MyObj12706177 : NSObject
2070 -(instancetype)initX;
2071 +(void)test12706177;
2074 @implementation MyObj12706177
2075 -(instancetype)initX {
2078 self = [super init];
2081 +(void)test12706177 {
2082 id x = [[MyObj12706177 alloc] initX]; //expected-warning {{Potential leak of an object}}
2087 //===----------------------------------------------------------------------===//
2088 // <rdar://problem/13783514> xpc_connection_set_finalizer_f
2089 //===----------------------------------------------------------------------===//
2091 typedef xpc_object_t xpc_connection_t;
2092 typedef void (*xpc_finalizer_t)(void *value);
2093 void xpc_connection_set_context(xpc_connection_t connection, void *ctx);
2094 void xpc_connection_set_finalizer_f(xpc_connection_t connection,
2095 xpc_finalizer_t finalizer);
2096 void releaseAfterXPC(void *context) {
2097 [(NSArray *)context release];
2100 void rdar13783514(xpc_connection_t connection) {
2101 xpc_connection_set_context(connection, [[NSMutableArray alloc] init]);
2102 xpc_connection_set_finalizer_f(connection, releaseAfterXPC);
2105 CFAttributedStringRef CFAttributedCreate(void *CFObj CF_CONSUMED) CF_RETURNS_RETAINED;
2108 @property (nonatomic) SEL action;
2109 @property (nonatomic, assign) id target;