Debian Codegraph @

clang/test/ARCMT/objcmt-arc-cf-annotations.m.result

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