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