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