[clang] Handle __declspec() attributes in using
[llvm-project.git] / clang / test / ARCMT / objcmt-arc-cf-annotations.m.result
blob33727329fe5ebfb1fe38d198136b76e900dab3bd
1 // RUN: rm -rf %t
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")
9 #else
10 #define CF_IMPLICIT_BRIDGING_ENABLED
11 #endif
12 #endif
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")
17 #else
18 #define CF_IMPLICIT_BRIDGING_DISABLED
19 #endif
20 #endif
22 #if __has_feature(attribute_ns_returns_retained)
23 #define NS_RETURNS_RETAINED __attribute__((ns_returns_retained))
24 #endif
25 #if __has_feature(attribute_cf_returns_retained)
26 #define CF_RETURNS_RETAINED __attribute__((cf_returns_retained))
27 #endif
28 #if __has_feature(attribute_ns_returns_not_retained)
29 #define NS_RETURNS_NOT_RETAINED __attribute__((ns_returns_not_retained))
30 #endif
31 #if __has_feature(attribute_cf_returns_not_retained)
32 #define CF_RETURNS_NOT_RETAINED __attribute__((cf_returns_not_retained))
33 #endif
34 #if __has_feature(attribute_ns_consumes_self)
35 #define NS_CONSUMES_SELF __attribute__((ns_consumes_self))
36 #endif
37 #if __has_feature(attribute_ns_consumed)
38 #define NS_CONSUMED __attribute__((ns_consumed))
39 #endif
40 #if __has_feature(attribute_cf_consumed)
41 #define CF_CONSUMED __attribute__((cf_consumed))
42 #endif
43 #if __has_attribute(ns_returns_autoreleased)
44 #define NS_RETURNS_AUTORELEASED __attribute__((ns_returns_autoreleased))
45 #endif
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;
67 typedef struct {
68     CFIndex location;
69     CFIndex length;
70 } CFRange;
71 static __inline__ __attribute__((always_inline)) CFRange CFRangeMake(CFIndex loc, CFIndex len) {
72     CFRange range;
73     range.location = loc;
74     range.length = len;
75     return range;
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);
91 typedef struct {
93 CFArrayCallBacks;
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);
100 typedef struct {
102 CFDictionaryKeyCallBacks;
103 extern const CFDictionaryKeyCallBacks kCFTypeDictionaryKeyCallBacks;
104 typedef struct {
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;
112 enum {
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;
126 enum {
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;
142 @protocol NSObject
143 - (BOOL)isEqual:(id)object;
144 - (id)retain;
145 - (oneway void)release;
146 - (id)autorelease;
147 - (NSString *)description;
148 - (instancetype)init;
149 @end
150 @protocol NSCopying 
151 - (id)copyWithZone:(NSZone *)zone;
152 @end
153 @protocol NSMutableCopying  - (id)mutableCopyWithZone:(NSZone *)zone;
154 @end
155 @protocol NSCoding  - (void)encodeWithCoder:(NSCoder *)aCoder;
156 @end
157 @interface NSObject <NSObject> {}
158 + (id)allocWithZone:(NSZone *)zone;
159 + (id)alloc;
160 + (id)new;
161 - (void)dealloc;
162 @end
163 @interface NSObject (NSCoderMethods)
164 - (id)awakeAfterUsingCoder:(NSCoder *)aDecoder;
165 @end
166 extern id NSAllocateObject(Class aClass, NSUInteger extraBytes, NSZone *zone);
167 typedef struct {
169 NSFastEnumerationState;
170 @protocol NSFastEnumeration 
171 - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len;
172 @end
173 @class NSString, NSDictionary;
174 @interface NSValue : NSObject <NSCopying, NSCoding>  - (void)getValue:(void *)value;
175 @end
176 @interface NSNumber : NSValue
177 - (char)charValue;
178 - (instancetype)initWithInt:(int)value;
179 + (NSNumber *)numberWithInt:(int)value;
180 @end
181 @class NSString;
182 @interface NSArray : NSObject <NSCopying, NSMutableCopying, NSCoding, NSFastEnumeration>
183 - (NSUInteger)count;
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 {
193 - (void)drain;
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>
210 - (NSUInteger)count;
211 + (instancetype)dictionaryWithObjects:(NSArray *)objects forKeys:(NSArray *)keys;
212 + (instancetype)dictionaryWithObjects:(const id [])objects forKeys:(const id <NSCopying> [])keys count:(NSUInteger)cnt;
213 @end
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;
218 struct CGSize {
220 typedef struct CGSize CGSize;
221 struct CGRect {
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;
275 @end   enum {
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> {
282 @end 
283 typedef struct {
285 CVTimeStamp;
286 @interface CIImage : NSObject <NSCoding, NSCopying> {
288 typedef int CIFormat;
289 @end  enum {
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;
308 @end    enum {
309 ICEXIFOrientation1 = 1,     ICEXIFOrientation2 = 2,     ICEXIFOrientation3 = 3,     ICEXIFOrientation4 = 4,     ICEXIFOrientation5 = 5,     ICEXIFOrientation6 = 6,     ICEXIFOrientation7 = 7,     ICEXIFOrientation8 = 8, };
310 @class ICDevice;
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;
315 @end
317 typedef long unsigned int __darwin_size_t;
318 typedef __darwin_size_t size_t;
319 typedef unsigned long CFTypeID;
320 struct CGPoint {
321   CGFloat x;
322   CGFloat y;
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;
355 @end
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;
362 extern
363 void *CFPlugInInstanceCreate(CFAllocatorRef allocator, CFUUIDRef factoryUUID, CFUUIDRef typeUUID);
365 //===----------------------------------------------------------------------===//
366 // Test cases.
367 //===----------------------------------------------------------------------===//
369 CFAbsoluteTime f1(void) {
370   CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
371   CFDateRef date = CFDateCreate(0, t);
372   CFRetain(date);
373   CFRelease(date);
374   CFDateGetAbsoluteTime(date); // no-warning
375   CFRelease(date);
376   t = CFDateGetAbsoluteTime(date);   // expected-warning{{Reference-counted object is used after it is released}}
377   return t;
380 CFAbsoluteTime f2(void) {
381   CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
382   CFDateRef date = CFDateCreate(0, t);  
383   [((NSDate*) date) retain];
384   CFRelease(date);
385   CFDateGetAbsoluteTime(date); // no-warning
386   [((NSDate*) date) release];
387   t = CFDateGetAbsoluteTime(date);   // expected-warning{{Reference-counted object is used after it is released}}
388   return t;
392 NSDate* global_x;
394 // Test to see if we suppress an error when we store the pointer
395 // to a global.
397 CFAbsoluteTime f3(void) {
398   CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
399   CFDateRef date = CFDateCreate(0, t);  
400   [((NSDate*) date) retain];
401   CFRelease(date);
402   CFDateGetAbsoluteTime(date); // no-warning
403   global_x = (NSDate*) date;  
404   [((NSDate*) date) release];
405   t = CFDateGetAbsoluteTime(date);   // no-warning
406   return t;
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 //---------------------------------------------------------------------------
414 // Test a leak.
416 CFAbsoluteTime f5(int x) {  
417   CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
418   CFDateRef date = CFDateCreate(0, t); // expected-warning{{leak}}
419   
420   if (x)
421     CFRelease(date);
422   
423   return t;
426 // Test a leak involving the return.
428 CFDateRef f6(int x) {  
429   CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent());  // expected-warning{{leak}}
430   CFRetain(date);
431   return date;
434 // Test a leak involving an overwrite.
436 CFDateRef f7(void) {
437   CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent());  //expected-warning{{leak}}
438   CFRetain(date);
439   date = CFDateCreate(0, CFAbsoluteTimeGetCurrent()); // expected-warning {{leak}}
440   return date;
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
453 CFDateRef f8(void) {
454   CFDateRef date = MyDateCreate(); // expected-warning{{leak}}
455   CFRetain(date);  
456   return date;
459 __attribute__((cf_returns_retained)) CFDateRef f9(void) {
460   CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent()); // no-warning
461   int *p = 0;
462   // When allocations fail, CFDateCreate can return null.
463   if (!date) *p = 1; // expected-warning{{null}}
464   return date;
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");
474   
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"); 
480   
481   disk = DADiskCopyWholeDisk(d); // expected-warning{{leak}}
482   if (disk) NSLog(@"ok");
483     
484   DADissenterRef dissenter = DADissenterCreate(kCFAllocatorDefault,   // expected-warning{{leak}}
485                                                 kDAReturnSuccess, s);
486   if (dissenter) NSLog(@"ok");
487   
488   DASessionRef session = DASessionCreate(kCFAllocatorDefault);  // expected-warning{{leak}}
489   if (session) NSLog(@"ok");
492 // Test retain/release checker with CFString and CFMutableArray.
493 void f11(void) {
494   // Create the array.
495   CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
497   // Create a string.
498   CFStringRef s1 = CFStringCreateWithCString(0, "hello world",
499                                              kCFStringEncodingUTF8);
501   // Add the string to the array.
502   CFArrayAppendValue(A, s1);
503   
504   // Decrement the reference count.
505   CFRelease(s1); // no-warning
506   
507   // Get the string.  We don't own it.
508   s1 = (CFStringRef) CFArrayGetValueAtIndex(A, 0);
509   
510   // Release the array.
511   CFRelease(A); // no-warning
512   
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
527 void f12(void) {
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
555   while (1) {}
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.
566 void f15(void) {
567   // Create the array.
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) {
576   if (p)
577     return;
579   switch (x) {
580   case 0:
581     CFRelease(p);
582     break;
583   case 1:
584     CFRetain(p);
585     break;
586   case 2:
587     CFMakeCollectable(p);
588     break;
589   case 3:
590     CFAutorelease(p);
591     break;
592   default:
593     break;
594   }
597 // Test that an object is non-null after CFRetain/CFRelease/CFMakeCollectable/CFAutorelease.
598 void f17(int x, CFTypeRef p) {
599   switch (x) {
600   case 0:
601     CFRelease(p);
602     if (!p)
603       CFRelease(0); // no-warning
604     break;
605   case 1:
606     CFRetain(p);
607     if (!p)
608       CFRetain(0); // no-warning
609     break;
610   case 2:
611     CFMakeCollectable(p);
612     if (!p)
613       CFMakeCollectable(0); // no-warning
614     break;
615   case 3:
616     CFAutorelease(p);
617     if (!p)
618       CFAutorelease(0); // no-warning
619     break;
620   default:
621     break;
622   }
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 {
629   id myObj;
631 - (void)test_self_tracking;
632 @end
634 @implementation SelfIvarTest
635 - (void)test_self_tracking {
636   myObj = (id) CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
638 @end
640 // Test return of non-owned objects in contexts where an owned object
641 // is expected.
642 @interface TestReturnNotOwnedWhenExpectedOwned
643 - (NSString*)newString;
644 @end
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}}
651 @end
653 // <rdar://problem/6659160>
654 int isFoo(char c);
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
661   // conditions.
662   NSString *kind = [[NSString alloc] initWithUTF8String:inkind];  // expected-warning{{leak}}
663   
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
667   // isn't expected.
668   NSString *name = [NSString stringWithUTF8String:inname];
669   if(!name)
670     return;
672   const char *kindC = 0;
673   const char *nameC = 0;
674   
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
678   // up above.
679   
680   if(kind)
681     kindC = [kind UTF8String];
682   if(name)
683     nameC = [name UTF8String];
684   if(!isFoo(kindC[0])) // expected-warning{{null}}
685     return;
686   if(!isFoo(nameC[0])) // no-warning
687     return;
689   [kind release];
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
700 @end
702 // PR 3820 - Reason about calls to -dealloc
703 void pr3820_DeallocInsteadOfRelease(void)
705   id foo = [[NSString alloc] init]; // no-warning
706   [foo dealloc];
707   // foo is not leaked, since it has been deallocated.
710 void pr3820_ReleaseAfterDealloc(void)
712   id foo = [[NSString alloc] init];
713   [foo dealloc];
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];
722   [foo release];
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) {
732   NSString* name = 0;
733   if (s != 0) {
734     if (length > 0) {
735       while (length > 0) {
736         if (*s == ':') {
737           ++s;
738           --length;
739           name = [[NSString alloc] init]; // no-warning
740           break;
741         }
742         ++s;
743         --length;
744       }
745       if ((length == 0) && (name != 0)) {
746         [name release];
747         name = 0;
748       }
749       if (length == 0) { // no ':' found -> use it all as name
750         name = [[NSString alloc] init]; // no-warning
751       }
752     }
753   }
755   if (name != 0) {
756     [name release];
757   }
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> {
767     NSWindow *window;
769 @property (nonatomic, retain) NSWindow *window;
770 @end
772 @implementation rdar_6833332
773 @synthesize window;
774 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
775  NSMutableDictionary *dict = [[NSMutableDictionary dictionaryWithCapacity:4] retain]; // expected-warning{{leak}}
777  [dict setObject:@"foo" forKey:@"bar"];
779  NSLog(@"%@", dict);
781 - (void)dealloc {
782     [window release];
783     [super dealloc];
786 - (void)radar10102244 {
787  NSMutableDictionary *dict = [[NSMutableDictionary dictionaryWithCapacity:4] retain]; // expected-warning{{leak}} 
788  if (window) 
789    NSLog(@"%@", window);    
791 @end
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}}
801   [pool drain];
802   return 0;
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];
811     (void) pool;
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"];
823  [array release];
824  // Using 'array' here should be fine
825  NSLog(@"array = %@\n", array); // no-warning
826  // Now the array is released
827  [dictionary release];
828  [pool drain];
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;
841 @end
843 @implementation RDar6877235
844 - (CFTypeRef)_copyCFTypeRef {
845   return [[NSString alloc] init]; // no-warning
847 - (OtherRef)_copyOtherRef {
848   return [[NSString alloc] init]; // no-warning
850 @end
852 //===----------------------------------------------------------------------===//
853 // <rdar://problem/6320065> false positive - init method returns an object
854 // owned by caller
855 //===----------------------------------------------------------------------===//
857 @interface RDar6320065 : NSObject {
858   NSString *_foo;
860 - (instancetype)initReturningNewClass;
861 - (id)_initReturningNewClassBad;
862 - (instancetype)initReturningNewClassBad2;
863 @end
865 @interface RDar6320065Subclass : RDar6320065
866 @end
868 @implementation RDar6320065
869 - (instancetype)initReturningNewClass {
870   [self release];
871   self = [[RDar6320065Subclass alloc] init]; // no-warning
872   return self;
874 - (id)_initReturningNewClassBad {
875   [self release];
876   [[RDar6320065Subclass alloc] init]; // expected-warning {{leak}}
877   return self;
879 - (instancetype)initReturningNewClassBad2 {
880   [self release];
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}}
885 @end
887 @implementation RDar6320065Subclass
888 @end
890 int RDar6320065_test(void) {
891   RDar6320065 *test = [[RDar6320065 alloc] init]; // no-warning
892   [test release];
893   return 0;
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
907 @end
909 //===----------------------------------------------------------------------===//
910 // <rdar://problem/6859457> [NSData dataWithBytesNoCopy] does not return a
911 //  retained object
912 //===----------------------------------------------------------------------===//
914 @interface RDar6859457 : NSObject {}
915 - (NSString*) NoCopyString;
916 - (NSString*) noCopyString;
917 @end
919 @implementation RDar6859457 
920 - (NSString*) NoCopyString { return [[NSString alloc] init]; } // expected-warning{{leak}}
921 - (NSString*) noCopyString { return [[NSString alloc] init]; } // expected-warning{{leak}}
922 @end
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
933 //  return
934 //===----------------------------------------------------------------------===//
936 static void PR4230(void)
938   NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // no-warning
939   NSString *object = [[[NSString alloc] init] autorelease]; // no-warning
940   return;
943 static void PR4230_new(void)
945   NSAutoreleasePool *pool = [NSAutoreleasePool new]; // no-warning
946   NSString *object = [[[NSString alloc] init] autorelease]; // no-warning
947   return;
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
956 @end
958 @implementation TestNullIdentifier
959 + (id):(int)x, ... {
960   return [[NSString alloc] init]; // expected-warning{{leak}}
962 @end
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;
975 @end
977 @implementation RDar6893565
978 -(TD6893565)newThing {  
979   return (TD6893565) [[NSString alloc] init]; // no-warning
981 @end
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 
1007 //                          checker
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) {
1056     
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
1073   signed z = 1;
1074   CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z);
1075   if (value) {
1076     CFDictionaryAddValue(x, val_key, (void*)value); // no-warning
1077     CFRelease(value);
1078     CFDictionaryAddValue(y, val_key, (void*)value); // no-warning
1079   }
1082 // <rdar://problem/6560661>
1083 // Same issue, except with "AppendValue" functions.
1084 void rdar_6560661(CFMutableArrayRef x) {
1085   signed z = 1;
1086   CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z);
1087   // CFArrayAppendValue keeps a reference to value.
1088   CFArrayAppendValue(x, value);
1089   CFRelease(value);
1090   CFRetain(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);
1099   CFRelease(string);
1100   NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1101   CFAttributedStringSetAttribute(attrString, CFRangeMake(0, 1), str, number);
1102   [number release];
1103   [number retain];
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,
1116      x,  // Start color
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
1122   }; // End color
1123   
1124   CGGradientRef myGradient =
1125     CGGradientCreateWithColorComponents(CGColorSpaceCreateDeviceRGB(), // expected-warning{{leak}}
1126       components, locations, num_locations);
1128   CGContextDrawLinearGradient(myContext, myGradient, myStartPoint, myEndPoint,
1129                               0);
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,
1138      x,  // Start color
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
1144   }; // End color
1145   
1146   CGGradientRef myGradient =
1147    CGGradientCreateWithColorComponents(CGColorSpaceCreateDeviceRGB(), components, locations, num_locations); // expected-warning 2 {{leak}}
1149   CGContextDrawLinearGradient(myContext, myGradient, myStartPoint, myEndPoint,
1150                               0);
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) {
1177   [((id) p) release];
1178   return 0;
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
1190 // local storage
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,
1220             size_t width,
1221             size_t height,
1222             OSType pixelFormatType,
1223             void *baseAddress,
1224             size_t bytesPerRow,
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,
1233         size_t width,
1234         size_t height,
1235         OSType pixelFormatType,
1236         void *dataPtr,
1237         size_t dataSize,
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,
1249             size_t width,
1250             size_t height,
1251             OSType pixelFormatType,
1252             void *baseAddress,
1253             size_t bytesPerRow,
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,
1261                       size_t bytesPerRow,
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
1270   
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) {
1284     
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);
1304     
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 {}
1334 - (id) new_stuff;
1335 @end
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
1343   [y release];
1346 //===----------------------------------------------------------------------===//
1347 // <rdar://problem/7306898> clang thinks [NSCursor dragCopyCursor] returns a
1348 //                          retained reference
1349 //===----------------------------------------------------------------------===//
1351 @interface NSCursor : NSObject
1352 + (NSCursor *)dragCopyCursor;
1353 @end
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;
1381 @protocol FooP;
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;
1394 @end
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}}
1423   x = x;
1426 void testattr2_c(void) {
1427   TestOwnershipAttr *x = [[TestOwnershipAttr alloc] pseudoInit]; // no-warning
1428   [x release];
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
1443   consume_ns(x);
1444   TestOwnershipAttr *y = [TestOwnershipAttr alloc]; // no-warning
1445   consume_cf(y);
1448 @interface TestOwnershipAttr2 : NSObject
1449 - (NSString*) newString NS_RETURNS_NOT_RETAINED; // no-warning
1450 @end
1452 @implementation TestOwnershipAttr2
1453 - (NSString*) newString {
1454   return [NSString alloc]; // expected-warning {{Potential leak of an object}}
1456 @end
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;
1466 @end
1468 CF_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
1502 @end
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) {
1515   signed z = 1;
1516   CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z);  // expected-warning{{leak}}
1519 void test_panic_positive(void) {
1520   signed z = 1;
1521   CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // no-warning
1522   panic();
1525 void test_panic_neg_2(int x) {
1526   signed z = 1;
1527   CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // expected-warning{{leak}}
1528   if (x)
1529     panic();
1532 void test_panic_pos_2(int x) {
1533   signed z = 1;
1534   CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // no-warning
1535   if (x)
1536     panic();
1537   if (!x) {
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();
1542   }
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}}
1551   ^{}();
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
1582 - (id)retain {
1583   return [super retain];
1585 @end
1587 // <rdar://problem/8272168> - Correcly handle Class<...> in Cocoa Conventions
1588 // detector.
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;
1600 @end
1602 @implementation RDar8356342
1603 - (NSDate*) rdar8356342:(NSDate*)inValue {
1604   NSDate *outValue = inValue;
1605   if (outValue == 0)
1606     outValue = [[NSDate alloc] init]; // no-warning
1608   if (outValue != inValue)
1609     [outValue autorelease];
1611   return outValue;
1613 @end
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)) {
1632         }
1634         error_to_dump = (CFErrorRef) CFDictionaryGetValue(info, kCFErrorUnderlyingErrorKey);
1635     }
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.
1654 struct TwoDoubles {
1655   double one;
1656   double two;
1658 typedef struct TwoDoubles TwoDoubles;
1660 @interface NSValue (Mine)
1661 - (id)_prefix_initWithTwoDoubles:(TwoDoubles)twoDoubles __attribute__((objc_method_family(init)));
1662 @end
1664 @implementation NSValue (Mine)
1665 - (id)_prefix_initWithTwoDoubles:(TwoDoubles)twoDoubles
1667   return [self init];
1669 @end
1671 void rdar9726279(void) {
1672   TwoDoubles twoDoubles = { 0.0, 0.0 };
1673   NSValue *value = [[NSValue alloc] _prefix_initWithTwoDoubles:twoDoubles];
1674   [value release];
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
1730 @protocol F18P
1731 - (id) clone;
1732 @end
1733 @interface F18 : NSObject<F18P> @end
1734 @interface F18(Cat)
1735 - (id) clone NS_RETURNS_RETAINED;
1736 @end
1738 @implementation F18
1739 - (id) clone {
1740   return [F18 alloc];
1742 @end
1744 // Radar 6582778.
1745 void rdar6582778(void) {
1746   CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
1747   CFTypeRef vals[] = { CFDateCreate(0, t) }; // expected-warning {{leak}}
1750 CFTypeRef global;
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];
1765   [string release];
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"];
1775   [string release];
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) {
1788   CFStringRef cf;
1789   xpc_object_t xpc;
1790   cf = CFStringCreateWithCString( ((CFAllocatorRef)0), "test", kCFStringEncodingUTF8 ); // no-warning
1791   xpc = _CFXPCCreateXPCObjectFromCFObject( cf );
1792   CFRelease(cf);
1793   xpc_release(xpc);
1796 // Support annotations with method families.
1797 @interface RDar10824732 : NSObject
1798 - (instancetype)initWithObj:(id CF_CONSUMED)obj;
1799 @end
1801 @implementation RDar10824732
1802 - (instancetype)initWithObj:(id)obj {
1803   [obj release];
1804   return [super init];
1806 @end
1808 void rdar_10824732(void) {
1809   @autoreleasepool {
1810     NSString *obj = @"test";
1811     RDar10824732 *foo = [[RDar10824732 alloc] initWithObj:obj]; // no-warning
1812     [foo release];
1813   }
1816 // Stop tracking objects passed to functions, which take callbacks as parameters.
1817 // radar://10973977
1818 typedef int (*CloseCallback) (void *);
1819 void ReaderForIO(CloseCallback ioclose, void *ioctx);
1820 int IOClose(void *context);
1822 @protocol SInS <NSObject>
1823 @end
1825 @interface radar10973977 : NSObject
1826 - (id<SInS>)inputS;
1827 - (void)reader;
1828 @end
1830 @implementation radar10973977
1831 - (void)reader
1833     id<SInS> inputS = [[self inputS] retain];
1834     ReaderForIO(IOClose, inputS);
1836 - (id<SInS>)inputS
1838     return 0;
1840 @end
1842 // Object escapes through a selector callback: radar://11398514
1843 extern id NSApp;
1844 @interface MySheetController
1845 - (id<SInS>)inputS;
1846 - (void)showDoSomethingSheetAction:(id)action;
1847 - (void)sheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo;
1848 @end
1850 @implementation MySheetController
1851 - (id<SInS>)inputS {
1852     return 0;
1854 - (void)showDoSomethingSheetAction:(id)action {
1855   id<SInS> inputS = [[self inputS] retain]; 
1856   [NSApp beginSheet:0
1857          modalForWindow:0
1858          modalDelegate:0
1859          didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:)
1860          contextInfo:(void *)inputS]; // no - warning
1862 - (void)sheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo {
1863    
1864       id contextObject = (id)contextInfo;
1865       [contextObject release];
1868 - (id)copyAutoreleaseRadar13081402 {
1869   id x = [[[NSString alloc] initWithUTF8String:"foo"] autorelease];
1870   [x retain];
1871   return x; // no warning
1874 @end
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;
1887   V.myStr = cf;
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));
1894   V->myStr = cf;
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}}
1906         [o release];
1907         [a description];
1908         [o description];
1909     }
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}}
1915         [o release];        
1916         [a2 description];
1917         [o description];
1918     }
1920     { // CASE THREE -- OBJECT IN RETAINED @[]
1921         NSObject *o = [[NSObject alloc] init];
1922         NSArray *a3 = [@[o] retain]; // expected-warning {{leak}}
1923         [o release];        
1924         [a3 description];
1925         [o description];
1926     }
1927     
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}}
1931         [o release];
1932         
1933         [a description];
1934         [o description];
1935     }
1936     
1937     { // CASE FIVE -- OBJECT IN RETAINED @{}
1938         NSValue *o = [[NSValue alloc] init];
1939         NSDictionary *a = [@{o : o} retain]; // expected-warning {{leak}}
1940         [o release];
1941         
1942         [a description];
1943         [o description];
1944     }
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)
1963   @autoreleasepool {
1964     NSString *printString;
1965     if(y > 2)
1966       printString = [[NSString alloc] init];
1967     else
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}}
1972   }
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];
1996   }); // no-warning
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];
2009   }); // no-warning
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 
2022     
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
2041 - (void)drain;
2042 @end
2044 void test_drain(void) {
2045   PR14927 *obj = [[PR14927 alloc] init];
2046   [obj drain];
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;
2072 @end
2073 static int Cond;
2074 @implementation MyObj12706177
2075 -(instancetype)initX {
2076   if (Cond)
2077     return 0;
2078   self = [super init];
2079   return self;
2081 +(void)test12706177 {
2082   id x = [[MyObj12706177 alloc] initX]; //expected-warning {{Potential leak of an object}}
2083   [x release]; 
2085 @end
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);
2103 } // no-warning
2105 CFAttributedStringRef CFAttributedCreate(void *CFObj CF_CONSUMED) CF_RETURNS_RETAINED;
2107 @interface Action
2108 @property (nonatomic) SEL action;
2109 @property (nonatomic, assign) id target;
2110 @end