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