]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - test/Analysis/retain-release.m
Vendor import of clang trunk r351319 (just before the release_80 branch
[FreeBSD/FreeBSD.git] / test / Analysis / retain-release.m
1 // RUN: rm -f %t.objc.plist %t.objcpp.plist
2 // RUN: %clang_analyze_cc1 -triple x86_64-apple-darwin10\
3 // RUN:     -analyzer-checker=core,osx.coreFoundation.CFRetainRelease\
4 // RUN:     -analyzer-checker=osx.cocoa.ClassRelease,osx.cocoa.RetainCount\
5 // RUN:     -analyzer-checker=debug.ExprInspection -fblocks -verify %s\
6 // RUN:     -Wno-objc-root-class -analyzer-output=plist -o %t.objc.plist
7 // RUN: %clang_analyze_cc1 -triple x86_64-apple-darwin10\
8 // RUN:     -analyzer-checker=core,osx.coreFoundation.CFRetainRelease\
9 // RUN:     -analyzer-checker=osx.cocoa.ClassRelease,osx.cocoa.RetainCount\
10 // RUN:     -analyzer-checker=debug.ExprInspection -fblocks -verify %s\
11 // RUN:     -Wno-objc-root-class -analyzer-output=plist -o %t.objcpp.plist\
12 // RUN:     -x objective-c++ -std=gnu++98
13 // RUN: cat %t.objcpp.plist | %diff_plist %S/Inputs/expected-plists/retain-release.m.objcpp.plist -
14 // RUN: cat %t.objc.plist | %diff_plist %S/Inputs/expected-plists/retain-release.m.objc.plist -
15
16 void clang_analyzer_eval(int);
17
18 #if __has_feature(attribute_ns_returns_retained)
19 #define NS_RETURNS_RETAINED __attribute__((ns_returns_retained))
20 #endif
21 #if __has_feature(attribute_cf_returns_retained)
22 #define CF_RETURNS_RETAINED __attribute__((cf_returns_retained))
23 #endif
24 #if __has_feature(attribute_ns_returns_not_retained)
25 #define NS_RETURNS_NOT_RETAINED __attribute__((ns_returns_not_retained))
26 #endif
27 #if __has_feature(attribute_cf_returns_not_retained)
28 #define CF_RETURNS_NOT_RETAINED __attribute__((cf_returns_not_retained))
29 #endif
30 #if __has_feature(attribute_ns_consumes_self)
31 #define NS_CONSUMES_SELF __attribute__((ns_consumes_self))
32 #endif
33 #if __has_feature(attribute_ns_consumed)
34 #define NS_CONSUMED __attribute__((ns_consumed))
35 #endif
36 #if __has_feature(attribute_cf_consumed)
37 #define CF_CONSUMED __attribute__((cf_consumed))
38 #endif
39 #if __has_attribute(ns_returns_autoreleased)
40 #define NS_RETURNS_AUTORELEASED __attribute__((ns_returns_autoreleased))
41 #endif
42
43 //===----------------------------------------------------------------------===//
44 // The following code is reduced using delta-debugging from Mac OS X headers:
45 //
46 // #include <Cocoa/Cocoa.h>
47 // #include <CoreFoundation/CoreFoundation.h>
48 // #include <DiskArbitration/DiskArbitration.h>
49 // #include <QuartzCore/QuartzCore.h>
50 // #include <Quartz/Quartz.h>
51 // #include <IOKit/IOKitLib.h>
52 //
53 // It includes the basic definitions for the test cases below.
54 //===----------------------------------------------------------------------===//
55
56 typedef unsigned int __darwin_natural_t;
57 typedef unsigned long uintptr_t;
58 typedef unsigned int uint32_t;
59 typedef unsigned long long uint64_t;
60 typedef unsigned int UInt32;
61 typedef signed long CFIndex;
62 typedef CFIndex CFByteOrder;
63 typedef struct {
64     CFIndex location;
65     CFIndex length;
66 } CFRange;
67 static __inline__ __attribute__((always_inline)) CFRange CFRangeMake(CFIndex loc, CFIndex len) {
68     CFRange range;
69     range.location = loc;
70     range.length = len;
71     return range;
72 }
73 typedef const void * CFTypeRef;
74 typedef const struct __CFString * CFStringRef;
75 typedef const struct __CFAllocator * CFAllocatorRef;
76 extern const CFAllocatorRef kCFAllocatorDefault;
77
78 extern CFTypeRef CFRetain(CFTypeRef cf);
79 extern void CFRelease(CFTypeRef cf);
80 extern CFTypeRef CFMakeCollectable(CFTypeRef cf);
81 extern CFTypeRef CFAutorelease(CFTypeRef CF_CONSUMED cf);
82
83 typedef struct {
84 }
85 CFArrayCallBacks;
86 extern const CFArrayCallBacks kCFTypeArrayCallBacks;
87 typedef const struct __CFArray * CFArrayRef;
88 typedef struct __CFArray * CFMutableArrayRef;
89 extern CFMutableArrayRef CFArrayCreateMutable(CFAllocatorRef allocator, CFIndex capacity, const CFArrayCallBacks *callBacks);
90 extern const void *CFArrayGetValueAtIndex(CFArrayRef theArray, CFIndex idx);
91 extern void CFArrayAppendValue(CFMutableArrayRef theArray, const void *value);
92 typedef struct {
93 }
94 CFDictionaryKeyCallBacks;
95 extern const CFDictionaryKeyCallBacks kCFTypeDictionaryKeyCallBacks;
96 typedef struct {
97 }
98 CFDictionaryValueCallBacks;
99 extern const CFDictionaryValueCallBacks kCFTypeDictionaryValueCallBacks;
100 typedef const struct __CFDictionary * CFDictionaryRef;
101 typedef struct __CFDictionary * CFMutableDictionaryRef;
102 extern CFMutableDictionaryRef CFDictionaryCreateMutable(CFAllocatorRef allocator, CFIndex capacity, const CFDictionaryKeyCallBacks *keyCallBacks, const CFDictionaryValueCallBacks *valueCallBacks);
103 typedef UInt32 CFStringEncoding;
104 enum {
105 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  };
106 extern CFStringRef CFStringCreateWithCString(CFAllocatorRef alloc, const char *cStr, CFStringEncoding encoding);
107 typedef double CFTimeInterval;
108 typedef CFTimeInterval CFAbsoluteTime;
109 extern CFAbsoluteTime CFAbsoluteTimeGetCurrent(void);
110 typedef const struct __CFDate * CFDateRef;
111 extern CFDateRef CFDateCreate(CFAllocatorRef allocator, CFAbsoluteTime at);
112 extern CFAbsoluteTime CFDateGetAbsoluteTime(CFDateRef theDate);
113 typedef __darwin_natural_t natural_t;
114 typedef natural_t mach_port_name_t;
115 typedef mach_port_name_t mach_port_t;
116 typedef int kern_return_t;
117 typedef kern_return_t mach_error_t;
118 enum {
119 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    };
120 typedef CFIndex CFNumberType;
121 typedef const struct __CFNumber * CFNumberRef;
122 extern CFNumberRef CFNumberCreate(CFAllocatorRef allocator, CFNumberType theType, const void *valuePtr);
123 typedef const struct __CFAttributedString *CFAttributedStringRef;
124 typedef struct __CFAttributedString *CFMutableAttributedStringRef;
125 extern CFAttributedStringRef CFAttributedStringCreate(CFAllocatorRef alloc, CFStringRef str, CFDictionaryRef attributes) ;
126 extern CFMutableAttributedStringRef CFAttributedStringCreateMutableCopy(CFAllocatorRef alloc, CFIndex maxLength, CFAttributedStringRef aStr) ;
127 extern void CFAttributedStringSetAttribute(CFMutableAttributedStringRef aStr, CFRange range, CFStringRef attrName, CFTypeRef value) ;
128 typedef signed char BOOL;
129 typedef unsigned long NSUInteger;
130 @class NSString, Protocol;
131 extern void NSLog(NSString *format, ...) __attribute__((format(__NSString__, 1, 2)));
132 typedef struct _NSZone NSZone;
133 @class NSInvocation, NSMethodSignature, NSCoder, NSString, NSEnumerator;
134 @protocol NSObject
135 - (BOOL)isEqual:(id)object;
136 - (id)retain;
137 - (oneway void)release;
138 - (id)autorelease;
139 - (NSString *)description;
140 - (id)init;
141 @end
142 @protocol NSCopying 
143 - (id)copyWithZone:(NSZone *)zone;
144 @end
145 @protocol NSMutableCopying  - (id)mutableCopyWithZone:(NSZone *)zone;
146 @end
147 @protocol NSCoding  - (void)encodeWithCoder:(NSCoder *)aCoder;
148 @end
149 @interface NSObject <NSObject> {}
150 + (id)allocWithZone:(NSZone *)zone;
151 + (id)alloc;
152 + (id)new;
153 - (void)dealloc;
154 @end
155 @interface NSObject (NSCoderMethods)
156 - (id)awakeAfterUsingCoder:(NSCoder *)aDecoder;
157 @end
158 extern id NSAllocateObject(Class aClass, NSUInteger extraBytes, NSZone *zone);
159 typedef struct {
160 }
161 NSFastEnumerationState;
162 @protocol NSFastEnumeration 
163 - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len;
164 @end
165 @class NSString, NSDictionary;
166 @interface NSValue : NSObject <NSCopying, NSCoding>  - (void)getValue:(void *)value;
167 @end
168 @interface NSNumber : NSValue
169 - (char)charValue;
170 - (id)initWithInt:(int)value;
171 + (NSNumber *)numberWithInt:(int)value;
172 @end
173 @class NSString;
174 @interface NSArray : NSObject <NSCopying, NSMutableCopying, NSCoding, NSFastEnumeration>
175 - (NSUInteger)count;
176 - (id)initWithObjects:(const id [])objects count:(NSUInteger)cnt;
177 + (id)arrayWithObject:(id)anObject;
178 + (id)arrayWithObjects:(const id [])objects count:(NSUInteger)cnt;
179 + (id)arrayWithObjects:(id)firstObj, ... __attribute__((sentinel(0,1)));
180 - (id)initWithObjects:(id)firstObj, ... __attribute__((sentinel(0,1)));
181 - (id)initWithArray:(NSArray *)array;
182 @end  @interface NSArray (NSArrayCreation)  + (id)array;
183 @end       @interface NSAutoreleasePool : NSObject {
184 }
185 - (void)drain;
186 @end extern NSString * const NSBundleDidLoadNotification;
187 typedef double NSTimeInterval;
188 @interface NSDate : NSObject <NSCopying, NSCoding>  - (NSTimeInterval)timeIntervalSinceReferenceDate;
189 @end            typedef unsigned short unichar;
190 @interface NSString : NSObject <NSCopying, NSMutableCopying, NSCoding>
191 - (NSUInteger)length;
192 - (NSString *)stringByAppendingString:(NSString *)aString;
193 - ( const char *)UTF8String;
194 - (id)initWithUTF8String:(const char *)nullTerminatedCString;
195 + (id)stringWithUTF8String:(const char *)nullTerminatedCString;
196 @end        @class NSString, NSURL, NSError;
197 @interface NSData : NSObject <NSCopying, NSMutableCopying, NSCoding>  - (NSUInteger)length;
198 + (id)dataWithBytesNoCopy:(void *)bytes length:(NSUInteger)length;
199 + (id)dataWithBytesNoCopy:(void *)bytes length:(NSUInteger)length freeWhenDone:(BOOL)b;
200 @end   @class NSLocale, NSDate, NSCalendar, NSTimeZone, NSError, NSArray, NSMutableDictionary;
201 @interface NSDictionary : NSObject <NSCopying, NSMutableCopying, NSCoding, NSFastEnumeration>
202 - (NSUInteger)count;
203 + (id)dictionaryWithObjects:(NSArray *)objects forKeys:(NSArray *)keys;
204 + (id)dictionaryWithObjects:(const id [])objects forKeys:(const id <NSCopying> [])keys count:(NSUInteger)cnt;
205 @end
206 @interface NSMutableDictionary : NSDictionary  - (void)removeObjectForKey:(id)aKey;
207 - (void)setObject:(id)anObject forKey:(id)aKey;
208 @end
209 @interface NSMutableDictionary (NSMutableDictionaryCreation)  + (id)dictionaryWithCapacity:(NSUInteger)numItems;
210 @end
211
212 @interface NSNull : NSObject
213 + (NSNull*) null;
214 @end
215
216 typedef double CGFloat;
217 struct CGSize {
218 };
219 typedef struct CGSize CGSize;
220 struct CGRect {
221 };
222 typedef struct CGRect CGRect;
223 typedef mach_port_t io_object_t;
224 typedef char io_name_t[128];
225 typedef io_object_t io_iterator_t;
226 typedef io_object_t io_service_t;
227 typedef struct IONotificationPort * IONotificationPortRef;
228 typedef void (*IOServiceMatchingCallback)(  void * refcon,  io_iterator_t iterator );
229 io_service_t IOServiceGetMatchingService(  mach_port_t masterPort,  CFDictionaryRef matching );
230 kern_return_t IOServiceGetMatchingServices(  mach_port_t masterPort,  CFDictionaryRef matching,  io_iterator_t * existing );
231 kern_return_t IOServiceAddNotification(  mach_port_t masterPort,  const io_name_t notificationType,  CFDictionaryRef matching,  mach_port_t wakePort,  uintptr_t reference,  io_iterator_t * notification ) __attribute__((deprecated)); // expected-note {{'IOServiceAddNotification' has been explicitly marked deprecated here}}
232 kern_return_t IOServiceAddMatchingNotification(  IONotificationPortRef notifyPort,  const io_name_t notificationType,  CFDictionaryRef matching,         IOServiceMatchingCallback callback,         void * refCon,  io_iterator_t * notification );
233 CFMutableDictionaryRef IOServiceMatching(  const char * name );
234 CFMutableDictionaryRef IOServiceNameMatching(  const char * name );
235 CFMutableDictionaryRef IOBSDNameMatching(  mach_port_t masterPort,  uint32_t options,  const char * bsdName );
236 CFMutableDictionaryRef IOOpenFirmwarePathMatching(  mach_port_t masterPort,  uint32_t options,  const char * path );
237 CFMutableDictionaryRef IORegistryEntryIDMatching(  uint64_t entryID );
238 typedef struct __DASession * DASessionRef;
239 extern DASessionRef DASessionCreate( CFAllocatorRef allocator );
240 typedef struct __DADisk * DADiskRef;
241 extern DADiskRef DADiskCreateFromBSDName( CFAllocatorRef allocator, DASessionRef session, const char * name );
242 extern DADiskRef DADiskCreateFromIOMedia( CFAllocatorRef allocator, DASessionRef session, io_service_t media );
243 extern CFDictionaryRef DADiskCopyDescription( DADiskRef disk );
244 extern DADiskRef DADiskCopyWholeDisk( DADiskRef disk );
245 @interface NSTask : NSObject - (id)init;
246 @end                    typedef struct CGColorSpace *CGColorSpaceRef;
247 typedef struct CGImage *CGImageRef;
248 typedef struct CGLayer *CGLayerRef;
249 @interface NSResponder : NSObject <NSCoding> {
250 }
251 @end    @protocol NSAnimatablePropertyContainer      - (id)animator;
252 @end  extern NSString *NSAnimationTriggerOrderIn ;
253 @interface NSView : NSResponder  <NSAnimatablePropertyContainer>  {
254 }
255 @end @protocol NSValidatedUserInterfaceItem - (SEL)action;
256 @end   @protocol NSUserInterfaceValidations - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)anItem;
257 @end  @class NSDate, NSDictionary, NSError, NSException, NSNotification;
258 @class NSTextField, NSPanel, NSArray, NSWindow, NSImage, NSButton, NSError;
259 @interface NSApplication : NSResponder <NSUserInterfaceValidations> {
260 }
261 - (void)beginSheet:(NSWindow *)sheet modalForWindow:(NSWindow *)docWindow modalDelegate:(id)modalDelegate didEndSelector:(SEL)didEndSelector contextInfo:(void *)contextInfo;
262 @end   enum {
263 NSTerminateCancel = 0,         NSTerminateNow = 1,         NSTerminateLater = 2 };
264 typedef NSUInteger NSApplicationTerminateReply;
265 @protocol NSApplicationDelegate <NSObject> @optional        - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender;
266 @end  @class NSAttributedString, NSEvent, NSFont, NSFormatter, NSImage, NSMenu, NSText, NSView, NSTextView;
267 @interface NSCell : NSObject <NSCopying, NSCoding> {
268 }
269 @end 
270 typedef struct {
271 }
272 CVTimeStamp;
273 @interface CIImage : NSObject <NSCoding, NSCopying> {
274 }
275 typedef int CIFormat;
276 @end  enum {
277 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 };
278 typedef mach_error_t DAReturn;
279 typedef const struct __DADissenter * DADissenterRef;
280 extern DADissenterRef DADissenterCreate( CFAllocatorRef allocator, DAReturn status, CFStringRef string );
281 @interface CIContext: NSObject {
282 }
283 - (CGImageRef)createCGImage:(CIImage *)im fromRect:(CGRect)r;
284 - (CGImageRef)createCGImage:(CIImage *)im fromRect:(CGRect)r     format:(CIFormat)f colorSpace:(CGColorSpaceRef)cs;
285 - (CGLayerRef)createCGLayerWithSize:(CGSize)size info:(CFDictionaryRef)d;
286 @end extern NSString* const QCRendererEventKey;
287 @protocol QCCompositionRenderer - (NSDictionary*) attributes;
288 @end   @interface QCRenderer : NSObject <QCCompositionRenderer> {
289 }
290 - (id) createSnapshotImageOfType:(NSString*)type;
291 @end  extern NSString* const QCViewDidStartRenderingNotification;
292 @interface QCView : NSView <QCCompositionRenderer> {
293 }
294 - (id) createSnapshotImageOfType:(NSString*)type;
295 @end    enum {
296 ICEXIFOrientation1 = 1,     ICEXIFOrientation2 = 2,     ICEXIFOrientation3 = 3,     ICEXIFOrientation4 = 4,     ICEXIFOrientation5 = 5,     ICEXIFOrientation6 = 6,     ICEXIFOrientation7 = 7,     ICEXIFOrientation8 = 8, };
297 @class ICDevice;
298 @protocol ICDeviceDelegate <NSObject>  @required      - (void)didRemoveDevice:(ICDevice*)device;
299 @end extern NSString *const ICScannerStatusWarmingUp;
300 @class ICScannerDevice;
301 @protocol ICScannerDeviceDelegate <ICDeviceDelegate>  @optional       - (void)scannerDeviceDidBecomeAvailable:(ICScannerDevice*)scanner;
302 @end
303
304 typedef long unsigned int __darwin_size_t;
305 typedef __darwin_size_t size_t;
306 typedef unsigned long CFTypeID;
307 struct CGPoint {
308   CGFloat x;
309   CGFloat y;
310 };
311 typedef struct CGPoint CGPoint;
312 typedef struct CGGradient *CGGradientRef;
313 typedef uint32_t CGGradientDrawingOptions;
314 extern CFTypeID CGGradientGetTypeID(void);
315 extern CGGradientRef CGGradientCreateWithColorComponents(CGColorSpaceRef
316   space, const CGFloat components[], const CGFloat locations[], size_t count);
317 extern CGGradientRef CGGradientCreateWithColors(CGColorSpaceRef space,
318   CFArrayRef colors, const CGFloat locations[]);
319 extern CGGradientRef CGGradientRetain(CGGradientRef gradient);
320 extern void CGGradientRelease(CGGradientRef gradient);
321 typedef struct CGContext *CGContextRef;
322 extern void CGContextDrawLinearGradient(CGContextRef context,
323     CGGradientRef gradient, CGPoint startPoint, CGPoint endPoint,
324     CGGradientDrawingOptions options);
325 extern CGColorSpaceRef CGColorSpaceCreateDeviceRGB(void);
326
327 @interface NSMutableArray : NSObject
328 - (void)addObject:(id)object;
329 + (id)array;
330 @end
331
332 // This is how NSMakeCollectable is declared in the OS X 10.8 headers.
333 id NSMakeCollectable(CFTypeRef __attribute__((cf_consumed))) __attribute__((ns_returns_retained));
334
335 typedef const struct __CFUUID * CFUUIDRef;
336
337 extern
338 void *CFPlugInInstanceCreate(CFAllocatorRef allocator, CFUUIDRef factoryUUID, CFUUIDRef typeUUID);
339 typedef struct {
340   int ref;
341 } isl_basic_map;
342
343 //===----------------------------------------------------------------------===//
344 // Test cases.
345 //===----------------------------------------------------------------------===//
346
347 CFAbsoluteTime f1() {
348   CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
349   CFDateRef date = CFDateCreate(0, t);
350   CFRetain(date);
351   CFRelease(date);
352   CFDateGetAbsoluteTime(date); // no-warning
353   CFRelease(date);
354   t = CFDateGetAbsoluteTime(date);   // expected-warning{{Reference-counted object is used after it is released}}
355   return t;
356 }
357
358 CFAbsoluteTime f2() {
359   CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
360   CFDateRef date = CFDateCreate(0, t);  
361   [((NSDate*) date) retain];
362   CFRelease(date);
363   CFDateGetAbsoluteTime(date); // no-warning
364   [((NSDate*) date) release];
365   t = CFDateGetAbsoluteTime(date);   // expected-warning{{Reference-counted object is used after it is released}}
366   return t;
367 }
368
369
370 NSDate* global_x;
371
372 // Test to see if we suppress an error when we store the pointer
373 // to a global.
374
375 CFAbsoluteTime f3() {
376   CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
377   CFDateRef date = CFDateCreate(0, t);  
378   [((NSDate*) date) retain];
379   CFRelease(date);
380   CFDateGetAbsoluteTime(date); // no-warning
381   global_x = (NSDate*) date;  
382   [((NSDate*) date) release];
383   t = CFDateGetAbsoluteTime(date);   // no-warning
384   return t;
385 }
386
387 //---------------------------------------------------------------------------
388 // Test case 'f4' differs for region store and basic store.  See
389 // retain-release-region-store.m and retain-release-basic-store.m.
390 //---------------------------------------------------------------------------
391
392 // Test a leak.
393
394 CFAbsoluteTime f5(int x) {  
395   CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
396   CFDateRef date = CFDateCreate(0, t); // expected-warning{{leak}}
397   
398   if (x)
399     CFRelease(date);
400   
401   return t;
402 }
403
404 // Test a leak involving the return.
405
406 CFDateRef f6(int x) {  
407   CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent());  // expected-warning{{leak}}
408   CFRetain(date);
409   return date;
410 }
411
412 // Test a leak involving an overwrite.
413
414 CFDateRef f7() {
415   CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent());  //expected-warning{{leak}}
416   CFRetain(date);
417   date = CFDateCreate(0, CFAbsoluteTimeGetCurrent()); // expected-warning {{leak}}
418   return date;
419 }
420
421 // Generalization of Create rule.  MyDateCreate returns a CFXXXTypeRef, and
422 // has the word create.
423 CFDateRef MyDateCreate();
424
425 CFDateRef f8() {
426   CFDateRef date = MyDateCreate(); // expected-warning{{leak}}
427   CFRetain(date);  
428   return date;
429 }
430
431 __attribute__((cf_returns_retained)) CFDateRef f9() {
432   CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent()); // no-warning
433   int *p = 0;
434   // When allocations fail, CFDateCreate can return null.
435   if (!date) *p = 1; // expected-warning{{null}}
436   return date;
437 }
438
439 // Handle DiskArbitration API:
440 //
441 // http://developer.apple.com/DOCUMENTATION/DARWIN/Reference/DiscArbitrationFramework/
442 //
443 void f10(io_service_t media, DADiskRef d, CFStringRef s) {
444   DADiskRef disk = DADiskCreateFromBSDName(kCFAllocatorDefault, 0, "hello"); // expected-warning{{leak}}
445   if (disk) NSLog(@"ok");
446   
447   disk = DADiskCreateFromIOMedia(kCFAllocatorDefault, 0, media); // expected-warning{{leak}}
448   if (disk) NSLog(@"ok");
449
450   CFDictionaryRef dict = DADiskCopyDescription(d);  // expected-warning{{leak}}
451   if (dict) NSLog(@"ok"); 
452   
453   disk = DADiskCopyWholeDisk(d); // expected-warning{{leak}}
454   if (disk) NSLog(@"ok");
455     
456   DADissenterRef dissenter = DADissenterCreate(kCFAllocatorDefault,   // expected-warning{{leak}}
457                                                 kDAReturnSuccess, s);
458   if (dissenter) NSLog(@"ok");
459   
460   DASessionRef session = DASessionCreate(kCFAllocatorDefault);  // expected-warning{{leak}}
461   if (session) NSLog(@"ok");
462 }
463
464
465 // Handle CoreMedia API
466
467 struct CMFoo;
468 typedef struct CMFoo *CMFooRef;
469
470 CMFooRef CMCreateFooRef();
471 CMFooRef CMGetFooRef();
472
473 typedef signed long SInt32;
474 typedef SInt32  OSStatus;
475 OSStatus CMCreateFooAndReturnViaOutParameter(CMFooRef * CF_RETURNS_RETAINED fooOut);
476
477 void testLeakCoreMediaReferenceType() {
478   CMFooRef f = CMCreateFooRef(); // expected-warning{{leak}}
479 }
480
481 void testOverReleaseMediaReferenceType() {
482   CMFooRef f = CMGetFooRef();
483   CFRelease(f); // expected-warning{{Incorrect decrement of the reference count}}
484 }
485
486 void testOkToReleaseReturnsRetainedOutParameter() {
487   CMFooRef foo = 0;
488   OSStatus status = CMCreateFooAndReturnViaOutParameter(&foo);
489
490   if (status != 0)
491     return;
492
493   CFRelease(foo); // no-warning
494 }
495
496 void testLeakWithReturnsRetainedOutParameter() {
497   CMFooRef foo = 0;
498   OSStatus status = CMCreateFooAndReturnViaOutParameter(&foo);
499
500   if (status != 0)
501     return;
502
503   // FIXME: Ideally we would report a leak here since it is the caller's
504   // responsibility to release 'foo'. However, we don't currently have
505   // a mechanism in this checker to only require a release when a successful
506   // status is returned.
507 }
508
509 typedef CFTypeRef CMBufferRef;
510
511 typedef CFTypeRef *CMBufferQueueRef;
512
513 CMBufferRef CMBufferQueueDequeueAndRetain(CMBufferQueueRef);
514
515 void testCMBufferQueueDequeueAndRetain(CMBufferQueueRef queue) {
516   CMBufferRef buffer = CMBufferQueueDequeueAndRetain(queue); // expected-warning{{Potential leak of an object stored into 'buffer'}}
517   // There's a state split due to the eagerly-assume behavior.
518   // The point here is that we don't treat CMBufferQueueDequeueAndRetain
519   // as some sort of CFRetain() that returns its argument.
520   clang_analyzer_eval((CMFooRef)buffer == (CMFooRef)queue); // expected-warning{{TRUE}}
521                                                             // expected-warning@-1{{FALSE}}
522 }
523
524 // Test retain/release checker with CFString and CFMutableArray.
525 void f11() {
526   // Create the array.
527   CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
528
529   // Create a string.
530   CFStringRef s1 = CFStringCreateWithCString(0, "hello world",
531                                              kCFStringEncodingUTF8);
532
533   // Add the string to the array.
534   CFArrayAppendValue(A, s1);
535   
536   // Decrement the reference count.
537   CFRelease(s1); // no-warning
538   
539   // Get the string.  We don't own it.
540   s1 = (CFStringRef) CFArrayGetValueAtIndex(A, 0);
541   
542   // Release the array.
543   CFRelease(A); // no-warning
544   
545   // Release the string.  This is a bug.
546   CFRelease(s1); // expected-warning{{Incorrect decrement of the reference count}}
547 }
548
549 // PR 3337: Handle functions declared using typedefs.
550 typedef CFTypeRef CREATEFUN();
551 CREATEFUN MyCreateFun;
552
553 void f12() {
554   CFTypeRef o = MyCreateFun(); // expected-warning {{leak}}
555 }
556
557 void f13_autorelease() {
558   CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
559   [(id) A autorelease]; // no-warning
560 }
561
562 void f13_autorelease_b() {
563   CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
564   [(id) A autorelease];
565   [(id) A autorelease];
566 } // expected-warning{{Object autoreleased too many times}}
567
568 CFMutableArrayRef f13_autorelease_c() {
569   CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
570   [(id) A autorelease];
571   [(id) A autorelease]; 
572   return A; // expected-warning{{Object autoreleased too many times}}
573 }
574
575 CFMutableArrayRef f13_autorelease_d() {
576   CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
577   [(id) A autorelease];
578   [(id) A autorelease]; 
579   CFMutableArrayRef B = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning{{Object autoreleased too many times}}
580   CFRelease(B); // no-warning
581   while (1) {}
582 }
583
584
585 // This case exercises the logic where the leak site is the same as the allocation site.
586 void f14_leakimmediately() {
587   CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning{{leak}}
588 }
589
590 // Test that we track an allocated object beyond the point where the *name*
591 // of the variable storing the reference is no longer live.
592 void f15() {
593   // Create the array.
594   CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
595   CFMutableArrayRef *B = &A;
596   // At this point, the name 'A' is no longer live.
597   CFRelease(*B);  // no-warning
598 }
599
600 // Test when we pass NULL to CFRetain/CFRelease/CFMakeCollectable/CFAutorelease.
601 void f16(int x, CFTypeRef p) {
602   if (p)
603     return;
604
605   switch (x) {
606   case 0:
607     CFRelease(p); // expected-warning{{Null pointer argument in call to CFRelease}}
608     break;
609   case 1:
610     CFRetain(p); // expected-warning{{Null pointer argument in call to CFRetain}}
611     break;
612   case 2:
613     CFMakeCollectable(p); // expected-warning{{Null pointer argument in call to CFMakeCollectable}}
614     break;
615   case 3:
616     CFAutorelease(p); // expected-warning{{Null pointer argument in call to CFAutorelease}}
617     break;
618   default:
619     break;
620   }
621 }
622
623 // Test that an object is non-null after CFRetain/CFRelease/CFMakeCollectable/CFAutorelease.
624 void f17(int x, CFTypeRef p) {
625   switch (x) {
626   case 0:
627     CFRelease(p);
628     if (!p)
629       CFRelease(0); // no-warning
630     break;
631   case 1:
632     CFRetain(p);
633     if (!p)
634       CFRetain(0); // no-warning
635     break;
636   case 2:
637     CFMakeCollectable(p);
638     if (!p)
639       CFMakeCollectable(0); // no-warning
640     break;
641   case 3:
642     CFAutorelease(p);
643     if (!p)
644       CFAutorelease(0); // no-warning
645     break;
646   default:
647     break;
648   }
649 }
650
651 __attribute__((annotate("rc_ownership_returns_retained"))) isl_basic_map *isl_basic_map_cow(__attribute__((annotate("rc_ownership_consumed"))) isl_basic_map *bmap);
652
653 // Test custom diagnostics for generalized objects.
654 void f18(__attribute__((annotate("rc_ownership_consumed"))) isl_basic_map *bmap) {
655   // After this call, 'bmap' has a +1 reference count.
656   bmap = isl_basic_map_cow(bmap); // expected-warning {{Potential leak of an object}}
657 }
658
659 // Test basic tracking of ivars associated with 'self'.  For the retain/release
660 // checker we currently do not want to flag leaks associated with stores
661 // of tracked objects to ivars.
662 @interface SelfIvarTest : NSObject {
663   id myObj;
664 }
665 - (void)test_self_tracking;
666 @end
667
668 @implementation SelfIvarTest
669 - (void)test_self_tracking {
670   myObj = (id) CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
671 }
672 @end
673
674 // Test return of non-owned objects in contexts where an owned object
675 // is expected.
676 @interface TestReturnNotOwnedWhenExpectedOwned
677 - (NSString*)newString;
678 @end
679
680 @implementation TestReturnNotOwnedWhenExpectedOwned
681 - (NSString*)newString {
682   NSString *s = [NSString stringWithUTF8String:"hello"];
683   return s; // expected-warning{{Object with a +0 retain count returned to caller where a +1 (owning) retain count is expected}}
684 }
685 @end
686
687 // <rdar://problem/6659160>
688 int isFoo(char c);
689
690 static void rdar_6659160(char *inkind, char *inname)
691 {
692   // We currently expect that [NSObject alloc] cannot fail.  This
693   // will be a toggled flag in the future.  It can indeed return null, but
694   // Cocoa programmers generally aren't expected to reason about out-of-memory
695   // conditions.
696   NSString *kind = [[NSString alloc] initWithUTF8String:inkind];  // expected-warning{{leak}}
697   
698   // We do allow stringWithUTF8String to fail.  This isn't really correct, as
699   // far as returning 0.  In most error conditions it will throw an exception.
700   // If allocation fails it could return 0, but again this
701   // isn't expected.
702   NSString *name = [NSString stringWithUTF8String:inname];
703   if(!name)
704     return;
705
706   const char *kindC = 0;
707   const char *nameC = 0;
708   
709   // In both cases, we cannot reach a point down below where we
710   // dereference kindC or nameC with either being null.  This is because
711   // we assume that [NSObject alloc] doesn't fail and that we have the guard
712   // up above.
713   
714   if(kind)
715     kindC = [kind UTF8String];
716   if(name)
717     nameC = [name UTF8String];
718   if(!isFoo(kindC[0])) // expected-warning{{null}}
719     return;
720   if(!isFoo(nameC[0])) // no-warning
721     return;
722
723   [kind release];
724   [name release]; // expected-warning{{Incorrect decrement of the reference count}}
725 }
726
727 // PR 3677 - 'allocWithZone' should be treated as following the Cocoa naming
728 //  conventions with respect to 'return'ing ownership.
729 @interface PR3677: NSObject @end
730 @implementation PR3677
731 + (id)allocWithZone:(NSZone *)inZone {
732   return [super allocWithZone:inZone];  // no-warning
733 }
734 @end
735
736 // PR 3820 - Reason about calls to -dealloc
737 void pr3820_DeallocInsteadOfRelease(void)
738 {
739   id foo = [[NSString alloc] init]; // no-warning
740   [foo dealloc];
741   // foo is not leaked, since it has been deallocated.
742 }
743
744 void pr3820_ReleaseAfterDealloc(void)
745 {
746   id foo = [[NSString alloc] init];
747   [foo dealloc];
748   [foo release];  // expected-warning{{used after it is release}}
749   // NSInternalInconsistencyException: message sent to deallocated object
750 }
751
752 void pr3820_DeallocAfterRelease(void)
753 {
754   NSLog(@"\n\n[%s]", __FUNCTION__);
755   id foo = [[NSString alloc] init];
756   [foo release];
757   [foo dealloc]; // expected-warning{{used after it is released}}
758   // message sent to released object
759 }
760
761 // From <rdar://problem/6704930>.  The problem here is that 'length' binds to
762 // '($0 - 1)' after '--length', but SimpleConstraintManager doesn't know how to
763 // reason about '($0 - 1) > constant'.  As a temporary hack, we drop the value
764 // of '($0 - 1)' and conjure a new symbol.
765 void rdar6704930(unsigned char *s, unsigned int length) {
766   NSString* name = 0;
767   if (s != 0) {
768     if (length > 0) {
769       while (length > 0) {
770         if (*s == ':') {
771           ++s;
772           --length;
773           name = [[NSString alloc] init]; // no-warning
774           break;
775         }
776         ++s;
777         --length;
778       }
779       if ((length == 0) && (name != 0)) {
780         [name release];
781         name = 0;
782       }
783       if (length == 0) { // no ':' found -> use it all as name
784         name = [[NSString alloc] init]; // no-warning
785       }
786     }
787   }
788
789   if (name != 0) {
790     [name release];
791   }
792 }
793
794 //===----------------------------------------------------------------------===//
795 // <rdar://problem/6833332>
796 // One build of the analyzer accidentally stopped tracking the allocated
797 // object after the 'retain'.
798 //===----------------------------------------------------------------------===//
799
800 @interface rdar_6833332 : NSObject <NSApplicationDelegate> {
801     NSWindow *window;
802 }
803 @property (nonatomic, retain) NSWindow *window;
804 @end
805
806 @implementation rdar_6833332
807 @synthesize window;
808 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
809  NSMutableDictionary *dict = [[NSMutableDictionary dictionaryWithCapacity:4] retain]; // expected-warning{{leak}}
810
811  [dict setObject:@"foo" forKey:@"bar"];
812
813  NSLog(@"%@", dict);
814 }
815 - (void)dealloc {
816     [window release];
817     [super dealloc];
818 }
819
820 - (void)radar10102244 {
821  NSMutableDictionary *dict = [[NSMutableDictionary dictionaryWithCapacity:4] retain]; // expected-warning{{leak}} 
822  if (window) 
823    NSLog(@"%@", window);    
824 }
825 @end
826
827 //===----------------------------------------------------------------------===//
828 // <rdar://problem/6257780> clang checker fails to catch use-after-release
829 //===----------------------------------------------------------------------===//
830
831 int rdar_6257780_Case1() {
832   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
833   NSArray *array = [NSArray array];
834   [array release]; // expected-warning{{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
835   [pool drain];
836   return 0;
837 }
838
839 //===----------------------------------------------------------------------===//
840 // <rdar://problem/10640253> Analyzer is confused about NSAutoreleasePool -allocWithZone:.
841 //===----------------------------------------------------------------------===//
842
843 void rdar_10640253_autorelease_allocWithZone() {
844     NSAutoreleasePool *pool = [[NSAutoreleasePool allocWithZone:(NSZone*)0] init];
845     (void) pool;
846 }
847
848 //===----------------------------------------------------------------------===//
849 // <rdar://problem/6866843> Checker should understand new/setObject:/release constructs
850 //===----------------------------------------------------------------------===//
851
852 void rdar_6866843() {
853  NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
854  NSMutableDictionary* dictionary = [[NSMutableDictionary alloc] init];
855  NSArray* array = [[NSArray alloc] init];
856  [dictionary setObject:array forKey:@"key"];
857  [array release];
858  // Using 'array' here should be fine
859  NSLog(@"array = %@\n", array); // no-warning
860  // Now the array is released
861  [dictionary release];
862  [pool drain];
863 }
864
865
866 //===----------------------------------------------------------------------===//
867 // <rdar://problem/6877235> Classes typedef-ed to CF objects should get the same treatment as CF objects
868 //===----------------------------------------------------------------------===//
869
870 typedef CFTypeRef OtherRef;
871
872 @interface RDar6877235 : NSObject {}
873 - (CFTypeRef)_copyCFTypeRef;
874 - (OtherRef)_copyOtherRef;
875 @end
876
877 @implementation RDar6877235
878 - (CFTypeRef)_copyCFTypeRef {
879   return [[NSString alloc] init]; // no-warning
880 }
881 - (OtherRef)_copyOtherRef {
882   return [[NSString alloc] init]; // no-warning
883 }
884 @end
885
886 //===----------------------------------------------------------------------===//
887 // <rdar://problem/6320065> false positive - init method returns an object
888 // owned by caller
889 //===----------------------------------------------------------------------===//
890
891 @interface RDar6320065 : NSObject {
892   NSString *_foo;
893 }
894 - (id)initReturningNewClass;
895 - (id)_initReturningNewClassBad;
896 - (id)initReturningNewClassBad2;
897 @end
898
899 @interface RDar6320065Subclass : RDar6320065
900 @end
901
902 @implementation RDar6320065
903 - (id)initReturningNewClass {
904   [self release];
905   self = [[RDar6320065Subclass alloc] init]; // no-warning
906   return self;
907 }
908 - (id)_initReturningNewClassBad {
909   [self release];
910   [[RDar6320065Subclass alloc] init]; // expected-warning {{leak}}
911   return self;
912 }
913 - (id)initReturningNewClassBad2 {
914   [self release];
915   self = [[RDar6320065Subclass alloc] init];
916   return [self autorelease]; // expected-warning{{Object with a +0 retain count returned to caller where a +1 (owning) retain count is expected}}
917 }
918
919 @end
920
921 @implementation RDar6320065Subclass
922 @end
923
924 int RDar6320065_test() {
925   RDar6320065 *test = [[RDar6320065 alloc] init]; // no-warning
926   [test release];
927   return 0;
928 }
929
930 //===----------------------------------------------------------------------===//
931 // <rdar://problem/7129086> -awakeAfterUsingCoder: returns an owned object 
932 //  and claims the receiver
933 //===----------------------------------------------------------------------===//
934
935 @interface RDar7129086 : NSObject {} @end
936 @implementation RDar7129086
937 - (id)awakeAfterUsingCoder:(NSCoder *)aDecoder {
938   [self release]; // no-warning
939   return [NSString alloc];  // no-warning
940 }
941 @end
942
943 //===----------------------------------------------------------------------===//
944 // <rdar://problem/6859457> [NSData dataWithBytesNoCopy] does not return a
945 //  retained object
946 //===----------------------------------------------------------------------===//
947
948 @interface RDar6859457 : NSObject {}
949 - (NSString*) NoCopyString;
950 - (NSString*) noCopyString;
951 @end
952
953 @implementation RDar6859457 
954 - (NSString*) NoCopyString { return [[NSString alloc] init]; } // expected-warning{{leak}}
955 - (NSString*) noCopyString { return [[NSString alloc] init]; } // expected-warning{{leak}}
956 @end
957
958 void test_RDar6859457(RDar6859457 *x, void *bytes, NSUInteger dataLength) {
959   [x NoCopyString]; // expected-warning{{leak}}
960   [x noCopyString]; // expected-warning{{leak}}
961   [NSData dataWithBytesNoCopy:bytes length:dataLength];  // no-warning
962   [NSData dataWithBytesNoCopy:bytes length:dataLength freeWhenDone:1]; // no-warning
963 }
964
965 //===----------------------------------------------------------------------===//
966 // PR 4230 - an autorelease pool is not necessarily leaked during a premature
967 //  return
968 //===----------------------------------------------------------------------===//
969
970 static void PR4230(void)
971 {
972   NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // no-warning
973   NSString *object = [[[NSString alloc] init] autorelease]; // no-warning
974   return;
975 }
976
977 static void PR4230_new(void)
978 {
979   NSAutoreleasePool *pool = [NSAutoreleasePool new]; // no-warning
980   NSString *object = [[[NSString alloc] init] autorelease]; // no-warning
981   return;
982 }
983
984 //===----------------------------------------------------------------------===//
985 // Method name that has a null IdentifierInfo* for its first selector slot.
986 // This test just makes sure that we handle it.
987 //===----------------------------------------------------------------------===//
988
989 @interface TestNullIdentifier
990 @end
991
992 @implementation TestNullIdentifier
993 + (id):(int)x, ... {
994   return [[NSString alloc] init]; // expected-warning{{leak}}
995 }
996 @end
997
998 //===----------------------------------------------------------------------===//
999 // <rdar://problem/6893565> don't flag leaks for return types that cannot be 
1000 //                          determined to be CF types
1001 //===----------------------------------------------------------------------===//
1002
1003 // We don't know if 'struct s6893565' represents a Core Foundation type, so
1004 // we shouldn't emit an error here.
1005 typedef struct s6893565* TD6893565;
1006
1007 @interface RDar6893565 {}
1008 -(TD6893565)newThing;
1009 @end
1010
1011 @implementation RDar6893565
1012 -(TD6893565)newThing {  
1013   return (TD6893565) [[NSString alloc] init]; // no-warning
1014 }
1015 @end
1016
1017 //===----------------------------------------------------------------------===//
1018 // <rdar://problem/6902710> clang: false positives w/QC and CoreImage methods
1019 //===----------------------------------------------------------------------===//
1020
1021 void rdar6902710(QCView *view, QCRenderer *renderer, CIContext *context,
1022                  NSString *str, CIImage *img, CGRect rect,
1023                  CIFormat form, CGColorSpaceRef cs) {
1024   [view createSnapshotImageOfType:str]; // expected-warning{{leak}}
1025   [renderer createSnapshotImageOfType:str]; // expected-warning{{leak}}
1026   [context createCGImage:img fromRect:rect]; // expected-warning{{leak}}
1027   [context createCGImage:img fromRect:rect format:form colorSpace:cs]; // expected-warning{{leak}}
1028 }
1029
1030 //===----------------------------------------------------------------------===//
1031 // <rdar://problem/6945561> -[CIContext createCGLayerWithSize:info:]
1032 //                           misinterpreted by clang scan-build
1033 //===----------------------------------------------------------------------===//
1034
1035 void rdar6945561(CIContext *context, CGSize size, CFDictionaryRef d) {
1036   [context createCGLayerWithSize:size info:d]; // expected-warning{{leak}}
1037 }
1038
1039 //===----------------------------------------------------------------------===//
1040 // <rdar://problem/6961230> add knowledge of IOKit functions to retain/release 
1041 //                          checker
1042 //===----------------------------------------------------------------------===//
1043
1044 void IOBSDNameMatching_wrapper(mach_port_t masterPort, uint32_t options,  const char * bsdName) {  
1045   IOBSDNameMatching(masterPort, options, bsdName); // expected-warning{{leak}}
1046 }
1047
1048 void IOServiceMatching_wrapper(const char * name) {
1049   IOServiceMatching(name); // expected-warning{{leak}}
1050 }
1051
1052 void IOServiceNameMatching_wrapper(const char * name) {
1053   IOServiceNameMatching(name); // expected-warning{{leak}}
1054 }
1055
1056 CF_RETURNS_RETAINED CFDictionaryRef CreateDict();
1057
1058 void IOServiceAddNotification_wrapper(mach_port_t masterPort, const io_name_t notificationType,
1059   mach_port_t wakePort, uintptr_t reference, io_iterator_t * notification ) {
1060
1061   CFDictionaryRef matching = CreateDict();
1062   CFRelease(matching);
1063   IOServiceAddNotification(masterPort, notificationType, matching, // expected-warning{{used after it is released}} expected-warning{{deprecated}}
1064                            wakePort, reference, notification);
1065 }
1066
1067 void IORegistryEntryIDMatching_wrapper(uint64_t entryID ) {
1068   IORegistryEntryIDMatching(entryID); // expected-warning{{leak}}
1069 }
1070
1071 void IOOpenFirmwarePathMatching_wrapper(mach_port_t masterPort, uint32_t options,
1072                                         const char * path) {
1073   IOOpenFirmwarePathMatching(masterPort, options, path); // expected-warning{{leak}}
1074 }
1075
1076 void IOServiceGetMatchingService_wrapper(mach_port_t masterPort) {
1077   CFDictionaryRef matching = CreateDict();
1078   IOServiceGetMatchingService(masterPort, matching);
1079   CFRelease(matching); // expected-warning{{used after it is released}}
1080 }
1081
1082 void IOServiceGetMatchingServices_wrapper(mach_port_t masterPort, io_iterator_t *existing) {
1083   CFDictionaryRef matching = CreateDict();
1084   IOServiceGetMatchingServices(masterPort, matching, existing);
1085   CFRelease(matching); // expected-warning{{used after it is released}}
1086 }
1087
1088 void IOServiceAddMatchingNotification_wrapper(IONotificationPortRef notifyPort, const io_name_t notificationType, 
1089   IOServiceMatchingCallback callback, void * refCon, io_iterator_t * notification) {
1090     
1091   CFDictionaryRef matching = CreateDict();
1092   IOServiceAddMatchingNotification(notifyPort, notificationType, matching, callback, refCon, notification);
1093   CFRelease(matching); // expected-warning{{used after it is released}}
1094 }
1095
1096 //===----------------------------------------------------------------------===//
1097 // Test of handling objects whose references "escape" to containers.
1098 //===----------------------------------------------------------------------===//
1099
1100 void CFDictionaryAddValue(CFMutableDictionaryRef, void *, void *);
1101
1102 // <rdar://problem/6539791>
1103 void rdar_6539791(CFMutableDictionaryRef y, void* key, void* val_key) {
1104   CFMutableDictionaryRef x = CFDictionaryCreateMutable(kCFAllocatorDefault, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
1105   CFDictionaryAddValue(y, key, x);
1106   CFRelease(x); // the dictionary keeps a reference, so the object isn't deallocated yet
1107   signed z = 1;
1108   CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z);
1109   if (value) {
1110     CFDictionaryAddValue(x, val_key, (void*)value); // no-warning
1111     CFRelease(value);
1112     CFDictionaryAddValue(y, val_key, (void*)value); // no-warning
1113   }
1114 }
1115
1116 // <rdar://problem/6560661>
1117 // Same issue, except with "AppendValue" functions.
1118 void rdar_6560661(CFMutableArrayRef x) {
1119   signed z = 1;
1120   CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z);
1121   // CFArrayAppendValue keeps a reference to value.
1122   CFArrayAppendValue(x, value);
1123   CFRelease(value);
1124   CFRetain(value);
1125   CFRelease(value); // no-warning
1126 }
1127
1128 // <rdar://problem/7152619>
1129 // Same issue, excwept with "CFAttributeStringSetAttribute".
1130 void rdar_7152619(CFStringRef str) {
1131   CFAttributedStringRef string = CFAttributedStringCreate(kCFAllocatorDefault, str, 0);
1132   CFMutableAttributedStringRef attrString = CFAttributedStringCreateMutableCopy(kCFAllocatorDefault, 100, string);
1133   CFRelease(string);
1134   NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1135   CFAttributedStringSetAttribute(attrString, CFRangeMake(0, 1), str, number);
1136   [number release];
1137   [number retain];
1138   CFRelease(attrString);  
1139 }
1140
1141 //===----------------------------------------------------------------------===//
1142 // Test of handling CGGradientXXX functions.
1143 //===----------------------------------------------------------------------===//
1144
1145 void rdar_7184450(CGContextRef myContext, CGFloat x, CGPoint myStartPoint,
1146                   CGPoint myEndPoint) {
1147   size_t num_locations = 6;
1148   CGFloat locations[6] = { 0.0, 0.265, 0.28, 0.31, 0.36, 1.0 };
1149   CGFloat components[28] = { 239.0/256.0, 167.0/256.0, 170.0/256.0,
1150      x,  // Start color
1151     207.0/255.0, 39.0/255.0, 39.0/255.0, x,
1152     147.0/255.0, 21.0/255.0, 22.0/255.0, x,
1153     175.0/255.0, 175.0/255.0, 175.0/255.0, x,
1154     255.0/255.0,255.0/255.0, 255.0/255.0, x,
1155     255.0/255.0,255.0/255.0, 255.0/255.0, x
1156   }; // End color
1157   
1158   CGGradientRef myGradient =
1159     CGGradientCreateWithColorComponents(CGColorSpaceCreateDeviceRGB(), // expected-warning{{leak}}
1160       components, locations, num_locations);
1161
1162   CGContextDrawLinearGradient(myContext, myGradient, myStartPoint, myEndPoint,
1163                               0);
1164   CGGradientRelease(myGradient);
1165 }
1166
1167 void rdar_7184450_pos(CGContextRef myContext, CGFloat x, CGPoint myStartPoint,
1168                   CGPoint myEndPoint) {
1169   size_t num_locations = 6;
1170   CGFloat locations[6] = { 0.0, 0.265, 0.28, 0.31, 0.36, 1.0 };
1171   CGFloat components[28] = { 239.0/256.0, 167.0/256.0, 170.0/256.0,
1172      x,  // Start color
1173     207.0/255.0, 39.0/255.0, 39.0/255.0, x,
1174     147.0/255.0, 21.0/255.0, 22.0/255.0, x,
1175     175.0/255.0, 175.0/255.0, 175.0/255.0, x,
1176     255.0/255.0,255.0/255.0, 255.0/255.0, x,
1177     255.0/255.0,255.0/255.0, 255.0/255.0, x
1178   }; // End color
1179   
1180   CGGradientRef myGradient =
1181    CGGradientCreateWithColorComponents(CGColorSpaceCreateDeviceRGB(), components, locations, num_locations); // expected-warning 2 {{leak}}
1182
1183   CGContextDrawLinearGradient(myContext, myGradient, myStartPoint, myEndPoint,
1184                               0);
1185 }
1186
1187 //===----------------------------------------------------------------------===//
1188 // <rdar://problem/7299394> clang false positive: retained instance passed to
1189 //                          thread in pthread_create marked as leak
1190 //
1191 // Until we have full IPA, the analyzer should stop tracking the reference
1192 // count of objects passed to pthread_create.
1193 //
1194 //===----------------------------------------------------------------------===//
1195
1196 struct _opaque_pthread_t {};
1197 struct _opaque_pthread_attr_t {};
1198 typedef struct _opaque_pthread_t *__darwin_pthread_t;
1199 typedef struct _opaque_pthread_attr_t __darwin_pthread_attr_t;
1200 typedef __darwin_pthread_t pthread_t;
1201 typedef __darwin_pthread_attr_t pthread_attr_t;
1202 typedef unsigned long __darwin_pthread_key_t;
1203 typedef __darwin_pthread_key_t pthread_key_t;
1204
1205 int pthread_create(pthread_t *, const pthread_attr_t *,
1206                    void *(*)(void *), void *);
1207
1208 int pthread_setspecific(pthread_key_t key, const void *value);
1209
1210 void *rdar_7299394_start_routine(void *p) {
1211   [((id) p) release];
1212   return 0;
1213 }
1214 void rdar_7299394(pthread_attr_t *attr, pthread_t *thread, void *args) {
1215   NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1216   pthread_create(thread, attr, rdar_7299394_start_routine, number);
1217 }
1218 void rdar_7299394_positive(pthread_attr_t *attr, pthread_t *thread) {
1219   NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1220 }
1221
1222 //===----------------------------------------------------------------------===//
1223 // <rdar://problem/11282706> false positive with not understanding thread
1224 // local storage
1225 //===----------------------------------------------------------------------===//
1226
1227 void rdar11282706(pthread_key_t key) {
1228   NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1229   pthread_setspecific(key, (void*) number);
1230 }
1231
1232 //===----------------------------------------------------------------------===//
1233 // <rdar://problem/7283567> False leak associated with call to 
1234 //                          CVPixelBufferCreateWithBytes ()
1235 //
1236 // According to the Core Video Reference (ADC), CVPixelBufferCreateWithBytes and
1237 // CVPixelBufferCreateWithPlanarBytes can release (via a callback) the
1238 // pixel buffer object.  These test cases show how the analyzer stops tracking
1239 // the reference count for the objects passed for this argument.  This
1240 // could be made smarter.
1241 //===----------------------------------------------------------------------===//
1242
1243 typedef int int32_t;
1244 typedef UInt32 FourCharCode;
1245 typedef FourCharCode OSType;
1246 typedef uint64_t CVOptionFlags;
1247 typedef int32_t CVReturn;
1248 typedef struct __CVBuffer *CVBufferRef;
1249 typedef CVBufferRef CVImageBufferRef;
1250 typedef CVImageBufferRef CVPixelBufferRef;
1251 typedef void (*CVPixelBufferReleaseBytesCallback)( void *releaseRefCon, const void *baseAddress );
1252
1253 extern CVReturn CVPixelBufferCreateWithBytes(CFAllocatorRef allocator,
1254             size_t width,
1255             size_t height,
1256             OSType pixelFormatType,
1257             void *baseAddress,
1258             size_t bytesPerRow,
1259             CVPixelBufferReleaseBytesCallback releaseCallback,
1260             void *releaseRefCon,
1261             CFDictionaryRef pixelBufferAttributes,
1262                    CVPixelBufferRef *pixelBufferOut) ;
1263
1264 typedef void (*CVPixelBufferReleasePlanarBytesCallback)( void *releaseRefCon, const void *dataPtr, size_t dataSize, size_t numberOfPlanes, const void *planeAddresses[] );
1265
1266 extern CVReturn CVPixelBufferCreateWithPlanarBytes(CFAllocatorRef allocator,
1267         size_t width,
1268         size_t height,
1269         OSType pixelFormatType,
1270         void *dataPtr,
1271         size_t dataSize,
1272         size_t numberOfPlanes,
1273         void *planeBaseAddress[],
1274         size_t planeWidth[],
1275         size_t planeHeight[],
1276         size_t planeBytesPerRow[],
1277         CVPixelBufferReleasePlanarBytesCallback releaseCallback,
1278         void *releaseRefCon,
1279         CFDictionaryRef pixelBufferAttributes,
1280         CVPixelBufferRef *pixelBufferOut) ;
1281
1282 extern CVReturn CVPixelBufferCreateWithBytes(CFAllocatorRef allocator,
1283             size_t width,
1284             size_t height,
1285             OSType pixelFormatType,
1286             void *baseAddress,
1287             size_t bytesPerRow,
1288             CVPixelBufferReleaseBytesCallback releaseCallback,
1289             void *releaseRefCon,
1290             CFDictionaryRef pixelBufferAttributes,
1291                    CVPixelBufferRef *pixelBufferOut) ;
1292
1293 CVReturn rdar_7283567(CFAllocatorRef allocator, size_t width, size_t height,
1294                       OSType pixelFormatType, void *baseAddress,
1295                       size_t bytesPerRow,
1296                       CVPixelBufferReleaseBytesCallback releaseCallback,
1297                       CFDictionaryRef pixelBufferAttributes,
1298                       CVPixelBufferRef *pixelBufferOut) {
1299
1300   // For the allocated object, it doesn't really matter what type it is
1301   // for the purpose of this test.  All we want to show is that
1302   // this is freed later by the callback.
1303   NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1304   
1305   return CVPixelBufferCreateWithBytes(allocator, width, height, pixelFormatType,
1306                                 baseAddress, bytesPerRow, releaseCallback,
1307                                 number, // potentially released by callback
1308                                 pixelBufferAttributes, pixelBufferOut) ;
1309 }
1310
1311 CVReturn rdar_7283567_2(CFAllocatorRef allocator, size_t width, size_t height,
1312         OSType pixelFormatType, void *dataPtr, size_t dataSize,
1313         size_t numberOfPlanes, void *planeBaseAddress[],
1314         size_t planeWidth[], size_t planeHeight[], size_t planeBytesPerRow[],
1315         CVPixelBufferReleasePlanarBytesCallback releaseCallback,
1316         CFDictionaryRef pixelBufferAttributes,
1317         CVPixelBufferRef *pixelBufferOut) {
1318     
1319     // For the allocated object, it doesn't really matter what type it is
1320     // for the purpose of this test.  All we want to show is that
1321     // this is freed later by the callback.
1322     NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1323
1324     return CVPixelBufferCreateWithPlanarBytes(allocator,
1325               width, height, pixelFormatType, dataPtr, dataSize,
1326               numberOfPlanes, planeBaseAddress, planeWidth,
1327               planeHeight, planeBytesPerRow, releaseCallback,
1328               number, // potentially released by callback
1329               pixelBufferAttributes, pixelBufferOut) ;
1330 }
1331
1332 #pragma clang arc_cf_code_audited begin
1333 typedef struct SomeOpaqueStruct *CMSampleBufferRef;
1334 CVImageBufferRef _Nonnull CMSampleBufferGetImageBuffer(CMSampleBufferRef _Nonnull sbuf);
1335 #pragma clang arc_cf_code_audited end
1336
1337 CVBufferRef _Nullable CVBufferRetain(CVBufferRef _Nullable buffer);
1338 void CVBufferRelease(CF_CONSUMED CVBufferRef _Nullable buffer);
1339
1340 void testCVPrefixRetain(CMSampleBufferRef sbuf) {
1341   // Make sure RetainCountChecker treats CVFooRetain() as a CF-style retain.
1342   CVPixelBufferRef pixelBuf = CMSampleBufferGetImageBuffer(sbuf);
1343   CVBufferRetain(pixelBuf);
1344   CVBufferRelease(pixelBuf); // no-warning
1345
1346
1347   // Make sure result of CVFooRetain() is the same as its argument.
1348   CVPixelBufferRef pixelBufAlias = CVBufferRetain(pixelBuf);
1349   CVBufferRelease(pixelBufAlias); // no-warning
1350 }
1351
1352 typedef signed long SInt32;
1353 typedef SInt32  OSStatus;
1354 typedef FourCharCode CMVideoCodecType;
1355
1356
1357 typedef UInt32 VTEncodeInfoFlags; enum {
1358  kVTEncodeInfo_Asynchronous = 1UL << 0,
1359  kVTEncodeInfo_FrameDropped = 1UL << 1,
1360 };
1361 typedef struct
1362 {
1363   int ignore;
1364 } CMTime;
1365
1366
1367 typedef void (*VTCompressionOutputCallback)(
1368     void * _Nullable outputCallbackRefCon,
1369     void * _Nullable sourceFrameRefCon,
1370     OSStatus status,
1371     VTEncodeInfoFlags infoFlags,
1372     _Nullable CMSampleBufferRef sampleBuffer );
1373
1374 typedef struct OpaqueVTCompressionSession*  VTCompressionSessionRef;
1375
1376 extern OSStatus
1377 VTCompressionSessionCreate(_Nullable CFAllocatorRef allocator,
1378     int32_t width,
1379     int32_t height,
1380     CMVideoCodecType codecType,
1381     _Nullable CFDictionaryRef encoderSpecification,
1382     _Nullable CFDictionaryRef sourceImageBufferAttributes,
1383     _Nullable CFAllocatorRef compressedDataAllocator,
1384     _Nullable VTCompressionOutputCallback outputCallback,
1385     void * _Nullable outputCallbackRefCon,
1386     CF_RETURNS_RETAINED _Nullable VTCompressionSessionRef * _Nonnull compressionSessionOut);
1387
1388 extern OSStatus
1389 VTCompressionSessionEncodeFrame(
1390     _Nonnull VTCompressionSessionRef session,
1391     _Nonnull CVImageBufferRef imageBuffer,
1392     CMTime presentationTimeStamp,
1393     CMTime duration,
1394     _Nullable CFDictionaryRef frameProperties,
1395     void * _Nullable sourceFrameRefCon,
1396     VTEncodeInfoFlags * _Nullable infoFlagsOut);
1397
1398 OSStatus test_VTCompressionSessionCreateAndEncode_CallbackReleases(
1399     _Nullable CFAllocatorRef allocator,
1400     int32_t width,
1401     int32_t height,
1402     CMVideoCodecType codecType,
1403     _Nullable CFDictionaryRef encoderSpecification,
1404     _Nullable CFDictionaryRef sourceImageBufferAttributes,
1405     _Nullable CFAllocatorRef compressedDataAllocator,
1406     _Nullable VTCompressionOutputCallback outputCallback,
1407
1408     _Nonnull CVImageBufferRef imageBuffer,
1409     CMTime presentationTimeStamp,
1410     CMTime duration,
1411     _Nullable CFDictionaryRef frameProperties
1412 ) {
1413
1414   // The outputCallback is passed both contexts and so can release either.
1415   NSNumber *contextForCreate = [[NSNumber alloc] initWithInt:5]; // no-warning
1416   NSNumber *contextForEncode = [[NSNumber alloc] initWithInt:6]; // no-warning
1417
1418   VTCompressionSessionRef session = 0;
1419   OSStatus status = VTCompressionSessionCreate(allocator,
1420       width, height, codecType, encoderSpecification,
1421       sourceImageBufferAttributes,
1422       compressedDataAllocator, outputCallback, contextForCreate,
1423       &session);
1424
1425   VTEncodeInfoFlags encodeInfoFlags;
1426
1427   status = VTCompressionSessionEncodeFrame(session, imageBuffer,
1428       presentationTimeStamp, duration, frameProperties, contextForEncode,
1429       &encodeInfoFlags);
1430
1431   return status;
1432 }
1433
1434 //===----------------------------------------------------------------------===//
1435 // <rdar://problem/7358899> False leak associated with 
1436 //  CGBitmapContextCreateWithData
1437 //===----------------------------------------------------------------------===//
1438 typedef uint32_t CGBitmapInfo;
1439 typedef void (*CGBitmapContextReleaseDataCallback)(void *releaseInfo, void *data);
1440     
1441 CGContextRef CGBitmapContextCreateWithData(void *data,
1442     size_t width, size_t height, size_t bitsPerComponent,
1443     size_t bytesPerRow, CGColorSpaceRef space, CGBitmapInfo bitmapInfo,
1444     CGBitmapContextReleaseDataCallback releaseCallback, void *releaseInfo);
1445
1446 void rdar_7358899(void *data,
1447       size_t width, size_t height, size_t bitsPerComponent,
1448       size_t bytesPerRow, CGColorSpaceRef space, CGBitmapInfo bitmapInfo,
1449       CGBitmapContextReleaseDataCallback releaseCallback) {
1450
1451     // For the allocated object, it doesn't really matter what type it is
1452     // for the purpose of this test.  All we want to show is that
1453     // this is freed later by the callback.
1454     NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1455
1456   CGBitmapContextCreateWithData(data, width, height, bitsPerComponent, // expected-warning{{leak}}
1457     bytesPerRow, space, bitmapInfo, releaseCallback, number);
1458 }
1459
1460 //===----------------------------------------------------------------------===//
1461 // <rdar://problem/7265711> allow 'new', 'copy', 'alloc', 'init' prefix to
1462 //  start before '_' when determining Cocoa fundamental rule
1463 //
1464 // Previously the retain/release checker just skipped prefixes before the
1465 // first '_' entirely.  Now the checker honors the prefix if it results in a
1466 // recognizable naming convention (e.g., 'new', 'init').
1467 //===----------------------------------------------------------------------===//
1468
1469 @interface RDar7265711 {}
1470 - (id) new_stuff;
1471 @end
1472
1473 void rdar7265711_a(RDar7265711 *x) {
1474   id y = [x new_stuff]; // expected-warning{{leak}}
1475 }
1476
1477 void rdar7265711_b(RDar7265711 *x) {
1478   id y = [x new_stuff]; // no-warning
1479   [y release];
1480 }
1481
1482 //===----------------------------------------------------------------------===//
1483 // <rdar://problem/7306898> clang thinks [NSCursor dragCopyCursor] returns a
1484 //                          retained reference
1485 //===----------------------------------------------------------------------===//
1486
1487 @interface NSCursor : NSObject
1488 + (NSCursor *)dragCopyCursor;
1489 @end
1490
1491 void rdar7306898(void) {
1492   // 'dragCopyCursor' does not follow Cocoa's fundamental rule.  It is a noun, not an sentence
1493   // implying a 'copy' of something.
1494   NSCursor *c =  [NSCursor dragCopyCursor]; // no-warning
1495   NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1496 }
1497
1498 //===----------------------------------------------------------------------===//
1499 // <rdar://problem/7252064> sending 'release', 'retain', etc. to a Class
1500 // directly is not likely what the user intended
1501 //===----------------------------------------------------------------------===//
1502
1503 @interface RDar7252064 : NSObject @end
1504 void rdar7252064(void) {
1505   [RDar7252064 release]; // expected-warning{{The 'release' message should be sent to instances of class 'RDar7252064' and not the class directly}}
1506   [RDar7252064 retain]; // expected-warning{{The 'retain' message should be sent to instances of class 'RDar7252064' and not the class directly}}
1507   [RDar7252064 autorelease]; // expected-warning{{The 'autorelease' message should be sent to instances of class 'RDar7252064' and not the class directly}}
1508   [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}}
1509 }
1510
1511 //===----------------------------------------------------------------------===//
1512 // Tests of ownership attributes.
1513 //===----------------------------------------------------------------------===//
1514
1515 typedef NSString* MyStringTy;
1516
1517 @protocol FooP;
1518
1519 @interface TestOwnershipAttr : NSObject
1520 - (NSString*) returnsAnOwnedString  NS_RETURNS_RETAINED; // no-warning
1521 - (NSString*) returnsAnOwnedCFString  CF_RETURNS_RETAINED; // no-warning
1522 - (MyStringTy) returnsAnOwnedTypedString NS_RETURNS_RETAINED; // no-warning
1523 - (NSString*) newString NS_RETURNS_NOT_RETAINED; // no-warning
1524 - (NSString*) newString_auto NS_RETURNS_AUTORELEASED; // no-warning
1525 - (NSString*) newStringNoAttr;
1526 - (int) returnsAnOwnedInt NS_RETURNS_RETAINED; // expected-warning{{'ns_returns_retained' attribute only applies to methods that return an Objective-C object}}
1527 - (id) pseudoInit NS_CONSUMES_SELF NS_RETURNS_RETAINED;
1528 + (void) consume:(id) NS_CONSUMED x;
1529 + (void) consume2:(id) CF_CONSUMED x;
1530 @end
1531
1532 static int ownership_attribute_doesnt_go_here NS_RETURNS_RETAINED; // expected-warning{{'ns_returns_retained' only applies to function types; type here is 'int'}}
1533
1534 void test_attr_1(TestOwnershipAttr *X) {
1535   NSString *str = [X returnsAnOwnedString]; // expected-warning{{leak}}
1536 }
1537
1538 void test_attr_1b(TestOwnershipAttr *X) {
1539   NSString *str = [X returnsAnOwnedCFString]; // expected-warning{{leak}}
1540 }
1541
1542 void test_attr1c(TestOwnershipAttr *X) {
1543   NSString *str = [X newString]; // no-warning
1544   NSString *str2 = [X newStringNoAttr]; // expected-warning{{leak}}
1545   NSString *str3 = [X newString_auto]; // no-warning
1546   NSString *str4 = [[X newString_auto] retain]; // expected-warning {{leak}}
1547 }
1548
1549 void testattr2_a() {
1550   TestOwnershipAttr *x = [TestOwnershipAttr alloc]; // expected-warning{{leak}}
1551 }
1552
1553 void testattr2_b() {
1554   TestOwnershipAttr *x = [[TestOwnershipAttr alloc] pseudoInit];  // expected-warning{{leak}}
1555 }
1556
1557 void testattr2_b_11358224_self_assign_looses_the_leak() {
1558   TestOwnershipAttr *x = [[TestOwnershipAttr alloc] pseudoInit];// expected-warning{{leak}}
1559   x = x;
1560 }
1561
1562 void testattr2_c() {
1563   TestOwnershipAttr *x = [[TestOwnershipAttr alloc] pseudoInit]; // no-warning
1564   [x release];
1565 }
1566
1567 void testattr3() {
1568   TestOwnershipAttr *x = [TestOwnershipAttr alloc]; // no-warning
1569   [TestOwnershipAttr consume:x];
1570   TestOwnershipAttr *y = [TestOwnershipAttr alloc]; // no-warning
1571   [TestOwnershipAttr consume2:y];
1572 }
1573
1574 void consume_ns(id NS_CONSUMED x);
1575 void consume_cf(id CF_CONSUMED x);
1576
1577 void testattr4() {
1578   TestOwnershipAttr *x = [TestOwnershipAttr alloc]; // no-warning
1579   consume_ns(x);
1580   TestOwnershipAttr *y = [TestOwnershipAttr alloc]; // no-warning
1581   consume_cf(y);
1582 }
1583
1584 @interface TestOwnershipAttr2 : NSObject
1585 - (NSString*) newString NS_RETURNS_NOT_RETAINED; // no-warning
1586 @end
1587
1588 @implementation TestOwnershipAttr2
1589 - (NSString*) newString {
1590   return [NSString alloc]; // expected-warning {{Potential leak of an object}}
1591 }
1592 @end
1593
1594 @interface MyClassTestCFAttr : NSObject {}
1595 - (NSDate*) returnsCFRetained CF_RETURNS_RETAINED;
1596 - (CFDateRef) returnsCFRetainedAsCF CF_RETURNS_RETAINED;
1597 - (CFDateRef) newCFRetainedAsCF CF_RETURNS_NOT_RETAINED;
1598 - (CFDateRef) newCFRetainedAsCFNoAttr;
1599 - (NSDate*) alsoReturnsRetained;
1600 - (CFDateRef) alsoReturnsRetainedAsCF;
1601 - (NSDate*) returnsNSRetained NS_RETURNS_RETAINED;
1602 @end
1603
1604 CF_RETURNS_RETAINED
1605 CFDateRef returnsRetainedCFDate()  {
1606   return CFDateCreate(0, CFAbsoluteTimeGetCurrent());
1607 }
1608
1609 @implementation MyClassTestCFAttr
1610 - (NSDate*) returnsCFRetained {
1611   return (NSDate*) returnsRetainedCFDate(); // No leak.
1612 }
1613
1614 - (CFDateRef) returnsCFRetainedAsCF {
1615   return returnsRetainedCFDate(); // No leak.
1616 }
1617
1618 - (CFDateRef) newCFRetainedAsCF {
1619   return (CFDateRef)[(id)[self returnsCFRetainedAsCF] autorelease];
1620 }
1621
1622 - (CFDateRef) newCFRetainedAsCFNoAttr {
1623   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}}
1624 }
1625
1626 - (NSDate*) alsoReturnsRetained {
1627   return (NSDate*) returnsRetainedCFDate(); // expected-warning{{leak}}
1628 }
1629
1630 - (CFDateRef) alsoReturnsRetainedAsCF {
1631   return returnsRetainedCFDate(); // expected-warning{{leak}}
1632 }
1633
1634
1635 - (NSDate*) returnsNSRetained {
1636   return (NSDate*) returnsRetainedCFDate(); // no-warning
1637 }
1638 @end
1639
1640 //===----------------------------------------------------------------------===//
1641 // Test that leaks post-dominated by "panic" functions are not reported.
1642 //
1643 // <rdar://problem/5905851> do not report a leak when post-dominated by a call
1644 // to a noreturn or panic function
1645 //===----------------------------------------------------------------------===//
1646
1647 void panic() __attribute__((noreturn));
1648 void panic_not_in_hardcoded_list() __attribute__((noreturn));
1649
1650 void test_panic_negative() {
1651   signed z = 1;
1652   CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z);  // expected-warning{{leak}}
1653 }
1654
1655 void test_panic_positive() {
1656   signed z = 1;
1657   CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // no-warning
1658   panic();
1659 }
1660
1661 void test_panic_neg_2(int x) {
1662   signed z = 1;
1663   CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // expected-warning{{leak}}
1664   if (x)
1665     panic();
1666 }
1667
1668 void test_panic_pos_2(int x) {
1669   signed z = 1;
1670   CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // no-warning
1671   if (x)
1672     panic();
1673   if (!x) {
1674     // This showed up in <rdar://problem/7796563>, where we silently missed checking
1675     // the function type for noreturn.  "panic()" is a hard-coded known panic function
1676     // that isn't always noreturn.
1677     panic_not_in_hardcoded_list();
1678   }
1679 }
1680
1681 //===----------------------------------------------------------------------===//
1682 // Test uses of blocks (closures)
1683 //===----------------------------------------------------------------------===//
1684
1685 void test_blocks_1_pos(void) {
1686   NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1687   ^{}();
1688 }
1689
1690 void test_blocks_1_indirect_release(void) {
1691   NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1692   ^{ [number release]; }();
1693 }
1694
1695 void test_blocks_1_indirect_retain(void) {
1696   // Eventually this should be reported as a leak.
1697   NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1698   ^{ [number retain]; }();
1699 }
1700
1701 void test_blocks_1_indirect_release_via_call(void) {
1702   NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1703   ^(NSObject *o){ [o release]; }(number);
1704 }
1705
1706 void test_blocks_1_indirect_retain_via_call(void) {
1707   NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning {{leak}}
1708   ^(NSObject *o){ [o retain]; }(number);
1709 }
1710
1711 //===--------------------------------------------------------------------===//
1712 // Test sending message to super that returns an object alias.  Previously
1713 // this caused a crash in the analyzer.
1714 //===--------------------------------------------------------------------===//
1715
1716 @interface Rdar8015556 : NSObject {} @end
1717 @implementation Rdar8015556
1718 - (id)retain {
1719   return [super retain];
1720 }
1721 @end
1722
1723 // <rdar://problem/8272168> - Correcly handle Class<...> in Cocoa Conventions
1724 // detector.
1725
1726 @protocol Prot_R8272168 @end
1727 Class <Prot_R8272168> GetAClassThatImplementsProt_R8272168();
1728 void r8272168() {
1729   GetAClassThatImplementsProt_R8272168();
1730 }
1731
1732 // Test case for <rdar://problem/8356342>, which in the past triggered
1733 // a false positive.
1734 @interface RDar8356342
1735 - (NSDate*) rdar8356342:(NSDate *)inValue;
1736 @end
1737
1738 @implementation RDar8356342
1739 - (NSDate*) rdar8356342:(NSDate*)inValue {
1740   NSDate *outValue = inValue;
1741   if (outValue == 0)
1742     outValue = [[NSDate alloc] init]; // no-warning
1743
1744   if (outValue != inValue)
1745     [outValue autorelease];
1746
1747   return outValue;
1748 }
1749 @end
1750
1751 // <rdar://problem/8724287> - This test case previously crashed because
1752 // of a bug in BugReporter.
1753 extern const void *CFDictionaryGetValue(CFDictionaryRef theDict, const void *key);
1754 typedef struct __CFError * CFErrorRef;
1755 extern const CFStringRef kCFErrorUnderlyingErrorKey;
1756 extern CFDictionaryRef CFErrorCopyUserInfo(CFErrorRef err);
1757 static void rdar_8724287(CFErrorRef error)
1758 {
1759     CFErrorRef error_to_dump;
1760
1761     error_to_dump = error;
1762     while (error_to_dump != ((void*)0)) {
1763         CFDictionaryRef info;
1764
1765         info = CFErrorCopyUserInfo(error_to_dump); // expected-warning{{Potential leak of an object}}
1766
1767         if (info != ((void*)0)) {
1768         }
1769
1770         error_to_dump = (CFErrorRef) CFDictionaryGetValue(info, kCFErrorUnderlyingErrorKey);
1771     }
1772 }
1773
1774 // <rdar://problem/9234108> - Make sure the model applies cf_consumed
1775 // correctly in argument positions besides the first.
1776 extern void *CFStringCreate(void);
1777 extern void rdar_9234108_helper(void *key, void * CF_CONSUMED value);
1778 void rdar_9234108() {
1779   rdar_9234108_helper(0, CFStringCreate());
1780 }
1781
1782 // <rdar://problem/9726279> - Make sure that objc_method_family works
1783 // to override naming conventions.
1784 struct TwoDoubles {
1785   double one;
1786   double two;
1787 };
1788 typedef struct TwoDoubles TwoDoubles;
1789
1790 @interface NSValue (Mine)
1791 - (id)_prefix_initWithTwoDoubles:(TwoDoubles)twoDoubles __attribute__((objc_method_family(init)));
1792 @end
1793
1794 @implementation NSValue (Mine)
1795 - (id)_prefix_initWithTwoDoubles:(TwoDoubles)twoDoubles
1796 {
1797   return [self init];
1798 }
1799 @end
1800
1801 void rdar9726279() {
1802   TwoDoubles twoDoubles = { 0.0, 0.0 };
1803   NSValue *value = [[NSValue alloc] _prefix_initWithTwoDoubles:twoDoubles];
1804   [value release];
1805 }
1806
1807 // <rdar://problem/9732321>
1808 // Test camelcase support for CF conventions.  While Core Foundation APIs
1809 // don't use camel casing, other code is allowed to use it.
1810 CFArrayRef camelcase_create_1() {
1811   return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1812 }
1813
1814 CFArrayRef camelcase_createno() {
1815   return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1816 }
1817
1818 CFArrayRef camelcase_copy() {
1819   return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1820 }
1821
1822 CFArrayRef camelcase_copying() {
1823   return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1824 }
1825
1826 CFArrayRef copyCamelCase() {
1827   return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1828 }
1829
1830 CFArrayRef __copyCamelCase() {
1831   return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1832 }
1833
1834 CFArrayRef __createCamelCase() {
1835   return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1836 }
1837
1838 CFArrayRef camel_create() {
1839   return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1840 }
1841
1842
1843 CFArrayRef camel_creat() {
1844   return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1845 }
1846
1847 CFArrayRef camel_copy() {
1848   return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1849 }
1850
1851 CFArrayRef camel_copyMachine() {
1852   return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
1853 }
1854
1855 CFArrayRef camel_copymachine() {
1856   return CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning {{leak}}
1857 }
1858
1859 // rdar://problem/8024350
1860 @protocol F18P
1861 - (id) clone; // expected-note 2 {{method declared here}}
1862 @end
1863 @interface F18 : NSObject<F18P> @end
1864 @interface F18(Cat)
1865 - (id) clone NS_RETURNS_RETAINED; // expected-warning {{overriding method has mismatched ns_returns_retained attributes}}
1866 @end
1867
1868 @implementation F18
1869 - (id) clone { // expected-warning {{overriding method has mismatched ns_returns_retained attributes}}
1870   return [F18 alloc];
1871 }
1872 @end
1873
1874 // Radar 6582778.
1875 void rdar6582778(void) {
1876   CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
1877   CFTypeRef vals[] = { CFDateCreate(0, t) }; // expected-warning {{leak}}
1878 }
1879
1880 CFTypeRef global;
1881
1882 void rdar6582778_2(void) {
1883   CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
1884   global = CFDateCreate(0, t); // no-warning
1885 }
1886
1887 // <rdar://problem/10232019> - Test that objects passed to containers
1888 // are marked "escaped".
1889
1890 void rdar10232019() {
1891   NSMutableArray *array = [NSMutableArray array];
1892
1893   NSString *string = [[NSString alloc] initWithUTF8String:"foo"];
1894   [array addObject:string];
1895   [string release];
1896
1897   NSString *otherString = [string stringByAppendingString:@"bar"]; // no-warning
1898   NSLog(@"%@", otherString);
1899 }
1900
1901 void rdar10232019_positive() {
1902   NSMutableArray *array = [NSMutableArray array];
1903
1904   NSString *string = [[NSString alloc] initWithUTF8String:"foo"];
1905   [string release];
1906
1907   NSString *otherString = [string stringByAppendingString:@"bar"]; // expected-warning {{Reference-counted object is used after it is release}}
1908   NSLog(@"%@", otherString);
1909 }
1910
1911 // RetainCountChecker support for XPC.
1912 // <rdar://problem/9658496>
1913 typedef void * xpc_object_t;
1914 xpc_object_t _CFXPCCreateXPCObjectFromCFObject(CFTypeRef cf);
1915 void xpc_release(xpc_object_t object);
1916
1917 void rdar9658496() {
1918   CFStringRef cf;
1919   xpc_object_t xpc;
1920   cf = CFStringCreateWithCString( ((CFAllocatorRef)0), "test", kCFStringEncodingUTF8 ); // no-warning
1921   xpc = _CFXPCCreateXPCObjectFromCFObject( cf );
1922   CFRelease(cf);
1923   xpc_release(xpc);
1924 }
1925
1926 // Support annotations with method families.
1927 @interface RDar10824732 : NSObject
1928 - (id)initWithObj:(id CF_CONSUMED)obj;
1929 @end
1930
1931 @implementation RDar10824732
1932 - (id)initWithObj:(id)obj {
1933   [obj release];
1934   return [super init];
1935 }
1936 @end
1937
1938 void rdar_10824732() {
1939   @autoreleasepool {
1940     NSString *obj = @"test";
1941     RDar10824732 *foo = [[RDar10824732 alloc] initWithObj:obj]; // no-warning
1942     [foo release];
1943   }
1944 }
1945
1946 // Stop tracking objects passed to functions, which take callbacks as parameters.
1947 // radar://10973977
1948 typedef int (*CloseCallback) (void *);
1949 void ReaderForIO(CloseCallback ioclose, void *ioctx);
1950 int IOClose(void *context);
1951
1952 @protocol SInS <NSObject>
1953 @end
1954
1955 @interface radar10973977 : NSObject
1956 - (id<SInS>)inputS;
1957 - (void)reader;
1958 @end
1959
1960 @implementation radar10973977
1961 - (void)reader
1962 {
1963     id<SInS> inputS = [[self inputS] retain];
1964     ReaderForIO(IOClose, inputS);
1965 }
1966 - (id<SInS>)inputS
1967 {
1968     return 0;
1969 }
1970 @end
1971
1972 // Object escapes through a selector callback: radar://11398514
1973 extern id NSApp;
1974 @interface MySheetController
1975 - (id<SInS>)inputS;
1976 - (void)showDoSomethingSheetAction:(id)action;
1977 - (void)sheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo;
1978 @end
1979
1980 @implementation MySheetController
1981 - (id<SInS>)inputS {
1982     return 0;
1983 }
1984 - (void)showDoSomethingSheetAction:(id)action {
1985   id<SInS> inputS = [[self inputS] retain]; 
1986   [NSApp beginSheet:0
1987          modalForWindow:0
1988          modalDelegate:0
1989          didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:)
1990          contextInfo:(void *)inputS]; // no - warning
1991 }
1992 - (void)sheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo {
1993    
1994       id contextObject = (id)contextInfo;
1995       [contextObject release];
1996 }
1997
1998 - (id)copyAutoreleaseRadar13081402 {
1999   id x = [[[NSString alloc] initWithUTF8String:"foo"] autorelease];
2000   [x retain];
2001   return x; // no warning
2002 }
2003
2004 @end
2005 //===----------------------------------------------------------------------===//
2006 // Test returning allocated memory in a struct.
2007 //
2008 // We currently don't have a general way to track pointers that "escape".
2009 // Here we test that RetainCountChecker doesn't get excited about returning
2010 // allocated CF objects in struct fields.
2011 //===----------------------------------------------------------------------===//
2012 void *malloc(size_t);
2013 struct rdar11104566 { CFStringRef myStr; };
2014 struct rdar11104566 test_rdar11104566() {
2015   CFStringRef cf = CFStringCreateWithCString( ((CFAllocatorRef)0), "test", kCFStringEncodingUTF8 ); // no-warning
2016   struct rdar11104566 V;
2017   V.myStr = cf;
2018   return V; // no-warning
2019 }
2020
2021 struct rdar11104566 *test_2_rdar11104566() {
2022   CFStringRef cf = CFStringCreateWithCString( ((CFAllocatorRef)0), "test", kCFStringEncodingUTF8 ); // no-warning
2023   struct rdar11104566 *V = (struct rdar11104566 *) malloc(sizeof(*V));
2024   V->myStr = cf;
2025   return V; // no-warning
2026 }
2027
2028 //===----------------------------------------------------------------------===//
2029 // ObjC literals support.
2030 //===----------------------------------------------------------------------===//
2031
2032 void test_objc_arrays() {
2033     { // CASE ONE -- OBJECT IN ARRAY CREATED DIRECTLY
2034         NSObject *o = [[NSObject alloc] init];
2035         NSArray *a = [[NSArray alloc] initWithObjects:o, (void*)0]; // expected-warning {{leak}}
2036         [o release];
2037         [a description];
2038         [o description];
2039     }
2040
2041     { // CASE TWO -- OBJECT IN ARRAY CREATED BY DUPING AUTORELEASED ARRAY
2042         NSObject *o = [[NSObject alloc] init];
2043         NSArray *a1 = [NSArray arrayWithObjects:o, (void*)0];
2044         NSArray *a2 = [[NSArray alloc] initWithArray:a1]; // expected-warning {{leak}}
2045         [o release];        
2046         [a2 description];
2047         [o description];
2048     }
2049
2050     { // CASE THREE -- OBJECT IN RETAINED @[]
2051         NSObject *o = [[NSObject alloc] init];
2052         NSArray *a3 = [@[o] retain]; // expected-warning {{leak}}
2053         [o release];        
2054         [a3 description];
2055         [o description];
2056     }
2057     
2058     { // CASE FOUR -- OBJECT IN ARRAY CREATED BY DUPING @[]
2059         NSObject *o = [[NSObject alloc] init];
2060         NSArray *a = [[NSArray alloc] initWithArray:@[o]]; // expected-warning {{leak}}
2061         [o release];
2062         
2063         [a description];
2064         [o description];
2065     }
2066     
2067     { // CASE FIVE -- OBJECT IN RETAINED @{}
2068         NSValue *o = [[NSValue alloc] init];
2069         NSDictionary *a = [@{o : o} retain]; // expected-warning {{leak}}
2070         [o release];
2071         
2072         [a description];
2073         [o description];
2074     }
2075 }
2076
2077 void test_objc_integer_literals() {
2078   id value = [@1 retain]; // expected-warning {{leak}}
2079   [value description];
2080 }
2081
2082 void test_objc_boxed_expressions(int x, const char *y) {
2083   id value = [@(x) retain]; // expected-warning {{leak}}
2084   [value description];
2085
2086   value = [@(y) retain]; // expected-warning {{leak}}
2087   [value description];
2088 }
2089
2090 // Test NSLog doesn't escape tracked objects.
2091 void rdar11400885(int y)
2092 {
2093   @autoreleasepool {
2094     NSString *printString;
2095     if(y > 2)
2096       printString = [[NSString alloc] init];
2097     else
2098       printString = [[NSString alloc] init];
2099     NSLog(@"Once %@", printString);
2100     [printString release];
2101     NSLog(@"Again: %@", printString); // expected-warning {{Reference-counted object is used after it is released}}
2102   }
2103 }
2104
2105 id makeCollectableNonLeak() {
2106   extern CFTypeRef CFCreateSomething();
2107
2108   CFTypeRef object = CFCreateSomething(); // +1
2109   CFRetain(object); // +2
2110   id objCObject = NSMakeCollectable(object); // +2
2111   [objCObject release]; // +1
2112   return [objCObject autorelease]; // +0
2113 }
2114
2115 void consumeAndStopTracking(id NS_CONSUMED obj, void (^callback)(void));
2116 void CFConsumeAndStopTracking(CFTypeRef CF_CONSUMED obj, void (^callback)(void));
2117
2118 void testConsumeAndStopTracking() {
2119   id retained = [@[] retain]; // +1
2120   consumeAndStopTracking(retained, ^{}); // no-warning
2121
2122   id doubleRetained = [[@[] retain] retain]; // +2
2123   consumeAndStopTracking(doubleRetained, ^{
2124     [doubleRetained release];
2125   }); // no-warning
2126
2127   id unretained = @[]; // +0
2128   consumeAndStopTracking(unretained, ^{}); // expected-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
2129 }
2130
2131 void testCFConsumeAndStopTracking() {
2132   id retained = [@[] retain]; // +1
2133   CFConsumeAndStopTracking((CFTypeRef)retained, ^{}); // no-warning
2134
2135   id doubleRetained = [[@[] retain] retain]; // +2
2136   CFConsumeAndStopTracking((CFTypeRef)doubleRetained, ^{
2137     [doubleRetained release];
2138   }); // no-warning
2139
2140   id unretained = @[]; // +0
2141   CFConsumeAndStopTracking((CFTypeRef)unretained, ^{}); // expected-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
2142 }
2143 //===----------------------------------------------------------------------===//
2144 // Test 'pragma clang arc_cf_code_audited' support.
2145 //===----------------------------------------------------------------------===//
2146
2147 typedef void *MyCFType;
2148 #pragma clang arc_cf_code_audited begin
2149 MyCFType CreateMyCFType();
2150 #pragma clang arc_cf_code_audited end 
2151     
2152 void test_custom_cf() {
2153   MyCFType x = CreateMyCFType(); // expected-warning {{leak of an object stored into 'x'}}
2154 }
2155
2156 //===----------------------------------------------------------------------===//
2157 // Test calling CFPlugInInstanceCreate, which appears in CF but doesn't
2158 // return a CF object.
2159 //===----------------------------------------------------------------------===//
2160
2161 void test_CFPlugInInstanceCreate(CFUUIDRef factoryUUID, CFUUIDRef typeUUID) {
2162   CFPlugInInstanceCreate(kCFAllocatorDefault, factoryUUID, typeUUID); // no-warning
2163 }
2164
2165 //===----------------------------------------------------------------------===//
2166 // PR14927: -drain only has retain-count semantics on NSAutoreleasePool.
2167 //===----------------------------------------------------------------------===//
2168
2169 @interface PR14927 : NSObject
2170 - (void)drain;
2171 @end
2172
2173 void test_drain() {
2174   PR14927 *obj = [[PR14927 alloc] init];
2175   [obj drain];
2176   [obj release]; // no-warning
2177 }
2178
2179 //===----------------------------------------------------------------------===//
2180 // Allow cf_returns_retained and cf_returns_not_retained to mark a return
2181 // value as tracked, even if the object isn't a known CF type.
2182 //===----------------------------------------------------------------------===//
2183
2184 MyCFType getCustom() __attribute__((cf_returns_not_retained));
2185 MyCFType makeCustom() __attribute__((cf_returns_retained));
2186
2187 void testCustomReturnsRetained() {
2188   MyCFType obj = makeCustom(); // expected-warning {{leak of an object stored into 'obj'}}
2189 }
2190
2191 void testCustomReturnsNotRetained() {
2192   CFRelease(getCustom()); // expected-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
2193 }
2194
2195 //===----------------------------------------------------------------------===//
2196 // Don't print variables which are out of the current scope.
2197 //===----------------------------------------------------------------------===//
2198 @interface MyObj12706177 : NSObject
2199 -(id)initX;
2200 +(void)test12706177;
2201 @end
2202 static int Cond;
2203 @implementation MyObj12706177
2204 -(id)initX {
2205   if (Cond)
2206     return 0;
2207   self = [super init];
2208   return self;
2209 }
2210 +(void)test12706177 {
2211   id x = [[MyObj12706177 alloc] initX]; //expected-warning {{Potential leak of an object}}
2212   [x release]; 
2213 }
2214 @end
2215
2216 //===----------------------------------------------------------------------===//
2217 // CFAutorelease
2218 //===----------------------------------------------------------------------===//
2219
2220 CFTypeRef getAutoreleasedCFType() {
2221   extern CFTypeRef CFCreateSomething();
2222   return CFAutorelease(CFCreateSomething()); // no-warning
2223 }
2224
2225 CFTypeRef getIncorrectlyAutoreleasedCFType() {
2226   extern CFTypeRef CFGetSomething();
2227   return CFAutorelease(CFGetSomething()); // expected-warning{{Object autoreleased too many times}}
2228 }
2229
2230 CFTypeRef createIncorrectlyAutoreleasedCFType() {
2231   extern CFTypeRef CFCreateSomething();
2232   return CFAutorelease(CFCreateSomething()); // expected-warning{{Object with a +0 retain count returned to caller where a +1 (owning) retain count is expected}}
2233 }
2234
2235 void useAfterAutorelease() {
2236   extern CFTypeRef CFCreateSomething();
2237   CFTypeRef obj = CFCreateSomething();
2238   CFAutorelease(obj);
2239
2240   extern void useCF(CFTypeRef);
2241   useCF(obj); // no-warning
2242 }
2243
2244 void useAfterRelease() {
2245   // Sanity check that the previous example would have warned with CFRelease.
2246   extern CFTypeRef CFCreateSomething();
2247   CFTypeRef obj = CFCreateSomething();
2248   CFRelease(obj);
2249
2250   extern void useCF(CFTypeRef);
2251   useCF(obj); // expected-warning{{Reference-counted object is used after it is released}}
2252 }
2253
2254 void testAutoreleaseReturnsInput() {
2255   extern CFTypeRef CFCreateSomething();
2256   CFTypeRef obj = CFCreateSomething(); // expected-warning{{Potential leak of an object stored into 'obj'}}
2257   CFTypeRef second = CFAutorelease(obj);
2258   CFRetain(second);
2259 }
2260
2261 CFTypeRef testAutoreleaseReturnsInputSilent() {
2262   extern CFTypeRef CFCreateSomething();
2263   CFTypeRef obj = CFCreateSomething();
2264   CFTypeRef alias = CFAutorelease(obj);
2265   CFRetain(alias);
2266   CFRelease(obj);
2267   return obj; // no-warning
2268 }
2269
2270 void autoreleaseTypedObject() {
2271   CFArrayRef arr = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
2272   CFAutorelease((CFTypeRef)arr); // no-warning
2273 }
2274
2275 void autoreleaseReturningTypedObject() {
2276   CFArrayRef arr = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning{{Potential leak of an object stored into 'arr'}}
2277   CFArrayRef alias = (CFArrayRef)CFAutorelease((CFTypeRef)arr);
2278   CFRetain(alias);
2279 }
2280
2281 CFArrayRef autoreleaseReturningTypedObjectSilent() {
2282   CFArrayRef arr = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
2283   CFArrayRef alias = (CFArrayRef)CFAutorelease((CFTypeRef)arr);
2284   CFRetain(alias);
2285   CFRelease(arr);
2286   return alias; // no-warning
2287 }
2288
2289 void autoreleaseObjC() {
2290   id obj = [@1 retain];
2291   CFAutorelease(obj); // no-warning
2292
2293   id anotherObj = @1;
2294   CFAutorelease(anotherObj);
2295 } // expected-warning{{Object autoreleased too many times}}
2296
2297 //===----------------------------------------------------------------------===//
2298 // <rdar://problem/13783514> xpc_connection_set_finalizer_f
2299 //===----------------------------------------------------------------------===//
2300
2301 typedef xpc_object_t xpc_connection_t;
2302 typedef void (*xpc_finalizer_t)(void *value);
2303 void xpc_connection_set_context(xpc_connection_t connection, void *ctx);
2304 void xpc_connection_set_finalizer_f(xpc_connection_t connection,
2305                                     xpc_finalizer_t finalizer);
2306 void releaseAfterXPC(void *context) {
2307   [(NSArray *)context release];
2308 }
2309
2310 void rdar13783514(xpc_connection_t connection) {
2311   xpc_connection_set_context(connection, [[NSMutableArray alloc] init]);
2312   xpc_connection_set_finalizer_f(connection, releaseAfterXPC);
2313 } // no-warning
2314
2315 // Do not report leaks when object is cleaned up with __attribute__((cleanup ..)).
2316 inline static void cleanupFunction(void *tp) {
2317     CFTypeRef x = *(CFTypeRef *)tp;
2318     if (x) {
2319         CFRelease(x);
2320     }
2321 }
2322 #define ADDCLEANUP __attribute__((cleanup(cleanupFunction)))
2323 void foo() {
2324   ADDCLEANUP CFStringRef myString;
2325   myString = CFStringCreateWithCString(0, "hello world", kCFStringEncodingUTF8);
2326   ADDCLEANUP CFStringRef myString2 = 
2327     CFStringCreateWithCString(0, "hello world", kCFStringEncodingUTF8);
2328 }
2329
2330 //===----------------------------------------------------------------------===//
2331 // Handle NSNull
2332 //===----------------------------------------------------------------------===//
2333
2334 __attribute__((ns_returns_retained))
2335 id returnNSNull() {
2336   return [NSNull null]; // no-warning
2337 }
2338
2339 //===----------------------------------------------------------------------===//
2340 // cf_returns_[not_]retained on parameters
2341 //===----------------------------------------------------------------------===//
2342
2343 void testCFReturnsNotRetained() {
2344   extern void getViaParam(CFTypeRef * CF_RETURNS_NOT_RETAINED outObj);
2345   CFTypeRef obj;
2346   getViaParam(&obj);
2347   CFRelease(obj); // // expected-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
2348 }
2349
2350 void testCFReturnsNotRetainedAnnotated() {
2351   extern void getViaParam2(CFTypeRef * _Nonnull CF_RETURNS_NOT_RETAINED outObj);
2352   CFTypeRef obj;
2353   getViaParam2(&obj);
2354   CFRelease(obj); // // expected-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
2355 }
2356
2357 void testCFReturnsRetained() {
2358   extern int copyViaParam(CFTypeRef * CF_RETURNS_RETAINED outObj);
2359   CFTypeRef obj;
2360   copyViaParam(&obj);
2361   CFRelease(obj);
2362   CFRelease(obj); // // FIXME-warning {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
2363 }
2364
2365 void testCFReturnsRetainedError() {
2366   extern int copyViaParam(CFTypeRef * CF_RETURNS_RETAINED outObj);
2367   CFTypeRef obj;
2368   if (copyViaParam(&obj) == -42)
2369     return; // no-warning
2370   CFRelease(obj);
2371 }