[clang] Handle __declspec() attributes in using
[llvm-project.git] / clang / test / ARCMT / objcmt-arc-cf-annotations.m
blob6b394e3b33ea349c72a35c98c51925e73e8b1f3b
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 // <rdar://problem/6659160>
612 int isFoo(char c);
614 static void rdar_6659160(char *inkind, char *inname)
616   // We currently expect that [NSObject alloc] cannot fail.  This
617   // will be a toggled flag in the future.  It can indeed return null, but
618   // Cocoa programmers generally aren't expected to reason about out-of-memory
619   // conditions.
620   NSString *kind = [[NSString alloc] initWithUTF8String:inkind];  // expected-warning{{leak}}
621   
622   // We do allow stringWithUTF8String to fail.  This isn't really correct, as
623   // far as returning 0.  In most error conditions it will throw an exception.
624   // If allocation fails it could return 0, but again this
625   // isn't expected.
626   NSString *name = [NSString stringWithUTF8String:inname];
627   if(!name)
628     return;
630   const char *kindC = 0;
631   const char *nameC = 0;
632   
633   // In both cases, we cannot reach a point down below where we
634   // dereference kindC or nameC with either being null.  This is because
635   // we assume that [NSObject alloc] doesn't fail and that we have the guard
636   // up above.
637   
638   if(kind)
639     kindC = [kind UTF8String];
640   if(name)
641     nameC = [name UTF8String];
642   if(!isFoo(kindC[0])) // expected-warning{{null}}
643     return;
644   if(!isFoo(nameC[0])) // no-warning
645     return;
647   [kind release];
648   [name release]; // expected-warning{{Incorrect decrement of the reference count}}
651 // PR 3677 - 'allocWithZone' should be treated as following the Cocoa naming
652 //  conventions with respect to 'return'ing ownership.
653 @interface PR3677: NSObject @end
654 @implementation PR3677
655 + (id)allocWithZone:(NSZone *)inZone {
656   return [super allocWithZone:inZone];  // no-warning
658 @end
660 // PR 3820 - Reason about calls to -dealloc
661 void pr3820_DeallocInsteadOfRelease(void)
663   id foo = [[NSString alloc] init]; // no-warning
664   [foo dealloc];
665   // foo is not leaked, since it has been deallocated.
668 void pr3820_ReleaseAfterDealloc(void)
670   id foo = [[NSString alloc] init];
671   [foo dealloc];
672   [foo release];  // expected-warning{{used after it is release}}
673   // NSInternalInconsistencyException: message sent to deallocated object
676 void pr3820_DeallocAfterRelease(void)
678   NSLog(@"\n\n[%s]", __FUNCTION__);
679   id foo = [[NSString alloc] init];
680   [foo release];
681   [foo dealloc]; // expected-warning{{used after it is released}}
682   // message sent to released object
685 // From <rdar://problem/6704930>.  The problem here is that 'length' binds to
686 // '($0 - 1)' after '--length', but SimpleConstraintManager doesn't know how to
687 // reason about '($0 - 1) > constant'.  As a temporary hack, we drop the value
688 // of '($0 - 1)' and conjure a new symbol.
689 void rdar6704930(unsigned char *s, unsigned int length) {
690   NSString* name = 0;
691   if (s != 0) {
692     if (length > 0) {
693       while (length > 0) {
694         if (*s == ':') {
695           ++s;
696           --length;
697           name = [[NSString alloc] init]; // no-warning
698           break;
699         }
700         ++s;
701         --length;
702       }
703       if ((length == 0) && (name != 0)) {
704         [name release];
705         name = 0;
706       }
707       if (length == 0) { // no ':' found -> use it all as name
708         name = [[NSString alloc] init]; // no-warning
709       }
710     }
711   }
713   if (name != 0) {
714     [name release];
715   }
718 //===----------------------------------------------------------------------===//
719 // <rdar://problem/6833332>
720 // One build of the analyzer accidentally stopped tracking the allocated
721 // object after the 'retain'.
722 //===----------------------------------------------------------------------===//
724 @interface rdar_6833332 : NSObject <NSApplicationDelegate> {
725     NSWindow *window;
727 @property (nonatomic, retain) NSWindow *window;
728 @end
730 @implementation rdar_6833332
731 @synthesize window;
732 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
733  NSMutableDictionary *dict = [[NSMutableDictionary dictionaryWithCapacity:4] retain]; // expected-warning{{leak}}
735  [dict setObject:@"foo" forKey:@"bar"];
737  NSLog(@"%@", dict);
739 - (void)dealloc {
740     [window release];
741     [super dealloc];
744 - (void)radar10102244 {
745  NSMutableDictionary *dict = [[NSMutableDictionary dictionaryWithCapacity:4] retain]; // expected-warning{{leak}} 
746  if (window) 
747    NSLog(@"%@", window);    
749 @end
751 //===----------------------------------------------------------------------===//
752 // <rdar://problem/6257780> clang checker fails to catch use-after-release
753 //===----------------------------------------------------------------------===//
755 int rdar_6257780_Case1(void) {
756   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
757   NSArray *array = [NSArray array];
758   [array release]; // expected-warning{{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
759   [pool drain];
760   return 0;
763 //===----------------------------------------------------------------------===//
764 // <rdar://problem/10640253> Analyzer is confused about NSAutoreleasePool -allocWithZone:.
765 //===----------------------------------------------------------------------===//
767 void rdar_10640253_autorelease_allocWithZone(void) {
768     NSAutoreleasePool *pool = [[NSAutoreleasePool allocWithZone:(NSZone*)0] init];
769     (void) pool;
772 //===----------------------------------------------------------------------===//
773 // <rdar://problem/6866843> Checker should understand new/setObject:/release constructs
774 //===----------------------------------------------------------------------===//
776 void rdar_6866843(void) {
777  NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
778  NSMutableDictionary* dictionary = [[NSMutableDictionary alloc] init];
779  NSArray* array = [[NSArray alloc] init];
780  [dictionary setObject:array forKey:@"key"];
781  [array release];
782  // Using 'array' here should be fine
783  NSLog(@"array = %@\n", array); // no-warning
784  // Now the array is released
785  [dictionary release];
786  [pool drain];
790 //===----------------------------------------------------------------------===//
791 // <rdar://problem/6877235> Classes typedef-ed to CF objects should get the same treatment as CF objects
792 //===----------------------------------------------------------------------===//
794 typedef CFTypeRef OtherRef;
796 @interface RDar6877235 : NSObject {}
797 - (CFTypeRef)_copyCFTypeRef;
798 - (OtherRef)_copyOtherRef;
799 @end
801 @implementation RDar6877235
802 - (CFTypeRef)_copyCFTypeRef {
803   return [[NSString alloc] init]; // no-warning
805 - (OtherRef)_copyOtherRef {
806   return [[NSString alloc] init]; // no-warning
808 @end
810 //===----------------------------------------------------------------------===//
811 // <rdar://problem/6320065> false positive - init method returns an object
812 // owned by caller
813 //===----------------------------------------------------------------------===//
815 @interface RDar6320065 : NSObject {
816   NSString *_foo;
818 - (id)initReturningNewClass;
819 - (id)_initReturningNewClassBad;
820 - (id)initReturningNewClassBad2;
821 @end
823 @interface RDar6320065Subclass : RDar6320065
824 @end
826 @implementation RDar6320065
827 - (id)initReturningNewClass {
828   [self release];
829   self = [[RDar6320065Subclass alloc] init]; // no-warning
830   return self;
832 - (id)_initReturningNewClassBad {
833   [self release];
834   [[RDar6320065Subclass alloc] init]; // expected-warning {{leak}}
835   return self;
837 - (id)initReturningNewClassBad2 {
838   [self release];
839   self = [[RDar6320065Subclass alloc] init];
840   return [self autorelease]; // expected-warning{{Object with a +0 retain count returned to caller where a +1 (owning) retain count is expected}}
843 @end
845 @implementation RDar6320065Subclass
846 @end
848 int RDar6320065_test(void) {
849   RDar6320065 *test = [[RDar6320065 alloc] init]; // no-warning
850   [test release];
851   return 0;
854 //===----------------------------------------------------------------------===//
855 // <rdar://problem/7129086> -awakeAfterUsingCoder: returns an owned object 
856 //  and claims the receiver
857 //===----------------------------------------------------------------------===//
859 @interface RDar7129086 : NSObject {} @end
860 @implementation RDar7129086
861 - (id)awakeAfterUsingCoder:(NSCoder *)aDecoder {
862   [self release]; // no-warning
863   return [NSString alloc];  // no-warning
865 @end
867 //===----------------------------------------------------------------------===//
868 // <rdar://problem/6859457> [NSData dataWithBytesNoCopy] does not return a
869 //  retained object
870 //===----------------------------------------------------------------------===//
872 @interface RDar6859457 : NSObject {}
873 - (NSString*) NoCopyString;
874 - (NSString*) noCopyString;
875 @end
877 @implementation RDar6859457 
878 - (NSString*) NoCopyString { return [[NSString alloc] init]; } // expected-warning{{leak}}
879 - (NSString*) noCopyString { return [[NSString alloc] init]; } // expected-warning{{leak}}
880 @end
882 void test_RDar6859457(RDar6859457 *x, void *bytes, NSUInteger dataLength) {
883   [x NoCopyString]; // expected-warning{{leak}}
884   [x noCopyString]; // expected-warning{{leak}}
885   [NSData dataWithBytesNoCopy:bytes length:dataLength];  // no-warning
886   [NSData dataWithBytesNoCopy:bytes length:dataLength freeWhenDone:1]; // no-warning
889 //===----------------------------------------------------------------------===//
890 // PR 4230 - an autorelease pool is not necessarily leaked during a premature
891 //  return
892 //===----------------------------------------------------------------------===//
894 static void PR4230(void)
896   NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // no-warning
897   NSString *object = [[[NSString alloc] init] autorelease]; // no-warning
898   return;
901 static void PR4230_new(void)
903   NSAutoreleasePool *pool = [NSAutoreleasePool new]; // no-warning
904   NSString *object = [[[NSString alloc] init] autorelease]; // no-warning
905   return;
908 //===----------------------------------------------------------------------===//
909 // Method name that has a null IdentifierInfo* for its first selector slot.
910 // This test just makes sure that we handle it.
911 //===----------------------------------------------------------------------===//
913 @interface TestNullIdentifier
914 @end
916 @implementation TestNullIdentifier
917 + (id):(int)x, ... {
918   return [[NSString alloc] init]; // expected-warning{{leak}}
920 @end
922 //===----------------------------------------------------------------------===//
923 // <rdar://problem/6893565> don't flag leaks for return types that cannot be 
924 //                          determined to be CF types
925 //===----------------------------------------------------------------------===//
927 // We don't know if 'struct s6893565' represents a Core Foundation type, so
928 // we shouldn't emit an error here.
929 typedef struct s6893565* TD6893565;
931 @interface RDar6893565 {}
932 -(TD6893565)newThing;
933 @end
935 @implementation RDar6893565
936 -(TD6893565)newThing {  
937   return (TD6893565) [[NSString alloc] init]; // no-warning
939 @end
941 //===----------------------------------------------------------------------===//
942 // <rdar://problem/6902710> clang: false positives w/QC and CoreImage methods
943 //===----------------------------------------------------------------------===//
945 void rdar6902710(QCView *view, QCRenderer *renderer, CIContext *context,
946                  NSString *str, CIImage *img, CGRect rect,
947                  CIFormat form, CGColorSpaceRef cs) {
948   [view createSnapshotImageOfType:str]; // expected-warning{{leak}}
949   [renderer createSnapshotImageOfType:str]; // expected-warning{{leak}}
950   [context createCGImage:img fromRect:rect]; // expected-warning{{leak}}
951   [context createCGImage:img fromRect:rect format:form colorSpace:cs]; // expected-warning{{leak}}
954 //===----------------------------------------------------------------------===//
955 // <rdar://problem/6945561> -[CIContext createCGLayerWithSize:info:]
956 //                           misinterpreted by clang scan-build
957 //===----------------------------------------------------------------------===//
959 void rdar6945561(CIContext *context, CGSize size, CFDictionaryRef d) {
960   [context createCGLayerWithSize:size info:d]; // expected-warning{{leak}}
963 //===----------------------------------------------------------------------===//
964 // <rdar://problem/6961230> add knowledge of IOKit functions to retain/release 
965 //                          checker
966 //===----------------------------------------------------------------------===//
968 void IOBSDNameMatching_wrapper(mach_port_t mainPort, uint32_t options,  const char * bsdName) {  
969   IOBSDNameMatching(mainPort, options, bsdName); // expected-warning{{leak}}
972 void IOServiceMatching_wrapper(const char * name) {
973   IOServiceMatching(name); // expected-warning{{leak}}
976 void IOServiceNameMatching_wrapper(const char * name) {
977   IOServiceNameMatching(name); // expected-warning{{leak}}
980 CF_RETURNS_RETAINED CFDictionaryRef CreateDict(void);
982 void IOServiceAddNotification_wrapper(mach_port_t mainPort, const io_name_t notificationType,
983   mach_port_t wakePort, uintptr_t reference, io_iterator_t * notification ) {
985   CFDictionaryRef matching = CreateDict();
986   CFRelease(matching);
987   IOServiceAddNotification(mainPort, notificationType, matching, // expected-warning{{used after it is released}} expected-warning{{deprecated}}
988                            wakePort, reference, notification);
991 void IORegistryEntryIDMatching_wrapper(uint64_t entryID ) {
992   IORegistryEntryIDMatching(entryID); // expected-warning{{leak}}
995 void IOOpenFirmwarePathMatching_wrapper(mach_port_t mainPort, uint32_t options,
996                                         const char * path) {
997   IOOpenFirmwarePathMatching(mainPort, options, path); // expected-warning{{leak}}
1000 void IOServiceGetMatchingService_wrapper(mach_port_t mainPort) {
1001   CFDictionaryRef matching = CreateDict();
1002   IOServiceGetMatchingService(mainPort, matching);
1003   CFRelease(matching); // expected-warning{{used after it is released}}
1006 void IOServiceGetMatchingServices_wrapper(mach_port_t mainPort, io_iterator_t *existing) {
1007   CFDictionaryRef matching = CreateDict();
1008   IOServiceGetMatchingServices(mainPort, matching, existing);
1009   CFRelease(matching); // expected-warning{{used after it is released}}
1012 void IOServiceAddMatchingNotification_wrapper(IONotificationPortRef notifyPort, const io_name_t notificationType, 
1013   IOServiceMatchingCallback callback, void * refCon, io_iterator_t * notification) {
1014     
1015   CFDictionaryRef matching = CreateDict();
1016   IOServiceAddMatchingNotification(notifyPort, notificationType, matching, callback, refCon, notification);
1017   CFRelease(matching); // expected-warning{{used after it is released}}
1020 //===----------------------------------------------------------------------===//
1021 // Test of handling objects whose references "escape" to containers.
1022 //===----------------------------------------------------------------------===//
1024 void CFDictionaryAddValue(CFMutableDictionaryRef, void *, void *);
1026 // <rdar://problem/6539791>
1027 void rdar_6539791(CFMutableDictionaryRef y, void* key, void* val_key) {
1028   CFMutableDictionaryRef x = CFDictionaryCreateMutable(kCFAllocatorDefault, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
1029   CFDictionaryAddValue(y, key, x);
1030   CFRelease(x); // the dictionary keeps a reference, so the object isn't deallocated yet
1031   signed z = 1;
1032   CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z);
1033   if (value) {
1034     CFDictionaryAddValue(x, val_key, (void*)value); // no-warning
1035     CFRelease(value);
1036     CFDictionaryAddValue(y, val_key, (void*)value); // no-warning
1037   }
1040 // <rdar://problem/6560661>
1041 // Same issue, except with "AppendValue" functions.
1042 void rdar_6560661(CFMutableArrayRef x) {
1043   signed z = 1;
1044   CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z);
1045   // CFArrayAppendValue keeps a reference to value.
1046   CFArrayAppendValue(x, value);
1047   CFRelease(value);
1048   CFRetain(value);
1049   CFRelease(value); // no-warning
1052 // <rdar://problem/7152619>
1053 // Same issue, excwept with "CFAttributeStringSetAttribute".
1054 void rdar_7152619(CFStringRef str) {
1055   CFAttributedStringRef string = CFAttributedStringCreate(kCFAllocatorDefault, str, 0);
1056   CFMutableAttributedStringRef attrString = CFAttributedStringCreateMutableCopy(kCFAllocatorDefault, 100, string);
1057   CFRelease(string);
1058   NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1059   CFAttributedStringSetAttribute(attrString, CFRangeMake(0, 1), str, number);
1060   [number release];
1061   [number retain];
1062   CFRelease(attrString);  
1065 //===----------------------------------------------------------------------===//
1066 // Test of handling CGGradientXXX functions.
1067 //===----------------------------------------------------------------------===//
1069 void rdar_7184450(CGContextRef myContext, CGFloat x, CGPoint myStartPoint,
1070                   CGPoint myEndPoint) {
1071   size_t num_locations = 6;
1072   CGFloat locations[6] = { 0.0, 0.265, 0.28, 0.31, 0.36, 1.0 };
1073   CGFloat components[28] = { 239.0/256.0, 167.0/256.0, 170.0/256.0,
1074      x,  // Start color
1075     207.0/255.0, 39.0/255.0, 39.0/255.0, x,
1076     147.0/255.0, 21.0/255.0, 22.0/255.0, x,
1077     175.0/255.0, 175.0/255.0, 175.0/255.0, x,
1078     255.0/255.0,255.0/255.0, 255.0/255.0, x,
1079     255.0/255.0,255.0/255.0, 255.0/255.0, x
1080   }; // End color
1081   
1082   CGGradientRef myGradient =
1083     CGGradientCreateWithColorComponents(CGColorSpaceCreateDeviceRGB(), // expected-warning{{leak}}
1084       components, locations, num_locations);
1086   CGContextDrawLinearGradient(myContext, myGradient, myStartPoint, myEndPoint,
1087                               0);
1088   CGGradientRelease(myGradient);
1091 void rdar_7184450_pos(CGContextRef myContext, CGFloat x, CGPoint myStartPoint,
1092                   CGPoint myEndPoint) {
1093   size_t num_locations = 6;
1094   CGFloat locations[6] = { 0.0, 0.265, 0.28, 0.31, 0.36, 1.0 };
1095   CGFloat components[28] = { 239.0/256.0, 167.0/256.0, 170.0/256.0,
1096      x,  // Start color
1097     207.0/255.0, 39.0/255.0, 39.0/255.0, x,
1098     147.0/255.0, 21.0/255.0, 22.0/255.0, x,
1099     175.0/255.0, 175.0/255.0, 175.0/255.0, x,
1100     255.0/255.0,255.0/255.0, 255.0/255.0, x,
1101     255.0/255.0,255.0/255.0, 255.0/255.0, x
1102   }; // End color
1103   
1104   CGGradientRef myGradient =
1105    CGGradientCreateWithColorComponents(CGColorSpaceCreateDeviceRGB(), components, locations, num_locations); // expected-warning 2 {{leak}}
1107   CGContextDrawLinearGradient(myContext, myGradient, myStartPoint, myEndPoint,
1108                               0);
1111 //===----------------------------------------------------------------------===//
1112 // <rdar://problem/7299394> clang false positive: retained instance passed to
1113 //                          thread in pthread_create marked as leak
1115 // Until we have full IPA, the analyzer should stop tracking the reference
1116 // count of objects passed to pthread_create.
1118 //===----------------------------------------------------------------------===//
1120 struct _opaque_pthread_t {};
1121 struct _opaque_pthread_attr_t {};
1122 typedef struct _opaque_pthread_t *__darwin_pthread_t;
1123 typedef struct _opaque_pthread_attr_t __darwin_pthread_attr_t;
1124 typedef __darwin_pthread_t pthread_t;
1125 typedef __darwin_pthread_attr_t pthread_attr_t;
1126 typedef unsigned long __darwin_pthread_key_t;
1127 typedef __darwin_pthread_key_t pthread_key_t;
1129 int pthread_create(pthread_t *, const pthread_attr_t *,
1130                    void *(*)(void *), void *);
1132 int pthread_setspecific(pthread_key_t key, const void *value);
1134 void *rdar_7299394_start_routine(void *p) {
1135   [((id) p) release];
1136   return 0;
1138 void rdar_7299394(pthread_attr_t *attr, pthread_t *thread, void *args) {
1139   NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1140   pthread_create(thread, attr, rdar_7299394_start_routine, number);
1142 void rdar_7299394_positive(pthread_attr_t *attr, pthread_t *thread) {
1143   NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1146 //===----------------------------------------------------------------------===//
1147 // <rdar://problem/11282706> false positive with not understanding thread
1148 // local storage
1149 //===----------------------------------------------------------------------===//
1151 void rdar11282706(pthread_key_t key) {
1152   NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1153   pthread_setspecific(key, (void*) number);
1156 //===----------------------------------------------------------------------===//
1157 // <rdar://problem/7283567> False leak associated with call to 
1158 //                          CVPixelBufferCreateWithBytes ()
1160 // According to the Core Video Reference (ADC), CVPixelBufferCreateWithBytes and
1161 // CVPixelBufferCreateWithPlanarBytes can release (via a callback) the
1162 // pixel buffer object.  These test cases show how the analyzer stops tracking
1163 // the reference count for the objects passed for this argument.  This
1164 // could be made smarter.
1165 //===----------------------------------------------------------------------===//
1167 typedef int int32_t;
1168 typedef UInt32 FourCharCode;
1169 typedef FourCharCode OSType;
1170 typedef uint64_t CVOptionFlags;
1171 typedef int32_t CVReturn;
1172 typedef struct __CVBuffer *CVBufferRef;
1173 typedef CVBufferRef CVImageBufferRef;
1174 typedef CVImageBufferRef CVPixelBufferRef;
1175 typedef void (*CVPixelBufferReleaseBytesCallback)( void *releaseRefCon, const void *baseAddress );
1177 extern CVReturn CVPixelBufferCreateWithBytes(CFAllocatorRef allocator,
1178             size_t width,
1179             size_t height,
1180             OSType pixelFormatType,
1181             void *baseAddress,
1182             size_t bytesPerRow,
1183             CVPixelBufferReleaseBytesCallback releaseCallback,
1184             void *releaseRefCon,
1185             CFDictionaryRef pixelBufferAttributes,
1186                    CVPixelBufferRef *pixelBufferOut) ;
1188 typedef void (*CVPixelBufferReleasePlanarBytesCallback)( void *releaseRefCon, const void *dataPtr, size_t dataSize, size_t numberOfPlanes, const void *planeAddresses[] );
1190 extern CVReturn CVPixelBufferCreateWithPlanarBytes(CFAllocatorRef allocator,
1191         size_t width,
1192         size_t height,
1193         OSType pixelFormatType,
1194         void *dataPtr,
1195         size_t dataSize,
1196         size_t numberOfPlanes,
1197         void *planeBaseAddress[],
1198         size_t planeWidth[],
1199         size_t planeHeight[],
1200         size_t planeBytesPerRow[],
1201         CVPixelBufferReleasePlanarBytesCallback releaseCallback,
1202         void *releaseRefCon,
1203         CFDictionaryRef pixelBufferAttributes,
1204         CVPixelBufferRef *pixelBufferOut) ;
1206 extern CVReturn CVPixelBufferCreateWithBytes(CFAllocatorRef allocator,
1207             size_t width,
1208             size_t height,
1209             OSType pixelFormatType,
1210             void *baseAddress,
1211             size_t bytesPerRow,
1212             CVPixelBufferReleaseBytesCallback releaseCallback,
1213             void *releaseRefCon,
1214             CFDictionaryRef pixelBufferAttributes,
1215                    CVPixelBufferRef *pixelBufferOut) ;
1217 CVReturn rdar_7283567(CFAllocatorRef allocator, size_t width, size_t height,
1218                       OSType pixelFormatType, void *baseAddress,
1219                       size_t bytesPerRow,
1220                       CVPixelBufferReleaseBytesCallback releaseCallback,
1221                       CFDictionaryRef pixelBufferAttributes,
1222                       CVPixelBufferRef *pixelBufferOut) {
1224   // For the allocated object, it doesn't really matter what type it is
1225   // for the purpose of this test.  All we want to show is that
1226   // this is freed later by the callback.
1227   NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1228   
1229   return CVPixelBufferCreateWithBytes(allocator, width, height, pixelFormatType,
1230                                 baseAddress, bytesPerRow, releaseCallback,
1231                                 number, // potentially released by callback
1232                                 pixelBufferAttributes, pixelBufferOut) ;
1235 CVReturn rdar_7283567_2(CFAllocatorRef allocator, size_t width, size_t height,
1236         OSType pixelFormatType, void *dataPtr, size_t dataSize,
1237         size_t numberOfPlanes, void *planeBaseAddress[],
1238         size_t planeWidth[], size_t planeHeight[], size_t planeBytesPerRow[],
1239         CVPixelBufferReleasePlanarBytesCallback releaseCallback,
1240         CFDictionaryRef pixelBufferAttributes,
1241         CVPixelBufferRef *pixelBufferOut) {
1242     
1243     // For the allocated object, it doesn't really matter what type it is
1244     // for the purpose of this test.  All we want to show is that
1245     // this is freed later by the callback.
1246     NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1248     return CVPixelBufferCreateWithPlanarBytes(allocator,
1249               width, height, pixelFormatType, dataPtr, dataSize,
1250               numberOfPlanes, planeBaseAddress, planeWidth,
1251               planeHeight, planeBytesPerRow, releaseCallback,
1252               number, // potentially released by callback
1253               pixelBufferAttributes, pixelBufferOut) ;
1256 //===----------------------------------------------------------------------===//
1257 // <rdar://problem/7358899> False leak associated with 
1258 //  CGBitmapContextCreateWithData
1259 //===----------------------------------------------------------------------===//
1260 typedef uint32_t CGBitmapInfo;
1261 typedef void (*CGBitmapContextReleaseDataCallback)(void *releaseInfo, void *data);
1262     
1263 CGContextRef CGBitmapContextCreateWithData(void *data,
1264     size_t width, size_t height, size_t bitsPerComponent,
1265     size_t bytesPerRow, CGColorSpaceRef space, CGBitmapInfo bitmapInfo,
1266     CGBitmapContextReleaseDataCallback releaseCallback, void *releaseInfo);
1268 void rdar_7358899(void *data,
1269       size_t width, size_t height, size_t bitsPerComponent,
1270       size_t bytesPerRow, CGColorSpaceRef space, CGBitmapInfo bitmapInfo,
1271       CGBitmapContextReleaseDataCallback releaseCallback) {
1273     // For the allocated object, it doesn't really matter what type it is
1274     // for the purpose of this test.  All we want to show is that
1275     // this is freed later by the callback.
1276     NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1278   CGBitmapContextCreateWithData(data, width, height, bitsPerComponent, // expected-warning{{leak}}
1279     bytesPerRow, space, bitmapInfo, releaseCallback, number);
1282 //===----------------------------------------------------------------------===//
1283 // <rdar://problem/7265711> allow 'new', 'copy', 'alloc', 'init' prefix to
1284 //  start before '_' when determining Cocoa fundamental rule
1286 // Previously the retain/release checker just skipped prefixes before the
1287 // first '_' entirely.  Now the checker honors the prefix if it results in a
1288 // recognizable naming convention (e.g., 'new', 'init').
1289 //===----------------------------------------------------------------------===//
1291 @interface RDar7265711 {}
1292 - (id) new_stuff;
1293 @end
1295 void rdar7265711_a(RDar7265711 *x) {
1296   id y = [x new_stuff]; // expected-warning{{leak}}
1299 void rdar7265711_b(RDar7265711 *x) {
1300   id y = [x new_stuff]; // no-warning
1301   [y release];
1304 //===----------------------------------------------------------------------===//
1305 // <rdar://problem/7306898> clang thinks [NSCursor dragCopyCursor] returns a
1306 //                          retained reference
1307 //===----------------------------------------------------------------------===//
1309 @interface NSCursor : NSObject
1310 + (NSCursor *)dragCopyCursor;
1311 @end
1313 void rdar7306898(void) {
1314   // 'dragCopyCursor' does not follow Cocoa's fundamental rule.  It is a noun, not an sentence
1315   // implying a 'copy' of something.
1316   NSCursor *c =  [NSCursor dragCopyCursor]; // no-warning
1317   NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1320 //===----------------------------------------------------------------------===//
1321 // <rdar://problem/7252064> sending 'release', 'retain', etc. to a Class
1322 // directly is not likely what the user intended
1323 //===----------------------------------------------------------------------===//
1325 @interface RDar7252064 : NSObject @end
1326 void rdar7252064(void) {
1327   [RDar7252064 release]; // expected-warning{{The 'release' message should be sent to instances of class 'RDar7252064' and not the class directly}}
1328   [RDar7252064 retain]; // expected-warning{{The 'retain' message should be sent to instances of class 'RDar7252064' and not the class directly}}
1329   [RDar7252064 autorelease]; // expected-warning{{The 'autorelease' message should be sent to instances of class 'RDar7252064' and not the class directly}}
1330   [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}}
1333 //===----------------------------------------------------------------------===//
1334 // Tests of ownership attributes.
1335 //===----------------------------------------------------------------------===//
1337 typedef NSString* MyStringTy;
1339 @protocol FooP;
1341 @interface TestOwnershipAttr : NSObject
1342 - (NSString*) returnsAnOwnedString  NS_RETURNS_RETAINED; // no-warning
1343 - (NSString*) returnsAnOwnedCFString  CF_RETURNS_RETAINED; // no-warning
1344 - (MyStringTy) returnsAnOwnedTypedString NS_RETURNS_RETAINED; // no-warning
1345 - (NSString*) newString NS_RETURNS_NOT_RETAINED; // no-warning
1346 - (NSString*) newString_auto NS_RETURNS_AUTORELEASED; // no-warning
1347 - (NSString*) newStringNoAttr;
1348 - (int) returnsAnOwnedInt NS_RETURNS_RETAINED; // expected-warning{{'ns_returns_retained' attribute only applies to methods that return an Objective-C object}}
1349 - (id) pseudoInit NS_CONSUMES_SELF NS_RETURNS_RETAINED;
1350 + (void) consume:(id) NS_CONSUMED x;
1351 + (void) consume2:(id) CF_CONSUMED x;
1352 @end
1354 static int ownership_attribute_doesnt_go_here NS_RETURNS_RETAINED; // expected-warning{{'ns_returns_retained' attribute only applies to functions and methods}}
1356 void test_attr_1(TestOwnershipAttr *X) {
1357   NSString *str = [X returnsAnOwnedString]; // expected-warning{{leak}}
1360 void test_attr_1b(TestOwnershipAttr *X) {
1361   NSString *str = [X returnsAnOwnedCFString]; // expected-warning{{leak}}
1364 void test_attr1c(TestOwnershipAttr *X) {
1365   NSString *str = [X newString]; // no-warning
1366   NSString *str2 = [X newStringNoAttr]; // expected-warning{{leak}}
1367   NSString *str3 = [X newString_auto]; // no-warning
1368   NSString *str4 = [[X newString_auto] retain]; // expected-warning {{leak}}
1371 void testattr2_a(void) {
1372   TestOwnershipAttr *x = [TestOwnershipAttr alloc]; // expected-warning{{leak}}
1375 void testattr2_b(void) {
1376   TestOwnershipAttr *x = [[TestOwnershipAttr alloc] pseudoInit];  // expected-warning{{leak}}
1379 void testattr2_b_11358224_self_assign_looses_the_leak(void) {
1380   TestOwnershipAttr *x = [[TestOwnershipAttr alloc] pseudoInit];// expected-warning{{leak}}
1381   x = x;
1384 void testattr2_c(void) {
1385   TestOwnershipAttr *x = [[TestOwnershipAttr alloc] pseudoInit]; // no-warning
1386   [x release];
1389 void testattr3(void) {
1390   TestOwnershipAttr *x = [TestOwnershipAttr alloc]; // no-warning
1391   [TestOwnershipAttr consume:x];
1392   TestOwnershipAttr *y = [TestOwnershipAttr alloc]; // no-warning
1393   [TestOwnershipAttr consume2:y];
1396 void consume_ns(id NS_CONSUMED x);
1397 void consume_cf(id CF_CONSUMED x);
1399 void testattr4(void) {
1400   TestOwnershipAttr *x = [TestOwnershipAttr alloc]; // no-warning
1401   consume_ns(x);
1402   TestOwnershipAttr *y = [TestOwnershipAttr alloc]; // no-warning
1403   consume_cf(y);
1406 @interface TestOwnershipAttr2 : NSObject
1407 - (NSString*) newString NS_RETURNS_NOT_RETAINED; // no-warning
1408 @end
1410 @implementation TestOwnershipAttr2
1411 - (NSString*) newString {
1412   return [NSString alloc]; // expected-warning {{Potential leak of an object}}
1414 @end
1416 @interface MyClassTestCFAttr : NSObject {}
1417 - (NSDate*) returnsCFRetained CF_RETURNS_RETAINED;
1418 - (CFDateRef) returnsCFRetainedAsCF CF_RETURNS_RETAINED;
1419 - (CFDateRef) newCFRetainedAsCF CF_RETURNS_NOT_RETAINED;
1420 - (CFDateRef) newCFRetainedAsCFNoAttr;
1421 - (NSDate*) alsoReturnsRetained;
1422 - (CFDateRef) alsoReturnsRetainedAsCF;
1423 - (NSDate*) returnsNSRetained NS_RETURNS_RETAINED;
1424 @end
1426 CF_RETURNS_RETAINED
1427 CFDateRef returnsRetainedCFDate(void)  {
1428   return CFDateCreate(0, CFAbsoluteTimeGetCurrent());
1431 @implementation MyClassTestCFAttr
1432 - (NSDate*) returnsCFRetained {
1433   return (NSDate*) returnsRetainedCFDate(); // No leak.
1436 - (CFDateRef) returnsCFRetainedAsCF {
1437   return returnsRetainedCFDate(); // No leak.
1440 - (CFDateRef) newCFRetainedAsCF {
1441   return (CFDateRef)[(id)[self returnsCFRetainedAsCF] autorelease];
1444 - (CFDateRef) newCFRetainedAsCFNoAttr {
1445   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}}
1448 - (NSDate*) alsoReturnsRetained {
1449   return (NSDate*) returnsRetainedCFDate(); // expected-warning{{leak}}
1452 - (CFDateRef) alsoReturnsRetainedAsCF {
1453   return returnsRetainedCFDate(); // expected-warning{{leak}}
1457 - (NSDate*) returnsNSRetained {
1458   return (NSDate*) returnsRetainedCFDate(); // no-warning
1460 @end
1462 //===----------------------------------------------------------------------===//
1463 // Test that leaks post-dominated by "panic" functions are not reported.
1465 // <rdar://problem/5905851> do not report a leak when post-dominated by a call
1466 // to a noreturn or panic function
1467 //===----------------------------------------------------------------------===//
1469 void panic(void) __attribute__((noreturn));
1470 void panic_not_in_hardcoded_list(void) __attribute__((noreturn));
1472 void test_panic_negative(void) {
1473   signed z = 1;
1474   CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z);  // expected-warning{{leak}}
1477 void test_panic_positive(void) {
1478   signed z = 1;
1479   CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // no-warning
1480   panic();
1483 void test_panic_neg_2(int x) {
1484   signed z = 1;
1485   CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // expected-warning{{leak}}
1486   if (x)
1487     panic();
1490 void test_panic_pos_2(int x) {
1491   signed z = 1;
1492   CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // no-warning
1493   if (x)
1494     panic();
1495   if (!x) {
1496     // This showed up in <rdar://problem/7796563>, where we silently missed checking
1497     // the function type for noreturn.  "panic()" is a hard-coded known panic function
1498     // that isn't always noreturn.
1499     panic_not_in_hardcoded_list();
1500   }
1503 //===----------------------------------------------------------------------===//
1504 // Test uses of blocks (closures)
1505 //===----------------------------------------------------------------------===//
1507 void test_blocks_1_pos(void) {
1508   NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1509   ^{}();
1512 void test_blocks_1_indirect_release(void) {
1513   NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1514   ^{ [number release]; }();
1517 void test_blocks_1_indirect_retain(void) {
1518   // Eventually this should be reported as a leak.
1519   NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1520   ^{ [number retain]; }();
1523 void test_blocks_1_indirect_release_via_call(void) {
1524   NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1525   ^(NSObject *o){ [o release]; }(number);
1528 void test_blocks_1_indirect_retain_via_call(void) {
1529   NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning {{leak}}
1530   ^(NSObject *o){ [o retain]; }(number);
1533 //===--------------------------------------------------------------------===//
1534 // Test sending message to super that returns an object alias.  Previously
1535 // this caused a crash in the analyzer.
1536 //===--------------------------------------------------------------------===//
1538 @interface Rdar8015556 : NSObject {} @end
1539 @implementation Rdar8015556
1540 - (id)retain {
1541   return [super retain];
1543 @end
1545 // <rdar://problem/8272168> - Correcly handle Class<...> in Cocoa Conventions
1546 // detector.
1548 @protocol Prot_R8272168 @end
1549 Class <Prot_R8272168> GetAClassThatImplementsProt_R8272168(void);
1550 void r8272168(void) {
1551   GetAClassThatImplementsProt_R8272168();
1554 // Test case for <rdar://problem/8356342>, which in the past triggered
1555 // a false positive.
1556 @interface RDar8356342
1557 - (NSDate*) rdar8356342:(NSDate *)inValue;
1558 @end
1560 @implementation RDar8356342
1561 - (NSDate*) rdar8356342:(NSDate*)inValue {
1562   NSDate *outValue = inValue;
1563   if (outValue == 0)
1564     outValue = [[NSDate alloc] init]; // no-warning
1566   if (outValue != inValue)
1567     [outValue autorelease];
1569   return outValue;
1571 @end
1573 // <rdar://problem/8724287> - This test case previously crashed because
1574 // of a bug in BugReporter.
1575 extern const void *CFDictionaryGetValue(CFDictionaryRef theDict, const void *key);
1576 typedef struct __CFError * CFErrorRef;
1577 extern const CFStringRef kCFErrorUnderlyingErrorKey;
1578 extern CFDictionaryRef CFErrorCopyUserInfo(CFErrorRef err);
1579 static void rdar_8724287(CFErrorRef error)
1581     CFErrorRef error_to_dump;
1583     error_to_dump = error;
1584     while (error_to_dump != ((void*)0)) {
1585         CFDictionaryRef info;
1587         info = CFErrorCopyUserInfo(error_to_dump); // expected-warning{{Potential leak of an object}}
1589         if (info != ((void*)0)) {
1590         }
1592         error_to_dump = (CFErrorRef) CFDictionaryGetValue(info, kCFErrorUnderlyingErrorKey);
1593     }
1596 // <rdar://problem/9234108> - Make sure the model applies cf_consumed
1597 // correctly in argument positions besides the first.
1598 extern void *CFStringCreate(void);
1599 extern void rdar_9234108_helper(void *key, void * CF_CONSUMED value);
1600 void rdar_9234108(void) {
1601   rdar_9234108_helper(0, CFStringCreate());
1604 // <rdar://problem/9726279> - Make sure that objc_method_family works
1605 // to override naming conventions.
1606 struct TwoDoubles {
1607   double one;
1608   double two;
1610 typedef struct TwoDoubles TwoDoubles;
1612 @interface NSValue (Mine)
1613 - (id)_prefix_initWithTwoDoubles:(TwoDoubles)twoDoubles __attribute__((objc_method_family(init)));
1614 @end
1616 @implementation NSValue (Mine)
1617 - (id)_prefix_initWithTwoDoubles:(TwoDoubles)twoDoubles
1619   return [self init];
1621 @end
1623 void rdar9726279(void) {
1624   TwoDoubles twoDoubles = { 0.0, 0.0 };
1625   NSValue *value = [[NSValue alloc] _prefix_initWithTwoDoubles:twoDoubles];
1626   [value release];
1629 // <rdar://problem/9732321>
1630 // Test camelcase support for CF conventions.  While Core Foundation APIs
1631 // don't use camel casing, other code is allowed to use it.
1632 CFArrayRef camelcase_create_1(void) {
1633   return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1636 CFArrayRef camelcase_createno(void) {
1637   return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1640 CFArrayRef camelcase_copy(void) {
1641   return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1644 CFArrayRef camelcase_copying(void) {
1645   return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1648 CFArrayRef copyCamelCase(void) {
1649   return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1652 CFArrayRef __copyCamelCase(void) {
1653   return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1656 CFArrayRef __createCamelCase(void) {
1657   return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1660 CFArrayRef camel_create(void) {
1661   return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1665 CFArrayRef camel_creat(void) {
1666   return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1669 CFArrayRef camel_copy(void) {
1670   return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1673 CFArrayRef camel_copyMachine(void) {
1674   return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1677 CFArrayRef camel_copymachine(void) {
1678   return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1681 // rdar://problem/8024350
1682 @protocol F18P
1683 - (id) clone;
1684 @end
1685 @interface F18 : NSObject<F18P> @end
1686 @interface F18(Cat)
1687 - (id) clone NS_RETURNS_RETAINED;
1688 @end
1690 @implementation F18
1691 - (id) clone {
1692   return [F18 alloc];
1694 @end
1696 // Radar 6582778.
1697 void rdar6582778(void) {
1698   CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
1699   CFTypeRef vals[] = { CFDateCreate(0, t) }; // expected-warning {{leak}}
1702 CFTypeRef global;
1704 void rdar6582778_2(void) {
1705   CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
1706   global = CFDateCreate(0, t); // no-warning
1709 // <rdar://problem/10232019> - Test that objects passed to containers
1710 // are marked "escaped".
1712 void rdar10232019(void) {
1713   NSMutableArray *array = [NSMutableArray array];
1715   NSString *string = [[NSString alloc] initWithUTF8String:"foo"];
1716   [array addObject:string];
1717   [string release];
1719   NSString *otherString = [string stringByAppendingString:@"bar"]; // no-warning
1720   NSLog(@"%@", otherString);
1723 void rdar10232019_positive(void) {
1724   NSMutableArray *array = [NSMutableArray array];
1726   NSString *string = [[NSString alloc] initWithUTF8String:"foo"];
1727   [string release];
1729   NSString *otherString = [string stringByAppendingString:@"bar"]; // expected-warning {{Reference-counted object is used after it is release}}
1730   NSLog(@"%@", otherString);
1733 // RetainCountChecker support for XPC.
1734 // <rdar://problem/9658496>
1735 typedef void * xpc_object_t;
1736 xpc_object_t _CFXPCCreateXPCObjectFromCFObject(CFTypeRef cf);
1737 void xpc_release(xpc_object_t object);
1739 void rdar9658496(void) {
1740   CFStringRef cf;
1741   xpc_object_t xpc;
1742   cf = CFStringCreateWithCString( ((CFAllocatorRef)0), "test", kCFStringEncodingUTF8 ); // no-warning
1743   xpc = _CFXPCCreateXPCObjectFromCFObject( cf );
1744   CFRelease(cf);
1745   xpc_release(xpc);
1748 // Support annotations with method families.
1749 @interface RDar10824732 : NSObject
1750 - (id)initWithObj:(id CF_CONSUMED)obj;
1751 @end
1753 @implementation RDar10824732
1754 - (id)initWithObj:(id)obj {
1755   [obj release];
1756   return [super init];
1758 @end
1760 void rdar_10824732(void) {
1761   @autoreleasepool {
1762     NSString *obj = @"test";
1763     RDar10824732 *foo = [[RDar10824732 alloc] initWithObj:obj]; // no-warning
1764     [foo release];
1765   }
1768 // Stop tracking objects passed to functions, which take callbacks as parameters.
1769 // radar://10973977
1770 typedef int (*CloseCallback) (void *);
1771 void ReaderForIO(CloseCallback ioclose, void *ioctx);
1772 int IOClose(void *context);
1774 @protocol SInS <NSObject>
1775 @end
1777 @interface radar10973977 : NSObject
1778 - (id<SInS>)inputS;
1779 - (void)reader;
1780 @end
1782 @implementation radar10973977
1783 - (void)reader
1785     id<SInS> inputS = [[self inputS] retain];
1786     ReaderForIO(IOClose, inputS);
1788 - (id<SInS>)inputS
1790     return 0;
1792 @end
1794 // Object escapes through a selector callback: radar://11398514
1795 extern id NSApp;
1796 @interface MySheetController
1797 - (id<SInS>)inputS;
1798 - (void)showDoSomethingSheetAction:(id)action;
1799 - (void)sheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo;
1800 @end
1802 @implementation MySheetController
1803 - (id<SInS>)inputS {
1804     return 0;
1806 - (void)showDoSomethingSheetAction:(id)action {
1807   id<SInS> inputS = [[self inputS] retain]; 
1808   [NSApp beginSheet:0
1809          modalForWindow:0
1810          modalDelegate:0
1811          didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:)
1812          contextInfo:(void *)inputS]; // no - warning
1814 - (void)sheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo {
1815    
1816       id contextObject = (id)contextInfo;
1817       [contextObject release];
1820 - (id)copyAutoreleaseRadar13081402 {
1821   id x = [[[NSString alloc] initWithUTF8String:"foo"] autorelease];
1822   [x retain];
1823   return x; // no warning
1826 @end
1827 //===----------------------------------------------------------------------===//
1828 // Test returning allocated memory in a struct.
1830 // We currently don't have a general way to track pointers that "escape".
1831 // Here we test that RetainCountChecker doesn't get excited about returning
1832 // allocated CF objects in struct fields.
1833 //===----------------------------------------------------------------------===//
1834 void *malloc(size_t);
1835 struct rdar11104566 { CFStringRef myStr; };
1836 struct rdar11104566 test_rdar11104566(void) {
1837   CFStringRef cf = CFStringCreateWithCString( ((CFAllocatorRef)0), "test", kCFStringEncodingUTF8 ); // no-warning
1838   struct rdar11104566 V;
1839   V.myStr = cf;
1840   return V; // no-warning
1843 struct rdar11104566 *test_2_rdar11104566(void) {
1844   CFStringRef cf = CFStringCreateWithCString( ((CFAllocatorRef)0), "test", kCFStringEncodingUTF8 ); // no-warning
1845   struct rdar11104566 *V = (struct rdar11104566 *) malloc(sizeof(*V));
1846   V->myStr = cf;
1847   return V; // no-warning
1850 //===----------------------------------------------------------------------===//
1851 // ObjC literals support.
1852 //===----------------------------------------------------------------------===//
1854 void test_objc_arrays(void) {
1855     { // CASE ONE -- OBJECT IN ARRAY CREATED DIRECTLY
1856         NSObject *o = [[NSObject alloc] init];
1857         NSArray *a = [[NSArray alloc] initWithObjects:o, (void*)0]; // expected-warning {{leak}}
1858         [o release];
1859         [a description];
1860         [o description];
1861     }
1863     { // CASE TWO -- OBJECT IN ARRAY CREATED BY DUPING AUTORELEASED ARRAY
1864         NSObject *o = [[NSObject alloc] init];
1865         NSArray *a1 = [NSArray arrayWithObjects:o, (void*)0];
1866         NSArray *a2 = [[NSArray alloc] initWithArray:a1]; // expected-warning {{leak}}
1867         [o release];        
1868         [a2 description];
1869         [o description];
1870     }
1872     { // CASE THREE -- OBJECT IN RETAINED @[]
1873         NSObject *o = [[NSObject alloc] init];
1874         NSArray *a3 = [@[o] retain]; // expected-warning {{leak}}
1875         [o release];        
1876         [a3 description];
1877         [o description];
1878     }
1879     
1880     { // CASE FOUR -- OBJECT IN ARRAY CREATED BY DUPING @[]
1881         NSObject *o = [[NSObject alloc] init];
1882         NSArray *a = [[NSArray alloc] initWithArray:@[o]]; // expected-warning {{leak}}
1883         [o release];
1884         
1885         [a description];
1886         [o description];
1887     }
1888     
1889     { // CASE FIVE -- OBJECT IN RETAINED @{}
1890         NSValue *o = [[NSValue alloc] init];
1891         NSDictionary *a = [@{o : o} retain]; // expected-warning {{leak}}
1892         [o release];
1893         
1894         [a description];
1895         [o description];
1896     }
1899 void test_objc_integer_literals(void) {
1900   id value = [@1 retain]; // expected-warning {{leak}}
1901   [value description];
1904 void test_objc_boxed_expressions(int x, const char *y) {
1905   id value = [@(x) retain]; // expected-warning {{leak}}
1906   [value description];
1908   value = [@(y) retain]; // expected-warning {{leak}}
1909   [value description];
1912 // Test NSLog doesn't escape tracked objects.
1913 void rdar11400885(int y)
1915   @autoreleasepool {
1916     NSString *printString;
1917     if(y > 2)
1918       printString = [[NSString alloc] init];
1919     else
1920       printString = [[NSString alloc] init];
1921     NSLog(@"Once %@", printString);
1922     [printString release];
1923     NSLog(@"Again: %@", printString); // expected-warning {{Reference-counted object is used after it is released}}
1924   }
1927 id makeCollectableNonLeak(void) {
1928   extern CFTypeRef CFCreateSomething(void);
1930   CFTypeRef object = CFCreateSomething(); // +1
1931   CFRetain(object); // +2
1932   id objCObject = NSMakeCollectable(object); // +2
1933   [objCObject release]; // +1
1934   return [objCObject autorelease]; // +0
1938 void consumeAndStopTracking(id NS_CONSUMED obj, void (^callback)(void));
1939 void CFConsumeAndStopTracking(CFTypeRef CF_CONSUMED obj, void (^callback)(void));
1941 void testConsumeAndStopTracking(void) {
1942   id retained = [@[] retain]; // +1
1943   consumeAndStopTracking(retained, ^{}); // no-warning
1945   id doubleRetained = [[@[] retain] retain]; // +2
1946   consumeAndStopTracking(doubleRetained, ^{
1947     [doubleRetained release];
1948   }); // no-warning
1950   id unretained = @[]; // +0
1951   consumeAndStopTracking(unretained, ^{}); // expected-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
1954 void testCFConsumeAndStopTracking(void) {
1955   id retained = [@[] retain]; // +1
1956   CFConsumeAndStopTracking((CFTypeRef)retained, ^{}); // no-warning
1958   id doubleRetained = [[@[] retain] retain]; // +2
1959   CFConsumeAndStopTracking((CFTypeRef)doubleRetained, ^{
1960     [doubleRetained release];
1961   }); // no-warning
1963   id unretained = @[]; // +0
1964   CFConsumeAndStopTracking((CFTypeRef)unretained, ^{}); // expected-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
1966 //===----------------------------------------------------------------------===//
1967 // Test 'pragma clang arc_cf_code_audited' support.
1968 //===----------------------------------------------------------------------===//
1970 typedef void *MyCFType;
1971 #pragma clang arc_cf_code_audited begin
1972 MyCFType CreateMyCFType(void);
1973 #pragma clang arc_cf_code_audited end 
1974     
1975 void test_custom_cf(void) {
1976   MyCFType x = CreateMyCFType(); // expected-warning {{leak of an object stored into 'x'}}
1979 //===----------------------------------------------------------------------===//
1980 // Test calling CFPlugInInstanceCreate, which appears in CF but doesn't
1981 // return a CF object.
1982 //===----------------------------------------------------------------------===//
1984 void test_CFPlugInInstanceCreate(CFUUIDRef factoryUUID, CFUUIDRef typeUUID) {
1985   CFPlugInInstanceCreate(kCFAllocatorDefault, factoryUUID, typeUUID); // no-warning
1988 //===----------------------------------------------------------------------===//
1989 // PR14927: -drain only has retain-count semantics on NSAutoreleasePool.
1990 //===----------------------------------------------------------------------===//
1992 @interface PR14927 : NSObject
1993 - (void)drain;
1994 @end
1996 void test_drain(void) {
1997   PR14927 *obj = [[PR14927 alloc] init];
1998   [obj drain];
1999   [obj release]; // no-warning
2002 //===----------------------------------------------------------------------===//
2003 // Allow cf_returns_retained and cf_returns_not_retained to mark a return
2004 // value as tracked, even if the object isn't a known CF type.
2005 //===----------------------------------------------------------------------===//
2007 MyCFType getCustom(void) __attribute__((cf_returns_not_retained));
2008 MyCFType makeCustom(void) __attribute__((cf_returns_retained));
2010 void testCustomReturnsRetained(void) {
2011   MyCFType obj = makeCustom(); // expected-warning {{leak of an object stored into 'obj'}}
2014 void testCustomReturnsNotRetained(void) {
2015   CFRelease(getCustom()); // expected-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
2018 //===----------------------------------------------------------------------===//
2019 // Don't print variables which are out of the current scope.
2020 //===----------------------------------------------------------------------===//
2021 @interface MyObj12706177 : NSObject
2022 -(id)initX;
2023 +(void)test12706177;
2024 @end
2025 static int Cond;
2026 @implementation MyObj12706177
2027 -(id)initX {
2028   if (Cond)
2029     return 0;
2030   self = [super init];
2031   return self;
2033 +(void)test12706177 {
2034   id x = [[MyObj12706177 alloc] initX]; //expected-warning {{Potential leak of an object}}
2035   [x release]; 
2037 @end
2039 //===----------------------------------------------------------------------===//
2040 // <rdar://problem/13783514> xpc_connection_set_finalizer_f
2041 //===----------------------------------------------------------------------===//
2043 typedef xpc_object_t xpc_connection_t;
2044 typedef void (*xpc_finalizer_t)(void *value);
2045 void xpc_connection_set_context(xpc_connection_t connection, void *ctx);
2046 void xpc_connection_set_finalizer_f(xpc_connection_t connection,
2047                                     xpc_finalizer_t finalizer);
2048 void releaseAfterXPC(void *context) {
2049   [(NSArray *)context release];
2052 void rdar13783514(xpc_connection_t connection) {
2053   xpc_connection_set_context(connection, [[NSMutableArray alloc] init]);
2054   xpc_connection_set_finalizer_f(connection, releaseAfterXPC);
2055 } // no-warning
2057 CFAttributedStringRef CFAttributedCreate(void *CFObj CF_CONSUMED) CF_RETURNS_RETAINED;
2059 @interface Action
2060 - (SEL)action;
2061 - (void)setAction:(SEL)aSelector;
2062 - (id) target;
2063 - (void)setTarget:(id)aTarget;
2064 @end