[clang-format] Fix a bug in aligning comments above PPDirective (#72791)
[llvm-project.git] / clang / test / ARCMT / objcmt-arc-cf-annotations.m
blob47c83ac9e3dd550af7f7ff9a3433b23ebd84fcc5
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);
82 extern void CFRelease(CFTypeRef cf);
83 extern CFTypeRef CFAutorelease(CFTypeRef cf);
84 extern CFTypeRef CFMakeCollectable(CFTypeRef cf);
85 typedef struct {
87 CFArrayCallBacks;
88 extern const CFArrayCallBacks kCFTypeArrayCallBacks;
89 typedef const struct __CFArray * CFArrayRef;
90 typedef struct __CFArray * CFMutableArrayRef;
91 extern CFMutableArrayRef CFArrayCreateMutable(CFAllocatorRef allocator, CFIndex capacity, const CFArrayCallBacks *callBacks);
92 extern const void *CFArrayGetValueAtIndex(CFArrayRef theArray, CFIndex idx);
93 extern void CFArrayAppendValue(CFMutableArrayRef theArray, const void *value);
94 typedef struct {
96 CFDictionaryKeyCallBacks;
97 extern const CFDictionaryKeyCallBacks kCFTypeDictionaryKeyCallBacks;
98 typedef struct {
100 CFDictionaryValueCallBacks;
101 extern const CFDictionaryValueCallBacks kCFTypeDictionaryValueCallBacks;
102 typedef const struct __CFDictionary * CFDictionaryRef;
103 typedef struct __CFDictionary * CFMutableDictionaryRef;
104 extern CFMutableDictionaryRef CFDictionaryCreateMutable(CFAllocatorRef allocator, CFIndex capacity, const CFDictionaryKeyCallBacks *keyCallBacks, const CFDictionaryValueCallBacks *valueCallBacks);
105 typedef UInt32 CFStringEncoding;
106 enum {
107 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  };
108 extern CFStringRef CFStringCreateWithCString(CFAllocatorRef alloc, const char *cStr, CFStringEncoding encoding);
109 typedef double CFTimeInterval;
110 typedef CFTimeInterval CFAbsoluteTime;
111 extern CFAbsoluteTime CFAbsoluteTimeGetCurrent(void);
112 typedef const struct __CFDate * CFDateRef;
113 extern CFDateRef CFDateCreate(CFAllocatorRef allocator, CFAbsoluteTime at);
114 extern CFAbsoluteTime CFDateGetAbsoluteTime(CFDateRef theDate);
115 typedef __darwin_natural_t natural_t;
116 typedef natural_t mach_port_name_t;
117 typedef mach_port_name_t mach_port_t;
118 typedef int kern_return_t;
119 typedef kern_return_t mach_error_t;
120 enum {
121 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    };
122 typedef CFIndex CFNumberType;
123 typedef const struct __CFNumber * CFNumberRef;
124 extern CFNumberRef CFNumberCreate(CFAllocatorRef allocator, CFNumberType theType, const void *valuePtr);
125 typedef const struct __CFAttributedString *CFAttributedStringRef;
126 typedef struct __CFAttributedString *CFMutableAttributedStringRef;
127 extern CFAttributedStringRef CFAttributedStringCreate(CFAllocatorRef alloc, CFStringRef str, CFDictionaryRef attributes) ;
128 extern CFMutableAttributedStringRef CFAttributedStringCreateMutableCopy(CFAllocatorRef alloc, CFIndex maxLength, CFAttributedStringRef aStr) ;
129 extern void CFAttributedStringSetAttribute(CFMutableAttributedStringRef aStr, CFRange range, CFStringRef attrName, CFTypeRef value) ;
130 typedef signed char BOOL;
131 typedef unsigned long NSUInteger;
132 @class NSString, Protocol;
133 extern void NSLog(NSString *format, ...) __attribute__((format(__NSString__, 1, 2)));
134 typedef struct _NSZone NSZone;
135 @class NSInvocation, NSMethodSignature, NSCoder, NSString, NSEnumerator;
136 @protocol NSObject
137 - (BOOL)isEqual:(id)object;
138 - (id)retain;
139 - (oneway void)release;
140 - (id)autorelease;
141 - (NSString *)description;
142 - (id)init;
143 @end
144 @protocol NSCopying 
145 - (id)copyWithZone:(NSZone *)zone;
146 @end
147 @protocol NSMutableCopying  - (id)mutableCopyWithZone:(NSZone *)zone;
148 @end
149 @protocol NSCoding  - (void)encodeWithCoder:(NSCoder *)aCoder;
150 @end
151 @interface NSObject <NSObject> {}
152 + (id)allocWithZone:(NSZone *)zone;
153 + (id)alloc;
154 + (id)new;
155 - (void)dealloc;
156 @end
157 @interface NSObject (NSCoderMethods)
158 - (id)awakeAfterUsingCoder:(NSCoder *)aDecoder;
159 @end
160 extern id NSAllocateObject(Class aClass, NSUInteger extraBytes, NSZone *zone);
161 typedef struct {
163 NSFastEnumerationState;
164 @protocol NSFastEnumeration 
165 - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len;
166 @end
167 @class NSString, NSDictionary;
168 @interface NSValue : NSObject <NSCopying, NSCoding>  - (void)getValue:(void *)value;
169 @end
170 @interface NSNumber : NSValue
171 - (char)charValue;
172 - (id)initWithInt:(int)value;
173 + (NSNumber *)numberWithInt:(int)value;
174 @end
175 @class NSString;
176 @interface NSArray : NSObject <NSCopying, NSMutableCopying, NSCoding, NSFastEnumeration>
177 - (NSUInteger)count;
178 - (id)initWithObjects:(const id [])objects count:(NSUInteger)cnt;
179 + (id)arrayWithObject:(id)anObject;
180 + (id)arrayWithObjects:(const id [])objects count:(NSUInteger)cnt;
181 + (id)arrayWithObjects:(id)firstObj, ... __attribute__((sentinel(0,1)));
182 - (id)initWithObjects:(id)firstObj, ... __attribute__((sentinel(0,1)));
183 - (id)initWithArray:(NSArray *)array;
184 @end  @interface NSArray (NSArrayCreation)  + (id)array;
185 @end       @interface NSAutoreleasePool : NSObject {
187 - (void)drain;
188 @end extern NSString * const NSBundleDidLoadNotification;
189 typedef double NSTimeInterval;
190 @interface NSDate : NSObject <NSCopying, NSCoding>  - (NSTimeInterval)timeIntervalSinceReferenceDate;
191 @end            typedef unsigned short unichar;
192 @interface NSString : NSObject <NSCopying, NSMutableCopying, NSCoding>
193 - (NSUInteger)length;
194 - (NSString *)stringByAppendingString:(NSString *)aString;
195 - ( const char *)UTF8String;
196 - (id)initWithUTF8String:(const char *)nullTerminatedCString;
197 + (id)stringWithUTF8String:(const char *)nullTerminatedCString;
198 @end        @class NSString, NSURL, NSError;
199 @interface NSData : NSObject <NSCopying, NSMutableCopying, NSCoding>  - (NSUInteger)length;
200 + (id)dataWithBytesNoCopy:(void *)bytes length:(NSUInteger)length;
201 + (id)dataWithBytesNoCopy:(void *)bytes length:(NSUInteger)length freeWhenDone:(BOOL)b;
202 @end   @class NSLocale, NSDate, NSCalendar, NSTimeZone, NSError, NSArray, NSMutableDictionary;
203 @interface NSDictionary : NSObject <NSCopying, NSMutableCopying, NSCoding, NSFastEnumeration>
204 - (NSUInteger)count;
205 + (id)dictionaryWithObjects:(NSArray *)objects forKeys:(NSArray *)keys;
206 + (id)dictionaryWithObjects:(const id [])objects forKeys:(const id <NSCopying> [])keys count:(NSUInteger)cnt;
207 @end
208 @interface NSMutableDictionary : NSDictionary  - (void)removeObjectForKey:(id)aKey;
209 - (void)setObject:(id)anObject forKey:(id)aKey;
210 @end  @interface NSMutableDictionary (NSMutableDictionaryCreation)  + (id)dictionaryWithCapacity:(NSUInteger)numItems;
211 @end  typedef double CGFloat;
212 struct CGSize {
214 typedef struct CGSize CGSize;
215 struct CGRect {
217 typedef struct CGRect CGRect;
218 typedef mach_port_t io_object_t;
219 typedef char io_name_t[128];
220 typedef io_object_t io_iterator_t;
221 typedef io_object_t io_service_t;
222 typedef struct IONotificationPort * IONotificationPortRef;
223 typedef void (*IOServiceMatchingCallback)(  void * refcon,  io_iterator_t iterator );
224 io_service_t IOServiceGetMatchingService(  mach_port_t mainPort,  CFDictionaryRef matching );
225 kern_return_t IOServiceGetMatchingServices(  mach_port_t mainPort,  CFDictionaryRef matching,  io_iterator_t * existing );
226 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}}
227 kern_return_t IOServiceAddMatchingNotification(  IONotificationPortRef notifyPort,  const io_name_t notificationType,  CFDictionaryRef matching,         IOServiceMatchingCallback callback,         void * refCon,  io_iterator_t * notification );
228 CFMutableDictionaryRef IOServiceMatching(  const char * name );
229 CFMutableDictionaryRef IOServiceNameMatching(  const char * name );
230 CFMutableDictionaryRef IOBSDNameMatching(  mach_port_t mainPort,  uint32_t options,  const char * bsdName );
231 CFMutableDictionaryRef IOOpenFirmwarePathMatching(  mach_port_t mainPort,  uint32_t options,  const char * path );
232 CFMutableDictionaryRef IORegistryEntryIDMatching(  uint64_t entryID );
233 typedef struct __DASession * DASessionRef;
234 extern DASessionRef DASessionCreate( CFAllocatorRef allocator );
235 typedef struct __DADisk * DADiskRef;
236 extern DADiskRef DADiskCreateFromBSDName( CFAllocatorRef allocator, DASessionRef session, const char * name );
237 extern DADiskRef DADiskCreateFromIOMedia( CFAllocatorRef allocator, DASessionRef session, io_service_t media );
238 extern CFDictionaryRef DADiskCopyDescription( DADiskRef disk );
239 extern DADiskRef DADiskCopyWholeDisk( DADiskRef disk );
240 @interface NSTask : NSObject - (id)init;
241 @end                    typedef struct CGColorSpace *CGColorSpaceRef;
242 typedef struct CGImage *CGImageRef;
243 typedef struct CGLayer *CGLayerRef;
244 @interface NSResponder : NSObject <NSCoding> {
246 @end    @protocol NSAnimatablePropertyContainer      - (id)animator;
247 @end  extern NSString *NSAnimationTriggerOrderIn ;
248 @interface NSView : NSResponder  <NSAnimatablePropertyContainer>  {
250 @end @protocol NSValidatedUserInterfaceItem - (SEL)action;
251 @end   @protocol NSUserInterfaceValidations - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)anItem;
252 @end  @class NSDate, NSDictionary, NSError, NSException, NSNotification;
253 @class NSTextField, NSPanel, NSArray, NSWindow, NSImage, NSButton, NSError;
254 @interface NSApplication : NSResponder <NSUserInterfaceValidations> {
256 - (void)beginSheet:(NSWindow *)sheet modalForWindow:(NSWindow *)docWindow modalDelegate:(id)modalDelegate didEndSelector:(SEL)didEndSelector contextInfo:(void *)contextInfo;
257 @end   enum {
258 NSTerminateCancel = 0,         NSTerminateNow = 1,         NSTerminateLater = 2 };
259 typedef NSUInteger NSApplicationTerminateReply;
260 @protocol NSApplicationDelegate <NSObject> @optional        - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender;
261 @end  @class NSAttributedString, NSEvent, NSFont, NSFormatter, NSImage, NSMenu, NSText, NSView, NSTextView;
262 @interface NSCell : NSObject <NSCopying, NSCoding> {
264 @end 
265 typedef struct {
267 CVTimeStamp;
268 @interface CIImage : NSObject <NSCoding, NSCopying> {
270 typedef int CIFormat;
271 @end  enum {
272 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 };
273 typedef mach_error_t DAReturn;
274 typedef const struct __DADissenter * DADissenterRef;
275 extern DADissenterRef DADissenterCreate( CFAllocatorRef allocator, DAReturn status, CFStringRef string );
276 @interface CIContext: NSObject {
278 - (CGImageRef)createCGImage:(CIImage *)im fromRect:(CGRect)r;
279 - (CGImageRef)createCGImage:(CIImage *)im fromRect:(CGRect)r     format:(CIFormat)f colorSpace:(CGColorSpaceRef)cs;
280 - (CGLayerRef)createCGLayerWithSize:(CGSize)size info:(CFDictionaryRef)d;
281 @end extern NSString* const QCRendererEventKey;
282 @protocol QCCompositionRenderer - (NSDictionary*) attributes;
283 @end   @interface QCRenderer : NSObject <QCCompositionRenderer> {
285 - (id) createSnapshotImageOfType:(NSString*)type;
286 @end  extern NSString* const QCViewDidStartRenderingNotification;
287 @interface QCView : NSView <QCCompositionRenderer> {
289 - (id) createSnapshotImageOfType:(NSString*)type;
290 @end    enum {
291 ICEXIFOrientation1 = 1,     ICEXIFOrientation2 = 2,     ICEXIFOrientation3 = 3,     ICEXIFOrientation4 = 4,     ICEXIFOrientation5 = 5,     ICEXIFOrientation6 = 6,     ICEXIFOrientation7 = 7,     ICEXIFOrientation8 = 8, };
292 @class ICDevice;
293 @protocol ICDeviceDelegate <NSObject>  @required      - (void)didRemoveDevice:(ICDevice*)device;
294 @end extern NSString *const ICScannerStatusWarmingUp;
295 @class ICScannerDevice;
296 @protocol ICScannerDeviceDelegate <ICDeviceDelegate>  @optional       - (void)scannerDeviceDidBecomeAvailable:(ICScannerDevice*)scanner;
297 @end
299 typedef long unsigned int __darwin_size_t;
300 typedef __darwin_size_t size_t;
301 typedef unsigned long CFTypeID;
302 struct CGPoint {
303   CGFloat x;
304   CGFloat y;
306 typedef struct CGPoint CGPoint;
307 typedef struct CGGradient *CGGradientRef;
308 typedef uint32_t CGGradientDrawingOptions;
309 extern CFTypeID CGGradientGetTypeID(void);
310 extern CGGradientRef CGGradientCreateWithColorComponents(CGColorSpaceRef
311   space, const CGFloat components[], const CGFloat locations[], size_t count);
312 extern CGGradientRef CGGradientCreateWithColors(CGColorSpaceRef space,
313   CFArrayRef colors, const CGFloat locations[]);
314 extern CGGradientRef CGGradientRetain(CGGradientRef gradient);
315 extern void CGGradientRelease(CGGradientRef gradient);
316 typedef struct CGContext *CGContextRef;
317 extern void CGContextDrawLinearGradient(CGContextRef context,
318     CGGradientRef gradient, CGPoint startPoint, CGPoint endPoint,
319     CGGradientDrawingOptions options);
320 extern CGColorSpaceRef CGColorSpaceCreateDeviceRGB(void);
322 @interface NSMutableArray : NSObject
323 - (void)addObject:(id)object;
324 + (id)array;
325 @end
327 // This is how NSMakeCollectable is declared in the OS X 10.8 headers.
328 id NSMakeCollectable(CFTypeRef __attribute__((cf_consumed))) __attribute__((ns_returns_retained));
330 typedef const struct __CFUUID * CFUUIDRef;
332 extern
333 void *CFPlugInInstanceCreate(CFAllocatorRef allocator, CFUUIDRef factoryUUID, CFUUIDRef typeUUID);
335 //===----------------------------------------------------------------------===//
336 // Test cases.
337 //===----------------------------------------------------------------------===//
339 CFAbsoluteTime f1(void) {
340   CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
341   CFDateRef date = CFDateCreate(0, t);
342   CFRetain(date);
343   CFRelease(date);
344   CFDateGetAbsoluteTime(date); // no-warning
345   CFRelease(date);
346   t = CFDateGetAbsoluteTime(date);   // expected-warning{{Reference-counted object is used after it is released}}
347   return t;
350 CFAbsoluteTime f2(void) {
351   CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
352   CFDateRef date = CFDateCreate(0, t);  
353   [((NSDate*) date) retain];
354   CFRelease(date);
355   CFDateGetAbsoluteTime(date); // no-warning
356   [((NSDate*) date) release];
357   t = CFDateGetAbsoluteTime(date);   // expected-warning{{Reference-counted object is used after it is released}}
358   return t;
362 NSDate* global_x;
364 // Test to see if we suppress an error when we store the pointer
365 // to a global.
367 CFAbsoluteTime f3(void) {
368   CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
369   CFDateRef date = CFDateCreate(0, t);  
370   [((NSDate*) date) retain];
371   CFRelease(date);
372   CFDateGetAbsoluteTime(date); // no-warning
373   global_x = (NSDate*) date;  
374   [((NSDate*) date) release];
375   t = CFDateGetAbsoluteTime(date);   // no-warning
376   return t;
379 //---------------------------------------------------------------------------
380 // Test case 'f4' differs for region store and basic store.  See
381 // retain-release-region-store.m and retain-release-basic-store.m.
382 //---------------------------------------------------------------------------
384 // Test a leak.
386 CFAbsoluteTime f5(int x) {  
387   CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
388   CFDateRef date = CFDateCreate(0, t); // expected-warning{{leak}}
389   
390   if (x)
391     CFRelease(date);
392   
393   return t;
396 // Test a leak involving the return.
398 CFDateRef f6(int x) {  
399   CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent());  // expected-warning{{leak}}
400   CFRetain(date);
401   return date;
404 // Test a leak involving an overwrite.
406 CFDateRef f7(void) {
407   CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent());  //expected-warning{{leak}}
408   CFRetain(date);
409   date = CFDateCreate(0, CFAbsoluteTimeGetCurrent()); // expected-warning {{leak}}
410   return date;
413 // Generalization of Create rule.  MyDateCreate returns a CFXXXTypeRef, and
414 // has the word create.
415 CFDateRef MyDateCreate(void);
417 CFDateRef f8(void) {
418   CFDateRef date = MyDateCreate(); // expected-warning{{leak}}
419   CFRetain(date);  
420   return date;
423 __attribute__((cf_returns_retained)) CFDateRef f9(void) {
424   CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent()); // no-warning
425   int *p = 0;
426   // When allocations fail, CFDateCreate can return null.
427   if (!date) *p = 1; // expected-warning{{null}}
428   return date;
431 // Handle DiskArbitration API:
433 // http://developer.apple.com/DOCUMENTATION/DARWIN/Reference/DiscArbitrationFramework/
435 void f10(io_service_t media, DADiskRef d, CFStringRef s) {
436   DADiskRef disk = DADiskCreateFromBSDName(kCFAllocatorDefault, 0, "hello"); // expected-warning{{leak}}
437   if (disk) NSLog(@"ok");
438   
439   disk = DADiskCreateFromIOMedia(kCFAllocatorDefault, 0, media); // expected-warning{{leak}}
440   if (disk) NSLog(@"ok");
442   CFDictionaryRef dict = DADiskCopyDescription(d);  // expected-warning{{leak}}
443   if (dict) NSLog(@"ok"); 
444   
445   disk = DADiskCopyWholeDisk(d); // expected-warning{{leak}}
446   if (disk) NSLog(@"ok");
447     
448   DADissenterRef dissenter = DADissenterCreate(kCFAllocatorDefault,   // expected-warning{{leak}}
449                                                 kDAReturnSuccess, s);
450   if (dissenter) NSLog(@"ok");
451   
452   DASessionRef session = DASessionCreate(kCFAllocatorDefault);  // expected-warning{{leak}}
453   if (session) NSLog(@"ok");
456 // Test retain/release checker with CFString and CFMutableArray.
457 void f11(void) {
458   // Create the array.
459   CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
461   // Create a string.
462   CFStringRef s1 = CFStringCreateWithCString(0, "hello world",
463                                              kCFStringEncodingUTF8);
465   // Add the string to the array.
466   CFArrayAppendValue(A, s1);
467   
468   // Decrement the reference count.
469   CFRelease(s1); // no-warning
470   
471   // Get the string.  We don't own it.
472   s1 = (CFStringRef) CFArrayGetValueAtIndex(A, 0);
473   
474   // Release the array.
475   CFRelease(A); // no-warning
476   
477   // Release the string.  This is a bug.
478   CFRelease(s1); // expected-warning{{Incorrect decrement of the reference count}}
481 // PR 3337: Handle functions declared using typedefs.
482 typedef CFTypeRef CREATEFUN(void);
483 CFTypeRef MyCreateFun(void);
485 void f12(void) {
486   CFTypeRef o = MyCreateFun(); // expected-warning {{leak}}
489 void f13_autorelease(void) {
490   CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
491   [(id) A autorelease]; // no-warning
494 void f13_autorelease_b(void) {
495   CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
496   [(id) A autorelease];
497   [(id) A autorelease];
498 } // expected-warning{{Object autoreleased too many times}}
500 CFMutableArrayRef f13_autorelease_c(void) {
501   CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
502   [(id) A autorelease];
503   [(id) A autorelease]; 
504   return A; // expected-warning{{Object autoreleased too many times}}
507 CFMutableArrayRef f13_autorelease_d(void) {
508   CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
509   [(id) A autorelease];
510   [(id) A autorelease]; 
511   CFMutableArrayRef B = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning{{Object autoreleased too many times}}
512   CFRelease(B); // no-warning
513   while (1) {}
517 // This case exercises the logic where the leak site is the same as the allocation site.
518 void f14_leakimmediately(void) {
519   CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning{{leak}}
522 // Test that we track an allocated object beyond the point where the *name*
523 // of the variable storing the reference is no longer live.
524 void f15(void) {
525   // Create the array.
526   CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
527   CFMutableArrayRef *B = &A;
528   // At this point, the name 'A' is no longer live.
529   CFRelease(*B);  // no-warning
532 // Test when we pass NULL to CFRetain/CFRelease/CFMakeCollectable/CFAutorelease.
533 void f16(int x, CFTypeRef p) {
534   if (p)
535     return;
537   switch (x) {
538   case 0:
539     CFRelease(p);
540     break;
541   case 1:
542     CFRetain(p);
543     break;
544   case 2:
545     CFMakeCollectable(p);
546     break;
547   case 3:
548     CFAutorelease(p);
549     break;
550   default:
551     break;
552   }
555 // Test that an object is non-null after CFRetain/CFRelease/CFMakeCollectable/CFAutorelease.
556 void f17(int x, CFTypeRef p) {
557   switch (x) {
558   case 0:
559     CFRelease(p);
560     if (!p)
561       CFRelease(0); // no-warning
562     break;
563   case 1:
564     CFRetain(p);
565     if (!p)
566       CFRetain(0); // no-warning
567     break;
568   case 2:
569     CFMakeCollectable(p);
570     if (!p)
571       CFMakeCollectable(0); // no-warning
572     break;
573   case 3:
574     CFAutorelease(p);
575     if (!p)
576       CFAutorelease(0); // no-warning
577     break;
578   default:
579     break;
580   }
583 // Test basic tracking of ivars associated with 'self'.  For the retain/release
584 // checker we currently do not want to flag leaks associated with stores
585 // of tracked objects to ivars.
586 @interface SelfIvarTest : NSObject {
587   id myObj;
589 - (void)test_self_tracking;
590 @end
592 @implementation SelfIvarTest
593 - (void)test_self_tracking {
594   myObj = (id) CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
596 @end
598 // Test return of non-owned objects in contexts where an owned object
599 // is expected.
600 @interface TestReturnNotOwnedWhenExpectedOwned
601 - (NSString*)newString;
602 @end
604 @implementation TestReturnNotOwnedWhenExpectedOwned
605 - (NSString*)newString {
606   NSString *s = [NSString stringWithUTF8String:"hello"];
607   return s; // expected-warning{{Object with a +0 retain count returned to caller where a +1 (owning) retain count is expected}}
609 @end
611 int isFoo(char c);
613 static void rdar_6659160(char *inkind, char *inname)
615   // We currently expect that [NSObject alloc] cannot fail.  This
616   // will be a toggled flag in the future.  It can indeed return null, but
617   // Cocoa programmers generally aren't expected to reason about out-of-memory
618   // conditions.
619   NSString *kind = [[NSString alloc] initWithUTF8String:inkind];  // expected-warning{{leak}}
620   
621   // We do allow stringWithUTF8String to fail.  This isn't really correct, as
622   // far as returning 0.  In most error conditions it will throw an exception.
623   // If allocation fails it could return 0, but again this
624   // isn't expected.
625   NSString *name = [NSString stringWithUTF8String:inname];
626   if(!name)
627     return;
629   const char *kindC = 0;
630   const char *nameC = 0;
631   
632   // In both cases, we cannot reach a point down below where we
633   // dereference kindC or nameC with either being null.  This is because
634   // we assume that [NSObject alloc] doesn't fail and that we have the guard
635   // up above.
636   
637   if(kind)
638     kindC = [kind UTF8String];
639   if(name)
640     nameC = [name UTF8String];
641   if(!isFoo(kindC[0])) // expected-warning{{null}}
642     return;
643   if(!isFoo(nameC[0])) // no-warning
644     return;
646   [kind release];
647   [name release]; // expected-warning{{Incorrect decrement of the reference count}}
650 // PR 3677 - 'allocWithZone' should be treated as following the Cocoa naming
651 //  conventions with respect to 'return'ing ownership.
652 @interface PR3677: NSObject @end
653 @implementation PR3677
654 + (id)allocWithZone:(NSZone *)inZone {
655   return [super allocWithZone:inZone];  // no-warning
657 @end
659 // PR 3820 - Reason about calls to -dealloc
660 void pr3820_DeallocInsteadOfRelease(void)
662   id foo = [[NSString alloc] init]; // no-warning
663   [foo dealloc];
664   // foo is not leaked, since it has been deallocated.
667 void pr3820_ReleaseAfterDealloc(void)
669   id foo = [[NSString alloc] init];
670   [foo dealloc];
671   [foo release];  // expected-warning{{used after it is release}}
672   // NSInternalInconsistencyException: message sent to deallocated object
675 void pr3820_DeallocAfterRelease(void)
677   NSLog(@"\n\n[%s]", __FUNCTION__);
678   id foo = [[NSString alloc] init];
679   [foo release];
680   [foo dealloc]; // expected-warning{{used after it is released}}
681   // message sent to released object
684 // The problem here is that 'length' binds to '($0 - 1)' after '--length', but
685 // SimpleConstraintManager doesn't know how to reason about
686 // '($0 - 1) > constant'.  As a temporary hack, we drop the value of '($0 - 1)'
687 // and conjure a new symbol.
688 void rdar6704930(unsigned char *s, unsigned int length) {
689   NSString* name = 0;
690   if (s != 0) {
691     if (length > 0) {
692       while (length > 0) {
693         if (*s == ':') {
694           ++s;
695           --length;
696           name = [[NSString alloc] init]; // no-warning
697           break;
698         }
699         ++s;
700         --length;
701       }
702       if ((length == 0) && (name != 0)) {
703         [name release];
704         name = 0;
705       }
706       if (length == 0) { // no ':' found -> use it all as name
707         name = [[NSString alloc] init]; // no-warning
708       }
709     }
710   }
712   if (name != 0) {
713     [name release];
714   }
717 //===----------------------------------------------------------------------===//
718 // One build of the analyzer accidentally stopped tracking the allocated
719 // object after the 'retain'.
720 //===----------------------------------------------------------------------===//
722 @interface rdar_6833332 : NSObject <NSApplicationDelegate> {
723     NSWindow *window;
725 @property (nonatomic, retain) NSWindow *window;
726 @end
728 @implementation rdar_6833332
729 @synthesize window;
730 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
731  NSMutableDictionary *dict = [[NSMutableDictionary dictionaryWithCapacity:4] retain]; // expected-warning{{leak}}
733  [dict setObject:@"foo" forKey:@"bar"];
735  NSLog(@"%@", dict);
737 - (void)dealloc {
738     [window release];
739     [super dealloc];
742 - (void)radar10102244 {
743  NSMutableDictionary *dict = [[NSMutableDictionary dictionaryWithCapacity:4] retain]; // expected-warning{{leak}} 
744  if (window) 
745    NSLog(@"%@", window);    
747 @end
749 //===----------------------------------------------------------------------===//
750 // clang checker fails to catch use-after-release
751 //===----------------------------------------------------------------------===//
752 int rdar_6257780_Case1(void) {
753   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
754   NSArray *array = [NSArray array];
755   [array release]; // expected-warning{{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
756   [pool drain];
757   return 0;
760 //===----------------------------------------------------------------------===//
761 // Analyzer is confused about NSAutoreleasePool -allocWithZone:.
762 //===----------------------------------------------------------------------===//
763 void rdar_10640253_autorelease_allocWithZone(void) {
764     NSAutoreleasePool *pool = [[NSAutoreleasePool allocWithZone:(NSZone*)0] init];
765     (void) pool;
768 //===----------------------------------------------------------------------===//
769 // Checker should understand new/setObject:/release constructs
770 //===----------------------------------------------------------------------===//
771 void rdar_6866843(void) {
772  NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
773  NSMutableDictionary* dictionary = [[NSMutableDictionary alloc] init];
774  NSArray* array = [[NSArray alloc] init];
775  [dictionary setObject:array forKey:@"key"];
776  [array release];
777  // Using 'array' here should be fine
778  NSLog(@"array = %@\n", array); // no-warning
779  // Now the array is released
780  [dictionary release];
781  [pool drain];
785 //===----------------------------------------------------------------------===//
786 // Classes typedef-ed to CF objects should get the same treatment as CF objects
787 //===----------------------------------------------------------------------===//
788 typedef CFTypeRef OtherRef;
790 @interface RDar6877235 : NSObject {}
791 - (CFTypeRef)_copyCFTypeRef;
792 - (OtherRef)_copyOtherRef;
793 @end
795 @implementation RDar6877235
796 - (CFTypeRef)_copyCFTypeRef {
797   return [[NSString alloc] init]; // no-warning
799 - (OtherRef)_copyOtherRef {
800   return [[NSString alloc] init]; // no-warning
802 @end
804 //===----------------------------------------------------------------------===//
805 // false positive - init method returns an object owned by caller
806 //===----------------------------------------------------------------------===//
807 @interface RDar6320065 : NSObject {
808   NSString *_foo;
810 - (id)initReturningNewClass;
811 - (id)_initReturningNewClassBad;
812 - (id)initReturningNewClassBad2;
813 @end
815 @interface RDar6320065Subclass : RDar6320065
816 @end
818 @implementation RDar6320065
819 - (id)initReturningNewClass {
820   [self release];
821   self = [[RDar6320065Subclass alloc] init]; // no-warning
822   return self;
824 - (id)_initReturningNewClassBad {
825   [self release];
826   [[RDar6320065Subclass alloc] init]; // expected-warning {{leak}}
827   return self;
829 - (id)initReturningNewClassBad2 {
830   [self release];
831   self = [[RDar6320065Subclass alloc] init];
832   return [self autorelease]; // expected-warning{{Object with a +0 retain count returned to caller where a +1 (owning) retain count is expected}}
835 @end
837 @implementation RDar6320065Subclass
838 @end
840 int RDar6320065_test(void) {
841   RDar6320065 *test = [[RDar6320065 alloc] init]; // no-warning
842   [test release];
843   return 0;
846 //===----------------------------------------------------------------------===//
847 // -awakeAfterUsingCoder: returns an owned object and claims the receiver
848 //===----------------------------------------------------------------------===//
849 @interface RDar7129086 : NSObject {} @end
850 @implementation RDar7129086
851 - (id)awakeAfterUsingCoder:(NSCoder *)aDecoder {
852   [self release]; // no-warning
853   return [NSString alloc];  // no-warning
855 @end
857 //===----------------------------------------------------------------------===//
858 // [NSData dataWithBytesNoCopy] does not return a retained object
859 //===----------------------------------------------------------------------===//
860 @interface RDar6859457 : NSObject {}
861 - (NSString*) NoCopyString;
862 - (NSString*) noCopyString;
863 @end
865 @implementation RDar6859457 
866 - (NSString*) NoCopyString { return [[NSString alloc] init]; } // expected-warning{{leak}}
867 - (NSString*) noCopyString { return [[NSString alloc] init]; } // expected-warning{{leak}}
868 @end
870 void test_RDar6859457(RDar6859457 *x, void *bytes, NSUInteger dataLength) {
871   [x NoCopyString]; // expected-warning{{leak}}
872   [x noCopyString]; // expected-warning{{leak}}
873   [NSData dataWithBytesNoCopy:bytes length:dataLength];  // no-warning
874   [NSData dataWithBytesNoCopy:bytes length:dataLength freeWhenDone:1]; // no-warning
877 //===----------------------------------------------------------------------===//
878 // PR 4230 - an autorelease pool is not necessarily leaked during a premature
879 //  return
880 //===----------------------------------------------------------------------===//
882 static void PR4230(void)
884   NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // no-warning
885   NSString *object = [[[NSString alloc] init] autorelease]; // no-warning
886   return;
889 static void PR4230_new(void)
891   NSAutoreleasePool *pool = [NSAutoreleasePool new]; // no-warning
892   NSString *object = [[[NSString alloc] init] autorelease]; // no-warning
893   return;
896 //===----------------------------------------------------------------------===//
897 // Method name that has a null IdentifierInfo* for its first selector slot.
898 // This test just makes sure that we handle it.
899 //===----------------------------------------------------------------------===//
900 @interface TestNullIdentifier
901 @end
903 @implementation TestNullIdentifier
904 + (id):(int)x, ... {
905   return [[NSString alloc] init]; // expected-warning{{leak}}
907 @end
909 //===----------------------------------------------------------------------===//
910 // don't flag leaks for return types that cannot be determined to be CF types
911 //===----------------------------------------------------------------------===//
913 // We don't know if 'struct s6893565' represents a Core Foundation type, so
914 // we shouldn't emit an error here.
915 typedef struct s6893565* TD6893565;
917 @interface RDar6893565 {}
918 -(TD6893565)newThing;
919 @end
921 @implementation RDar6893565
922 -(TD6893565)newThing {  
923   return (TD6893565) [[NSString alloc] init]; // no-warning
925 @end
927 //===----------------------------------------------------------------------===//
928 // clang: false positives w/QC and CoreImage methods
929 //===----------------------------------------------------------------------===//
930 void rdar6902710(QCView *view, QCRenderer *renderer, CIContext *context,
931                  NSString *str, CIImage *img, CGRect rect,
932                  CIFormat form, CGColorSpaceRef cs) {
933   [view createSnapshotImageOfType:str]; // expected-warning{{leak}}
934   [renderer createSnapshotImageOfType:str]; // expected-warning{{leak}}
935   [context createCGImage:img fromRect:rect]; // expected-warning{{leak}}
936   [context createCGImage:img fromRect:rect format:form colorSpace:cs]; // expected-warning{{leak}}
939 //===----------------------------------------------------------------------===//
940 // -[CIContext createCGLayerWithSize:info:] misinterpreted by clang scan-build
941 //===----------------------------------------------------------------------===//
942 void rdar6945561(CIContext *context, CGSize size, CFDictionaryRef d) {
943   [context createCGLayerWithSize:size info:d]; // expected-warning{{leak}}
946 //===----------------------------------------------------------------------===//
947 // Add knowledge of IOKit functions to retain/release checker.
948 //===----------------------------------------------------------------------===//
949 void IOBSDNameMatching_wrapper(mach_port_t mainPort, uint32_t options,  const char * bsdName) {  
950   IOBSDNameMatching(mainPort, options, bsdName); // expected-warning{{leak}}
953 void IOServiceMatching_wrapper(const char * name) {
954   IOServiceMatching(name); // expected-warning{{leak}}
957 void IOServiceNameMatching_wrapper(const char * name) {
958   IOServiceNameMatching(name); // expected-warning{{leak}}
961 CF_RETURNS_RETAINED CFDictionaryRef CreateDict(void);
963 void IOServiceAddNotification_wrapper(mach_port_t mainPort, const io_name_t notificationType,
964   mach_port_t wakePort, uintptr_t reference, io_iterator_t * notification ) {
966   CFDictionaryRef matching = CreateDict();
967   CFRelease(matching);
968   IOServiceAddNotification(mainPort, notificationType, matching, // expected-warning{{used after it is released}} expected-warning{{deprecated}}
969                            wakePort, reference, notification);
972 void IORegistryEntryIDMatching_wrapper(uint64_t entryID ) {
973   IORegistryEntryIDMatching(entryID); // expected-warning{{leak}}
976 void IOOpenFirmwarePathMatching_wrapper(mach_port_t mainPort, uint32_t options,
977                                         const char * path) {
978   IOOpenFirmwarePathMatching(mainPort, options, path); // expected-warning{{leak}}
981 void IOServiceGetMatchingService_wrapper(mach_port_t mainPort) {
982   CFDictionaryRef matching = CreateDict();
983   IOServiceGetMatchingService(mainPort, matching);
984   CFRelease(matching); // expected-warning{{used after it is released}}
987 void IOServiceGetMatchingServices_wrapper(mach_port_t mainPort, io_iterator_t *existing) {
988   CFDictionaryRef matching = CreateDict();
989   IOServiceGetMatchingServices(mainPort, matching, existing);
990   CFRelease(matching); // expected-warning{{used after it is released}}
993 void IOServiceAddMatchingNotification_wrapper(IONotificationPortRef notifyPort, const io_name_t notificationType, 
994   IOServiceMatchingCallback callback, void * refCon, io_iterator_t * notification) {
995     
996   CFDictionaryRef matching = CreateDict();
997   IOServiceAddMatchingNotification(notifyPort, notificationType, matching, callback, refCon, notification);
998   CFRelease(matching); // expected-warning{{used after it is released}}
1001 //===----------------------------------------------------------------------===//
1002 // Test of handling objects whose references "escape" to containers.
1003 //===----------------------------------------------------------------------===//
1004 void CFDictionaryAddValue(CFMutableDictionaryRef, void *, void *);
1006 void rdar_6539791(CFMutableDictionaryRef y, void* key, void* val_key) {
1007   CFMutableDictionaryRef x = CFDictionaryCreateMutable(kCFAllocatorDefault, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
1008   CFDictionaryAddValue(y, key, x);
1009   CFRelease(x); // the dictionary keeps a reference, so the object isn't deallocated yet
1010   signed z = 1;
1011   CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z);
1012   if (value) {
1013     CFDictionaryAddValue(x, val_key, (void*)value); // no-warning
1014     CFRelease(value);
1015     CFDictionaryAddValue(y, val_key, (void*)value); // no-warning
1016   }
1019 // Same issue, except with "AppendValue" functions.
1020 void rdar_6560661(CFMutableArrayRef x) {
1021   signed z = 1;
1022   CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z);
1023   // CFArrayAppendValue keeps a reference to value.
1024   CFArrayAppendValue(x, value);
1025   CFRelease(value);
1026   CFRetain(value);
1027   CFRelease(value); // no-warning
1030 // Same issue, excwept with "CFAttributeStringSetAttribute".
1031 void rdar_7152619(CFStringRef str) {
1032   CFAttributedStringRef string = CFAttributedStringCreate(kCFAllocatorDefault, str, 0);
1033   CFMutableAttributedStringRef attrString = CFAttributedStringCreateMutableCopy(kCFAllocatorDefault, 100, string);
1034   CFRelease(string);
1035   NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1036   CFAttributedStringSetAttribute(attrString, CFRangeMake(0, 1), str, number);
1037   [number release];
1038   [number retain];
1039   CFRelease(attrString);  
1042 //===----------------------------------------------------------------------===//
1043 // Test of handling CGGradientXXX functions.
1044 //===----------------------------------------------------------------------===//
1046 void rdar_7184450(CGContextRef myContext, CGFloat x, CGPoint myStartPoint,
1047                   CGPoint myEndPoint) {
1048   size_t num_locations = 6;
1049   CGFloat locations[6] = { 0.0, 0.265, 0.28, 0.31, 0.36, 1.0 };
1050   CGFloat components[28] = { 239.0/256.0, 167.0/256.0, 170.0/256.0,
1051      x,  // Start color
1052     207.0/255.0, 39.0/255.0, 39.0/255.0, x,
1053     147.0/255.0, 21.0/255.0, 22.0/255.0, x,
1054     175.0/255.0, 175.0/255.0, 175.0/255.0, x,
1055     255.0/255.0,255.0/255.0, 255.0/255.0, x,
1056     255.0/255.0,255.0/255.0, 255.0/255.0, x
1057   }; // End color
1058   
1059   CGGradientRef myGradient =
1060     CGGradientCreateWithColorComponents(CGColorSpaceCreateDeviceRGB(), // expected-warning{{leak}}
1061       components, locations, num_locations);
1063   CGContextDrawLinearGradient(myContext, myGradient, myStartPoint, myEndPoint,
1064                               0);
1065   CGGradientRelease(myGradient);
1068 void rdar_7184450_pos(CGContextRef myContext, CGFloat x, CGPoint myStartPoint,
1069                   CGPoint myEndPoint) {
1070   size_t num_locations = 6;
1071   CGFloat locations[6] = { 0.0, 0.265, 0.28, 0.31, 0.36, 1.0 };
1072   CGFloat components[28] = { 239.0/256.0, 167.0/256.0, 170.0/256.0,
1073      x,  // Start color
1074     207.0/255.0, 39.0/255.0, 39.0/255.0, x,
1075     147.0/255.0, 21.0/255.0, 22.0/255.0, x,
1076     175.0/255.0, 175.0/255.0, 175.0/255.0, x,
1077     255.0/255.0,255.0/255.0, 255.0/255.0, x,
1078     255.0/255.0,255.0/255.0, 255.0/255.0, x
1079   }; // End color
1080   
1081   CGGradientRef myGradient =
1082    CGGradientCreateWithColorComponents(CGColorSpaceCreateDeviceRGB(), components, locations, num_locations); // expected-warning 2 {{leak}}
1084   CGContextDrawLinearGradient(myContext, myGradient, myStartPoint, myEndPoint,
1085                               0);
1088 //===----------------------------------------------------------------------===//
1089 // clang false positive: retained instance passed to thread in pthread_create
1090 // marked as leak
1092 // Until we have full IPA, the analyzer should stop tracking the reference
1093 // count of objects passed to pthread_create.
1095 //===----------------------------------------------------------------------===//
1096 struct _opaque_pthread_t {};
1097 struct _opaque_pthread_attr_t {};
1098 typedef struct _opaque_pthread_t *__darwin_pthread_t;
1099 typedef struct _opaque_pthread_attr_t __darwin_pthread_attr_t;
1100 typedef __darwin_pthread_t pthread_t;
1101 typedef __darwin_pthread_attr_t pthread_attr_t;
1102 typedef unsigned long __darwin_pthread_key_t;
1103 typedef __darwin_pthread_key_t pthread_key_t;
1105 int pthread_create(pthread_t *, const pthread_attr_t *,
1106                    void *(*)(void *), void *);
1108 int pthread_setspecific(pthread_key_t key, const void *value);
1110 void *rdar_7299394_start_routine(void *p) {
1111   [((id) p) release];
1112   return 0;
1114 void rdar_7299394(pthread_attr_t *attr, pthread_t *thread, void *args) {
1115   NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1116   pthread_create(thread, attr, rdar_7299394_start_routine, number);
1118 void rdar_7299394_positive(pthread_attr_t *attr, pthread_t *thread) {
1119   NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1122 //===----------------------------------------------------------------------===//
1123 // false positive with not understanding thread local storage
1124 //===----------------------------------------------------------------------===//
1125 void rdar11282706(pthread_key_t key) {
1126   NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1127   pthread_setspecific(key, (void*) number);
1130 //===----------------------------------------------------------------------===//
1131 // False leak associated with call to CVPixelBufferCreateWithBytes ()
1133 // According to the Core Video Reference (ADC), CVPixelBufferCreateWithBytes and
1134 // CVPixelBufferCreateWithPlanarBytes can release (via a callback) the
1135 // pixel buffer object.  These test cases show how the analyzer stops tracking
1136 // the reference count for the objects passed for this argument.  This
1137 // could be made smarter.
1138 //===----------------------------------------------------------------------===//
1139 typedef int int32_t;
1140 typedef UInt32 FourCharCode;
1141 typedef FourCharCode OSType;
1142 typedef uint64_t CVOptionFlags;
1143 typedef int32_t CVReturn;
1144 typedef struct __CVBuffer *CVBufferRef;
1145 typedef CVBufferRef CVImageBufferRef;
1146 typedef CVImageBufferRef CVPixelBufferRef;
1147 typedef void (*CVPixelBufferReleaseBytesCallback)( void *releaseRefCon, const void *baseAddress );
1149 extern CVReturn CVPixelBufferCreateWithBytes(CFAllocatorRef allocator,
1150             size_t width,
1151             size_t height,
1152             OSType pixelFormatType,
1153             void *baseAddress,
1154             size_t bytesPerRow,
1155             CVPixelBufferReleaseBytesCallback releaseCallback,
1156             void *releaseRefCon,
1157             CFDictionaryRef pixelBufferAttributes,
1158                    CVPixelBufferRef *pixelBufferOut) ;
1160 typedef void (*CVPixelBufferReleasePlanarBytesCallback)( void *releaseRefCon, const void *dataPtr, size_t dataSize, size_t numberOfPlanes, const void *planeAddresses[] );
1162 extern CVReturn CVPixelBufferCreateWithPlanarBytes(CFAllocatorRef allocator,
1163         size_t width,
1164         size_t height,
1165         OSType pixelFormatType,
1166         void *dataPtr,
1167         size_t dataSize,
1168         size_t numberOfPlanes,
1169         void *planeBaseAddress[],
1170         size_t planeWidth[],
1171         size_t planeHeight[],
1172         size_t planeBytesPerRow[],
1173         CVPixelBufferReleasePlanarBytesCallback releaseCallback,
1174         void *releaseRefCon,
1175         CFDictionaryRef pixelBufferAttributes,
1176         CVPixelBufferRef *pixelBufferOut) ;
1178 extern CVReturn CVPixelBufferCreateWithBytes(CFAllocatorRef allocator,
1179             size_t width,
1180             size_t height,
1181             OSType pixelFormatType,
1182             void *baseAddress,
1183             size_t bytesPerRow,
1184             CVPixelBufferReleaseBytesCallback releaseCallback,
1185             void *releaseRefCon,
1186             CFDictionaryRef pixelBufferAttributes,
1187                    CVPixelBufferRef *pixelBufferOut) ;
1189 CVReturn rdar_7283567(CFAllocatorRef allocator, size_t width, size_t height,
1190                       OSType pixelFormatType, void *baseAddress,
1191                       size_t bytesPerRow,
1192                       CVPixelBufferReleaseBytesCallback releaseCallback,
1193                       CFDictionaryRef pixelBufferAttributes,
1194                       CVPixelBufferRef *pixelBufferOut) {
1196   // For the allocated object, it doesn't really matter what type it is
1197   // for the purpose of this test.  All we want to show is that
1198   // this is freed later by the callback.
1199   NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1200   
1201   return CVPixelBufferCreateWithBytes(allocator, width, height, pixelFormatType,
1202                                 baseAddress, bytesPerRow, releaseCallback,
1203                                 number, // potentially released by callback
1204                                 pixelBufferAttributes, pixelBufferOut) ;
1207 CVReturn rdar_7283567_2(CFAllocatorRef allocator, size_t width, size_t height,
1208         OSType pixelFormatType, void *dataPtr, size_t dataSize,
1209         size_t numberOfPlanes, void *planeBaseAddress[],
1210         size_t planeWidth[], size_t planeHeight[], size_t planeBytesPerRow[],
1211         CVPixelBufferReleasePlanarBytesCallback releaseCallback,
1212         CFDictionaryRef pixelBufferAttributes,
1213         CVPixelBufferRef *pixelBufferOut) {
1214     
1215     // For the allocated object, it doesn't really matter what type it is
1216     // for the purpose of this test.  All we want to show is that
1217     // this is freed later by the callback.
1218     NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1220     return CVPixelBufferCreateWithPlanarBytes(allocator,
1221               width, height, pixelFormatType, dataPtr, dataSize,
1222               numberOfPlanes, planeBaseAddress, planeWidth,
1223               planeHeight, planeBytesPerRow, releaseCallback,
1224               number, // potentially released by callback
1225               pixelBufferAttributes, pixelBufferOut) ;
1228 //===----------------------------------------------------------------------===//
1229 // False leak associated with CGBitmapContextCreateWithData
1230 //===----------------------------------------------------------------------===//
1231 typedef uint32_t CGBitmapInfo;
1232 typedef void (*CGBitmapContextReleaseDataCallback)(void *releaseInfo, void *data);
1233     
1234 CGContextRef CGBitmapContextCreateWithData(void *data,
1235     size_t width, size_t height, size_t bitsPerComponent,
1236     size_t bytesPerRow, CGColorSpaceRef space, CGBitmapInfo bitmapInfo,
1237     CGBitmapContextReleaseDataCallback releaseCallback, void *releaseInfo);
1239 void rdar_7358899(void *data,
1240       size_t width, size_t height, size_t bitsPerComponent,
1241       size_t bytesPerRow, CGColorSpaceRef space, CGBitmapInfo bitmapInfo,
1242       CGBitmapContextReleaseDataCallback releaseCallback) {
1244     // For the allocated object, it doesn't really matter what type it is
1245     // for the purpose of this test.  All we want to show is that
1246     // this is freed later by the callback.
1247     NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1249   CGBitmapContextCreateWithData(data, width, height, bitsPerComponent, // expected-warning{{leak}}
1250     bytesPerRow, space, bitmapInfo, releaseCallback, number);
1253 //===----------------------------------------------------------------------===//
1254 // Allow 'new', 'copy', 'alloc', 'init' prefix to start before '_' when
1255 // determining Cocoa fundamental rule.
1257 // Previously the retain/release checker just skipped prefixes before the
1258 // first '_' entirely.  Now the checker honors the prefix if it results in a
1259 // recognizable naming convention (e.g., 'new', 'init').
1260 //===----------------------------------------------------------------------===//
1261 @interface RDar7265711 {}
1262 - (id) new_stuff;
1263 @end
1265 void rdar7265711_a(RDar7265711 *x) {
1266   id y = [x new_stuff]; // expected-warning{{leak}}
1269 void rdar7265711_b(RDar7265711 *x) {
1270   id y = [x new_stuff]; // no-warning
1271   [y release];
1274 //===----------------------------------------------------------------------===//
1275 // clang thinks [NSCursor dragCopyCursor] returns a retained reference
1276 //===----------------------------------------------------------------------===//
1277 @interface NSCursor : NSObject
1278 + (NSCursor *)dragCopyCursor;
1279 @end
1281 void rdar7306898(void) {
1282   // 'dragCopyCursor' does not follow Cocoa's fundamental rule.  It is a noun, not an sentence
1283   // implying a 'copy' of something.
1284   NSCursor *c =  [NSCursor dragCopyCursor]; // no-warning
1285   NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1288 //===----------------------------------------------------------------------===//
1289 // Sending 'release', 'retain', etc. to a Class directly is not likely what the
1290 // user intended.
1291 //===----------------------------------------------------------------------===//
1292 @interface RDar7252064 : NSObject @end
1293 void rdar7252064(void) {
1294   [RDar7252064 release]; // expected-warning{{The 'release' message should be sent to instances of class 'RDar7252064' and not the class directly}}
1295   [RDar7252064 retain]; // expected-warning{{The 'retain' message should be sent to instances of class 'RDar7252064' and not the class directly}}
1296   [RDar7252064 autorelease]; // expected-warning{{The 'autorelease' message should be sent to instances of class 'RDar7252064' and not the class directly}}
1297   [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}}
1300 //===----------------------------------------------------------------------===//
1301 // Tests of ownership attributes.
1302 //===----------------------------------------------------------------------===//
1304 typedef NSString* MyStringTy;
1306 @protocol FooP;
1308 @interface TestOwnershipAttr : NSObject
1309 - (NSString*) returnsAnOwnedString  NS_RETURNS_RETAINED; // no-warning
1310 - (NSString*) returnsAnOwnedCFString  CF_RETURNS_RETAINED; // no-warning
1311 - (MyStringTy) returnsAnOwnedTypedString NS_RETURNS_RETAINED; // no-warning
1312 - (NSString*) newString NS_RETURNS_NOT_RETAINED; // no-warning
1313 - (NSString*) newString_auto NS_RETURNS_AUTORELEASED; // no-warning
1314 - (NSString*) newStringNoAttr;
1315 - (int) returnsAnOwnedInt NS_RETURNS_RETAINED; // expected-warning{{'ns_returns_retained' attribute only applies to methods that return an Objective-C object}}
1316 - (id) pseudoInit NS_CONSUMES_SELF NS_RETURNS_RETAINED;
1317 + (void) consume:(id) NS_CONSUMED x;
1318 + (void) consume2:(id) CF_CONSUMED x;
1319 @end
1321 static int ownership_attribute_doesnt_go_here NS_RETURNS_RETAINED; // expected-warning{{'ns_returns_retained' attribute only applies to functions and methods}}
1323 void test_attr_1(TestOwnershipAttr *X) {
1324   NSString *str = [X returnsAnOwnedString]; // expected-warning{{leak}}
1327 void test_attr_1b(TestOwnershipAttr *X) {
1328   NSString *str = [X returnsAnOwnedCFString]; // expected-warning{{leak}}
1331 void test_attr1c(TestOwnershipAttr *X) {
1332   NSString *str = [X newString]; // no-warning
1333   NSString *str2 = [X newStringNoAttr]; // expected-warning{{leak}}
1334   NSString *str3 = [X newString_auto]; // no-warning
1335   NSString *str4 = [[X newString_auto] retain]; // expected-warning {{leak}}
1338 void testattr2_a(void) {
1339   TestOwnershipAttr *x = [TestOwnershipAttr alloc]; // expected-warning{{leak}}
1342 void testattr2_b(void) {
1343   TestOwnershipAttr *x = [[TestOwnershipAttr alloc] pseudoInit];  // expected-warning{{leak}}
1346 void testattr2_b_11358224_self_assign_looses_the_leak(void) {
1347   TestOwnershipAttr *x = [[TestOwnershipAttr alloc] pseudoInit];// expected-warning{{leak}}
1348   x = x;
1351 void testattr2_c(void) {
1352   TestOwnershipAttr *x = [[TestOwnershipAttr alloc] pseudoInit]; // no-warning
1353   [x release];
1356 void testattr3(void) {
1357   TestOwnershipAttr *x = [TestOwnershipAttr alloc]; // no-warning
1358   [TestOwnershipAttr consume:x];
1359   TestOwnershipAttr *y = [TestOwnershipAttr alloc]; // no-warning
1360   [TestOwnershipAttr consume2:y];
1363 void consume_ns(id NS_CONSUMED x);
1364 void consume_cf(id CF_CONSUMED x);
1366 void testattr4(void) {
1367   TestOwnershipAttr *x = [TestOwnershipAttr alloc]; // no-warning
1368   consume_ns(x);
1369   TestOwnershipAttr *y = [TestOwnershipAttr alloc]; // no-warning
1370   consume_cf(y);
1373 @interface TestOwnershipAttr2 : NSObject
1374 - (NSString*) newString NS_RETURNS_NOT_RETAINED; // no-warning
1375 @end
1377 @implementation TestOwnershipAttr2
1378 - (NSString*) newString {
1379   return [NSString alloc]; // expected-warning {{Potential leak of an object}}
1381 @end
1383 @interface MyClassTestCFAttr : NSObject {}
1384 - (NSDate*) returnsCFRetained CF_RETURNS_RETAINED;
1385 - (CFDateRef) returnsCFRetainedAsCF CF_RETURNS_RETAINED;
1386 - (CFDateRef) newCFRetainedAsCF CF_RETURNS_NOT_RETAINED;
1387 - (CFDateRef) newCFRetainedAsCFNoAttr;
1388 - (NSDate*) alsoReturnsRetained;
1389 - (CFDateRef) alsoReturnsRetainedAsCF;
1390 - (NSDate*) returnsNSRetained NS_RETURNS_RETAINED;
1391 @end
1393 CF_RETURNS_RETAINED
1394 CFDateRef returnsRetainedCFDate(void)  {
1395   return CFDateCreate(0, CFAbsoluteTimeGetCurrent());
1398 @implementation MyClassTestCFAttr
1399 - (NSDate*) returnsCFRetained {
1400   return (NSDate*) returnsRetainedCFDate(); // No leak.
1403 - (CFDateRef) returnsCFRetainedAsCF {
1404   return returnsRetainedCFDate(); // No leak.
1407 - (CFDateRef) newCFRetainedAsCF {
1408   return (CFDateRef)[(id)[self returnsCFRetainedAsCF] autorelease];
1411 - (CFDateRef) newCFRetainedAsCFNoAttr {
1412   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}}
1415 - (NSDate*) alsoReturnsRetained {
1416   return (NSDate*) returnsRetainedCFDate(); // expected-warning{{leak}}
1419 - (CFDateRef) alsoReturnsRetainedAsCF {
1420   return returnsRetainedCFDate(); // expected-warning{{leak}}
1424 - (NSDate*) returnsNSRetained {
1425   return (NSDate*) returnsRetainedCFDate(); // no-warning
1427 @end
1429 //===----------------------------------------------------------------------===//
1430 // Test that leaks post-dominated by "panic" functions are not reported.
1432 // Do not report a leak when post-dominated by a call to a noreturn or panic
1433 // function.
1434 //===----------------------------------------------------------------------===//
1435 void panic(void) __attribute__((noreturn));
1436 void panic_not_in_hardcoded_list(void) __attribute__((noreturn));
1438 void test_panic_negative(void) {
1439   signed z = 1;
1440   CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z);  // expected-warning{{leak}}
1443 void test_panic_positive(void) {
1444   signed z = 1;
1445   CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // no-warning
1446   panic();
1449 void test_panic_neg_2(int x) {
1450   signed z = 1;
1451   CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // expected-warning{{leak}}
1452   if (x)
1453     panic();
1456 void test_panic_pos_2(int x) {
1457   signed z = 1;
1458   CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // no-warning
1459   if (x)
1460     panic();
1461   if (!x) {
1462     // This showed up previously where we silently missed checking the function
1463     // type for noreturn.  "panic()" is a hard-coded known panic function that
1464     // isn't always noreturn.
1465     panic_not_in_hardcoded_list();
1466   }
1469 //===----------------------------------------------------------------------===//
1470 // Test uses of blocks (closures)
1471 //===----------------------------------------------------------------------===//
1473 void test_blocks_1_pos(void) {
1474   NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1475   ^{}();
1478 void test_blocks_1_indirect_release(void) {
1479   NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1480   ^{ [number release]; }();
1483 void test_blocks_1_indirect_retain(void) {
1484   // Eventually this should be reported as a leak.
1485   NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1486   ^{ [number retain]; }();
1489 void test_blocks_1_indirect_release_via_call(void) {
1490   NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1491   ^(NSObject *o){ [o release]; }(number);
1494 void test_blocks_1_indirect_retain_via_call(void) {
1495   NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning {{leak}}
1496   ^(NSObject *o){ [o retain]; }(number);
1499 //===--------------------------------------------------------------------===//
1500 // Test sending message to super that returns an object alias.  Previously
1501 // this caused a crash in the analyzer.
1502 //===--------------------------------------------------------------------===//
1504 @interface Rdar8015556 : NSObject {} @end
1505 @implementation Rdar8015556
1506 - (id)retain {
1507   return [super retain];
1509 @end
1511 // Correcly handle Class<...> in Cocoa Conventions detector.
1512 @protocol Prot_R8272168 @end
1513 Class <Prot_R8272168> GetAClassThatImplementsProt_R8272168(void);
1514 void r8272168(void) {
1515   GetAClassThatImplementsProt_R8272168();
1518 // Test case which in the past triggered a false positive.
1519 @interface RDar8356342
1520 - (NSDate*) rdar8356342:(NSDate *)inValue;
1521 @end
1523 @implementation RDar8356342
1524 - (NSDate*) rdar8356342:(NSDate*)inValue {
1525   NSDate *outValue = inValue;
1526   if (outValue == 0)
1527     outValue = [[NSDate alloc] init]; // no-warning
1529   if (outValue != inValue)
1530     [outValue autorelease];
1532   return outValue;
1534 @end
1536 // This test case previously crashed because of a bug in BugReporter.
1537 extern const void *CFDictionaryGetValue(CFDictionaryRef theDict, const void *key);
1538 typedef struct __CFError * CFErrorRef;
1539 extern const CFStringRef kCFErrorUnderlyingErrorKey;
1540 extern CFDictionaryRef CFErrorCopyUserInfo(CFErrorRef err);
1541 static void rdar_8724287(CFErrorRef error)
1543     CFErrorRef error_to_dump;
1545     error_to_dump = error;
1546     while (error_to_dump != ((void*)0)) {
1547         CFDictionaryRef info;
1549         info = CFErrorCopyUserInfo(error_to_dump); // expected-warning{{Potential leak of an object}}
1551         if (info != ((void*)0)) {
1552         }
1554         error_to_dump = (CFErrorRef) CFDictionaryGetValue(info, kCFErrorUnderlyingErrorKey);
1555     }
1558 // Make sure the model applies cf_consumed correctly in argument positions
1559 // besides the first.
1560 extern void *CFStringCreate(void);
1561 extern void rdar_9234108_helper(void *key, void * CF_CONSUMED value);
1562 void rdar_9234108(void) {
1563   rdar_9234108_helper(0, CFStringCreate());
1566 // Make sure that objc_method_family works to override naming conventions.
1567 struct TwoDoubles {
1568   double one;
1569   double two;
1571 typedef struct TwoDoubles TwoDoubles;
1573 @interface NSValue (Mine)
1574 - (id)_prefix_initWithTwoDoubles:(TwoDoubles)twoDoubles __attribute__((objc_method_family(init)));
1575 @end
1577 @implementation NSValue (Mine)
1578 - (id)_prefix_initWithTwoDoubles:(TwoDoubles)twoDoubles
1580   return [self init];
1582 @end
1584 void rdar9726279(void) {
1585   TwoDoubles twoDoubles = { 0.0, 0.0 };
1586   NSValue *value = [[NSValue alloc] _prefix_initWithTwoDoubles:twoDoubles];
1587   [value release];
1590 // Test camelcase support for CF conventions.  While Core Foundation APIs
1591 // don't use camel casing, other code is allowed to use it.
1592 CFArrayRef camelcase_create_1(void) {
1593   return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1596 CFArrayRef camelcase_createno(void) {
1597   return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1600 CFArrayRef camelcase_copy(void) {
1601   return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1604 CFArrayRef camelcase_copying(void) {
1605   return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1608 CFArrayRef copyCamelCase(void) {
1609   return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1612 CFArrayRef __copyCamelCase(void) {
1613   return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1616 CFArrayRef __createCamelCase(void) {
1617   return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1620 CFArrayRef camel_create(void) {
1621   return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1625 CFArrayRef camel_creat(void) {
1626   return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1629 CFArrayRef camel_copy(void) {
1630   return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1633 CFArrayRef camel_copyMachine(void) {
1634   return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1637 CFArrayRef camel_copymachine(void) {
1638   return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1641 @protocol F18P
1642 - (id) clone;
1643 @end
1644 @interface F18 : NSObject<F18P> @end
1645 @interface F18(Cat)
1646 - (id) clone NS_RETURNS_RETAINED;
1647 @end
1649 @implementation F18
1650 - (id) clone {
1651   return [F18 alloc];
1653 @end
1655 void rdar6582778(void) {
1656   CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
1657   CFTypeRef vals[] = { CFDateCreate(0, t) }; // expected-warning {{leak}}
1660 CFTypeRef global;
1662 void rdar6582778_2(void) {
1663   CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
1664   global = CFDateCreate(0, t); // no-warning
1667 // Test that objects passed to containers are marked "escaped".
1668 void rdar10232019(void) {
1669   NSMutableArray *array = [NSMutableArray array];
1671   NSString *string = [[NSString alloc] initWithUTF8String:"foo"];
1672   [array addObject:string];
1673   [string release];
1675   NSString *otherString = [string stringByAppendingString:@"bar"]; // no-warning
1676   NSLog(@"%@", otherString);
1679 void rdar10232019_positive(void) {
1680   NSMutableArray *array = [NSMutableArray array];
1682   NSString *string = [[NSString alloc] initWithUTF8String:"foo"];
1683   [string release];
1685   NSString *otherString = [string stringByAppendingString:@"bar"]; // expected-warning {{Reference-counted object is used after it is release}}
1686   NSLog(@"%@", otherString);
1689 // RetainCountChecker support for XPC.
1690 typedef void * xpc_object_t;
1691 xpc_object_t _CFXPCCreateXPCObjectFromCFObject(CFTypeRef cf);
1692 void xpc_release(xpc_object_t object);
1694 void rdar9658496(void) {
1695   CFStringRef cf;
1696   xpc_object_t xpc;
1697   cf = CFStringCreateWithCString( ((CFAllocatorRef)0), "test", kCFStringEncodingUTF8 ); // no-warning
1698   xpc = _CFXPCCreateXPCObjectFromCFObject( cf );
1699   CFRelease(cf);
1700   xpc_release(xpc);
1703 // Support annotations with method families.
1704 @interface RDar10824732 : NSObject
1705 - (id)initWithObj:(id CF_CONSUMED)obj;
1706 @end
1708 @implementation RDar10824732
1709 - (id)initWithObj:(id)obj {
1710   [obj release];
1711   return [super init];
1713 @end
1715 void rdar_10824732(void) {
1716   @autoreleasepool {
1717     NSString *obj = @"test";
1718     RDar10824732 *foo = [[RDar10824732 alloc] initWithObj:obj]; // no-warning
1719     [foo release];
1720   }
1723 // Stop tracking objects passed to functions, which take callbacks as parameters.
1724 typedef int (*CloseCallback) (void *);
1725 void ReaderForIO(CloseCallback ioclose, void *ioctx);
1726 int IOClose(void *context);
1728 @protocol SInS <NSObject>
1729 @end
1731 @interface radar10973977 : NSObject
1732 - (id<SInS>)inputS;
1733 - (void)reader;
1734 @end
1736 @implementation radar10973977
1737 - (void)reader
1739     id<SInS> inputS = [[self inputS] retain];
1740     ReaderForIO(IOClose, inputS);
1742 - (id<SInS>)inputS
1744     return 0;
1746 @end
1748 // Object escapes through a selector callback
1749 extern id NSApp;
1750 @interface MySheetController
1751 - (id<SInS>)inputS;
1752 - (void)showDoSomethingSheetAction:(id)action;
1753 - (void)sheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo;
1754 @end
1756 @implementation MySheetController
1757 - (id<SInS>)inputS {
1758     return 0;
1760 - (void)showDoSomethingSheetAction:(id)action {
1761   id<SInS> inputS = [[self inputS] retain]; 
1762   [NSApp beginSheet:0
1763          modalForWindow:0
1764          modalDelegate:0
1765          didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:)
1766          contextInfo:(void *)inputS]; // no - warning
1768 - (void)sheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo {
1769    
1770       id contextObject = (id)contextInfo;
1771       [contextObject release];
1774 - (id)copyAutoreleaseRadar13081402 {
1775   id x = [[[NSString alloc] initWithUTF8String:"foo"] autorelease];
1776   [x retain];
1777   return x; // no warning
1780 @end
1781 //===----------------------------------------------------------------------===//
1782 // Test returning allocated memory in a struct.
1784 // We currently don't have a general way to track pointers that "escape".
1785 // Here we test that RetainCountChecker doesn't get excited about returning
1786 // allocated CF objects in struct fields.
1787 //===----------------------------------------------------------------------===//
1788 void *malloc(size_t);
1789 struct rdar11104566 { CFStringRef myStr; };
1790 struct rdar11104566 test_rdar11104566(void) {
1791   CFStringRef cf = CFStringCreateWithCString( ((CFAllocatorRef)0), "test", kCFStringEncodingUTF8 ); // no-warning
1792   struct rdar11104566 V;
1793   V.myStr = cf;
1794   return V; // no-warning
1797 struct rdar11104566 *test_2_rdar11104566(void) {
1798   CFStringRef cf = CFStringCreateWithCString( ((CFAllocatorRef)0), "test", kCFStringEncodingUTF8 ); // no-warning
1799   struct rdar11104566 *V = (struct rdar11104566 *) malloc(sizeof(*V));
1800   V->myStr = cf;
1801   return V; // no-warning
1804 //===----------------------------------------------------------------------===//
1805 // ObjC literals support.
1806 //===----------------------------------------------------------------------===//
1808 void test_objc_arrays(void) {
1809     { // CASE ONE -- OBJECT IN ARRAY CREATED DIRECTLY
1810         NSObject *o = [[NSObject alloc] init];
1811         NSArray *a = [[NSArray alloc] initWithObjects:o, (void*)0]; // expected-warning {{leak}}
1812         [o release];
1813         [a description];
1814         [o description];
1815     }
1817     { // CASE TWO -- OBJECT IN ARRAY CREATED BY DUPING AUTORELEASED ARRAY
1818         NSObject *o = [[NSObject alloc] init];
1819         NSArray *a1 = [NSArray arrayWithObjects:o, (void*)0];
1820         NSArray *a2 = [[NSArray alloc] initWithArray:a1]; // expected-warning {{leak}}
1821         [o release];        
1822         [a2 description];
1823         [o description];
1824     }
1826     { // CASE THREE -- OBJECT IN RETAINED @[]
1827         NSObject *o = [[NSObject alloc] init];
1828         NSArray *a3 = [@[o] retain]; // expected-warning {{leak}}
1829         [o release];        
1830         [a3 description];
1831         [o description];
1832     }
1833     
1834     { // CASE FOUR -- OBJECT IN ARRAY CREATED BY DUPING @[]
1835         NSObject *o = [[NSObject alloc] init];
1836         NSArray *a = [[NSArray alloc] initWithArray:@[o]]; // expected-warning {{leak}}
1837         [o release];
1838         
1839         [a description];
1840         [o description];
1841     }
1842     
1843     { // CASE FIVE -- OBJECT IN RETAINED @{}
1844         NSValue *o = [[NSValue alloc] init];
1845         NSDictionary *a = [@{o : o} retain]; // expected-warning {{leak}}
1846         [o release];
1847         
1848         [a description];
1849         [o description];
1850     }
1853 void test_objc_integer_literals(void) {
1854   id value = [@1 retain]; // expected-warning {{leak}}
1855   [value description];
1858 void test_objc_boxed_expressions(int x, const char *y) {
1859   id value = [@(x) retain]; // expected-warning {{leak}}
1860   [value description];
1862   value = [@(y) retain]; // expected-warning {{leak}}
1863   [value description];
1866 // Test NSLog doesn't escape tracked objects.
1867 void rdar11400885(int y)
1869   @autoreleasepool {
1870     NSString *printString;
1871     if(y > 2)
1872       printString = [[NSString alloc] init];
1873     else
1874       printString = [[NSString alloc] init];
1875     NSLog(@"Once %@", printString);
1876     [printString release];
1877     NSLog(@"Again: %@", printString); // expected-warning {{Reference-counted object is used after it is released}}
1878   }
1881 id makeCollectableNonLeak(void) {
1882   extern CFTypeRef CFCreateSomething(void);
1884   CFTypeRef object = CFCreateSomething(); // +1
1885   CFRetain(object); // +2
1886   id objCObject = NSMakeCollectable(object); // +2
1887   [objCObject release]; // +1
1888   return [objCObject autorelease]; // +0
1892 void consumeAndStopTracking(id NS_CONSUMED obj, void (^callback)(void));
1893 void CFConsumeAndStopTracking(CFTypeRef CF_CONSUMED obj, void (^callback)(void));
1895 void testConsumeAndStopTracking(void) {
1896   id retained = [@[] retain]; // +1
1897   consumeAndStopTracking(retained, ^{}); // no-warning
1899   id doubleRetained = [[@[] retain] retain]; // +2
1900   consumeAndStopTracking(doubleRetained, ^{
1901     [doubleRetained release];
1902   }); // no-warning
1904   id unretained = @[]; // +0
1905   consumeAndStopTracking(unretained, ^{}); // expected-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
1908 void testCFConsumeAndStopTracking(void) {
1909   id retained = [@[] retain]; // +1
1910   CFConsumeAndStopTracking((CFTypeRef)retained, ^{}); // no-warning
1912   id doubleRetained = [[@[] retain] retain]; // +2
1913   CFConsumeAndStopTracking((CFTypeRef)doubleRetained, ^{
1914     [doubleRetained release];
1915   }); // no-warning
1917   id unretained = @[]; // +0
1918   CFConsumeAndStopTracking((CFTypeRef)unretained, ^{}); // expected-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
1920 //===----------------------------------------------------------------------===//
1921 // Test 'pragma clang arc_cf_code_audited' support.
1922 //===----------------------------------------------------------------------===//
1924 typedef void *MyCFType;
1925 #pragma clang arc_cf_code_audited begin
1926 MyCFType CreateMyCFType(void);
1927 #pragma clang arc_cf_code_audited end 
1928     
1929 void test_custom_cf(void) {
1930   MyCFType x = CreateMyCFType(); // expected-warning {{leak of an object stored into 'x'}}
1933 //===----------------------------------------------------------------------===//
1934 // Test calling CFPlugInInstanceCreate, which appears in CF but doesn't
1935 // return a CF object.
1936 //===----------------------------------------------------------------------===//
1938 void test_CFPlugInInstanceCreate(CFUUIDRef factoryUUID, CFUUIDRef typeUUID) {
1939   CFPlugInInstanceCreate(kCFAllocatorDefault, factoryUUID, typeUUID); // no-warning
1942 //===----------------------------------------------------------------------===//
1943 // PR14927: -drain only has retain-count semantics on NSAutoreleasePool.
1944 //===----------------------------------------------------------------------===//
1946 @interface PR14927 : NSObject
1947 - (void)drain;
1948 @end
1950 void test_drain(void) {
1951   PR14927 *obj = [[PR14927 alloc] init];
1952   [obj drain];
1953   [obj release]; // no-warning
1956 //===----------------------------------------------------------------------===//
1957 // Allow cf_returns_retained and cf_returns_not_retained to mark a return
1958 // value as tracked, even if the object isn't a known CF type.
1959 //===----------------------------------------------------------------------===//
1961 MyCFType getCustom(void) __attribute__((cf_returns_not_retained));
1962 MyCFType makeCustom(void) __attribute__((cf_returns_retained));
1964 void testCustomReturnsRetained(void) {
1965   MyCFType obj = makeCustom(); // expected-warning {{leak of an object stored into 'obj'}}
1968 void testCustomReturnsNotRetained(void) {
1969   CFRelease(getCustom()); // expected-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
1972 //===----------------------------------------------------------------------===//
1973 // Don't print variables which are out of the current scope.
1974 //===----------------------------------------------------------------------===//
1975 @interface MyObj12706177 : NSObject
1976 -(id)initX;
1977 +(void)test12706177;
1978 @end
1979 static int Cond;
1980 @implementation MyObj12706177
1981 -(id)initX {
1982   if (Cond)
1983     return 0;
1984   self = [super init];
1985   return self;
1987 +(void)test12706177 {
1988   id x = [[MyObj12706177 alloc] initX]; //expected-warning {{Potential leak of an object}}
1989   [x release]; 
1991 @end
1993 //===----------------------------------------------------------------------===//
1994 // xpc_connection_set_finalizer_f
1995 //===----------------------------------------------------------------------===//
1996 typedef xpc_object_t xpc_connection_t;
1997 typedef void (*xpc_finalizer_t)(void *value);
1998 void xpc_connection_set_context(xpc_connection_t connection, void *ctx);
1999 void xpc_connection_set_finalizer_f(xpc_connection_t connection,
2000                                     xpc_finalizer_t finalizer);
2001 void releaseAfterXPC(void *context) {
2002   [(NSArray *)context release];
2005 void rdar13783514(xpc_connection_t connection) {
2006   xpc_connection_set_context(connection, [[NSMutableArray alloc] init]);
2007   xpc_connection_set_finalizer_f(connection, releaseAfterXPC);
2008 } // no-warning
2010 CFAttributedStringRef CFAttributedCreate(void *CFObj CF_CONSUMED) CF_RETURNS_RETAINED;
2012 @interface Action
2013 - (SEL)action;
2014 - (void)setAction:(SEL)aSelector;
2015 - (id) target;
2016 - (void)setTarget:(id)aTarget;
2017 @end