1 // RUN: %clang_cc1 -triple x86_64-apple-darwin10 -analyze -analyzer-checker=core,macosx.CFRetainRelease,cocoa.ClassRelease -analyzer-check-objc-mem -analyzer-store=basic -fblocks -verify %s
2 // RUN: %clang_cc1 -triple x86_64-apple-darwin10 -analyze -analyzer-checker=core,macosx.CFRetainRelease,cocoa.ClassRelease -analyzer-check-objc-mem -analyzer-store=region -fblocks -verify %s
4 #if __has_feature(attribute_ns_returns_retained)
5 #define NS_RETURNS_RETAINED __attribute__((ns_returns_retained))
7 #if __has_feature(attribute_cf_returns_retained)
8 #define CF_RETURNS_RETAINED __attribute__((cf_returns_retained))
10 #if __has_feature(attribute_ns_returns_not_retained)
11 #define NS_RETURNS_NOT_RETAINED __attribute__((ns_returns_not_retained))
13 #if __has_feature(attribute_cf_returns_not_retained)
14 #define CF_RETURNS_NOT_RETAINED __attribute__((cf_returns_not_retained))
16 #if __has_feature(attribute_ns_consumes_self)
17 #define NS_CONSUMES_SELF __attribute__((ns_consumes_self))
19 #if __has_feature(attribute_ns_consumed)
20 #define NS_CONSUMED __attribute__((ns_consumed))
22 #if __has_feature(attribute_cf_consumed)
23 #define CF_CONSUMED __attribute__((cf_consumed))
26 //===----------------------------------------------------------------------===//
27 // The following code is reduced using delta-debugging from Mac OS X headers:
29 // #include <Cocoa/Cocoa.h>
30 // #include <CoreFoundation/CoreFoundation.h>
31 // #include <DiskArbitration/DiskArbitration.h>
32 // #include <QuartzCore/QuartzCore.h>
33 // #include <Quartz/Quartz.h>
34 // #include <IOKit/IOKitLib.h>
36 // It includes the basic definitions for the test cases below.
37 //===----------------------------------------------------------------------===//
39 typedef unsigned int __darwin_natural_t;
40 typedef unsigned long uintptr_t;
41 typedef unsigned int uint32_t;
42 typedef unsigned long long uint64_t;
43 typedef unsigned int UInt32;
44 typedef signed long CFIndex;
49 static __inline__ __attribute__((always_inline)) CFRange CFRangeMake(CFIndex loc, CFIndex len) {
55 typedef const void * CFTypeRef;
56 typedef const struct __CFString * CFStringRef;
57 typedef const struct __CFAllocator * CFAllocatorRef;
58 extern const CFAllocatorRef kCFAllocatorDefault;
59 extern CFTypeRef CFRetain(CFTypeRef cf);
60 extern void CFRelease(CFTypeRef cf);
64 extern const CFArrayCallBacks kCFTypeArrayCallBacks;
65 typedef const struct __CFArray * CFArrayRef;
66 typedef struct __CFArray * CFMutableArrayRef;
67 extern CFMutableArrayRef CFArrayCreateMutable(CFAllocatorRef allocator, CFIndex capacity, const CFArrayCallBacks *callBacks);
68 extern const void *CFArrayGetValueAtIndex(CFArrayRef theArray, CFIndex idx);
69 extern void CFArrayAppendValue(CFMutableArrayRef theArray, const void *value);
72 CFDictionaryKeyCallBacks;
73 extern const CFDictionaryKeyCallBacks kCFTypeDictionaryKeyCallBacks;
76 CFDictionaryValueCallBacks;
77 extern const CFDictionaryValueCallBacks kCFTypeDictionaryValueCallBacks;
78 typedef const struct __CFDictionary * CFDictionaryRef;
79 typedef struct __CFDictionary * CFMutableDictionaryRef;
80 extern CFMutableDictionaryRef CFDictionaryCreateMutable(CFAllocatorRef allocator, CFIndex capacity, const CFDictionaryKeyCallBacks *keyCallBacks, const CFDictionaryValueCallBacks *valueCallBacks);
81 typedef UInt32 CFStringEncoding;
83 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 };
84 extern CFStringRef CFStringCreateWithCString(CFAllocatorRef alloc, const char *cStr, CFStringEncoding encoding);
85 typedef double CFTimeInterval;
86 typedef CFTimeInterval CFAbsoluteTime;
87 extern CFAbsoluteTime CFAbsoluteTimeGetCurrent(void);
88 typedef const struct __CFDate * CFDateRef;
89 extern CFDateRef CFDateCreate(CFAllocatorRef allocator, CFAbsoluteTime at);
90 extern CFAbsoluteTime CFDateGetAbsoluteTime(CFDateRef theDate);
91 typedef __darwin_natural_t natural_t;
92 typedef natural_t mach_port_name_t;
93 typedef mach_port_name_t mach_port_t;
94 typedef int kern_return_t;
95 typedef kern_return_t mach_error_t;
97 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 };
98 typedef CFIndex CFNumberType;
99 typedef const struct __CFNumber * CFNumberRef;
100 extern CFNumberRef CFNumberCreate(CFAllocatorRef allocator, CFNumberType theType, const void *valuePtr);
101 typedef const struct __CFAttributedString *CFAttributedStringRef;
102 typedef struct __CFAttributedString *CFMutableAttributedStringRef;
103 extern CFAttributedStringRef CFAttributedStringCreate(CFAllocatorRef alloc, CFStringRef str, CFDictionaryRef attributes) ;
104 extern CFMutableAttributedStringRef CFAttributedStringCreateMutableCopy(CFAllocatorRef alloc, CFIndex maxLength, CFAttributedStringRef aStr) ;
105 extern void CFAttributedStringSetAttribute(CFMutableAttributedStringRef aStr, CFRange range, CFStringRef attrName, CFTypeRef value) ;
106 typedef signed char BOOL;
107 typedef unsigned long NSUInteger;
108 @class NSString, Protocol;
109 extern void NSLog(NSString *format, ...) __attribute__((format(__NSString__, 1, 2)));
110 typedef struct _NSZone NSZone;
111 @class NSInvocation, NSMethodSignature, NSCoder, NSString, NSEnumerator;
113 - (BOOL)isEqual:(id)object;
115 - (oneway void)release;
117 @end @protocol NSCopying - (id)copyWithZone:(NSZone *)zone;
118 @end @protocol NSMutableCopying - (id)mutableCopyWithZone:(NSZone *)zone;
119 @end @protocol NSCoding - (void)encodeWithCoder:(NSCoder *)aCoder;
121 @interface NSObject <NSObject> {}
122 + (id)allocWithZone:(NSZone *)zone;
126 @interface NSObject (NSCoderMethods)
127 - (id)awakeAfterUsingCoder:(NSCoder *)aDecoder;
129 extern id NSAllocateObject(Class aClass, NSUInteger extraBytes, NSZone *zone);
132 NSFastEnumerationState;
133 @protocol NSFastEnumeration - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len;
134 @end @class NSString, NSDictionary;
135 @interface NSValue : NSObject <NSCopying, NSCoding> - (void)getValue:(void *)value;
136 @end @interface NSNumber : NSValue - (char)charValue;
137 - (id)initWithInt:(int)value;
138 @end @class NSString;
139 @interface NSArray : NSObject <NSCopying, NSMutableCopying, NSCoding, NSFastEnumeration> - (NSUInteger)count;
140 @end @interface NSArray (NSArrayCreation) + (id)array;
141 @end @interface NSAutoreleasePool : NSObject {
144 @end extern NSString * const NSBundleDidLoadNotification;
145 typedef double NSTimeInterval;
146 @interface NSDate : NSObject <NSCopying, NSCoding> - (NSTimeInterval)timeIntervalSinceReferenceDate;
147 @end typedef unsigned short unichar;
148 @interface NSString : NSObject <NSCopying, NSMutableCopying, NSCoding> - (NSUInteger)length;
149 - ( const char *)UTF8String;
150 - (id)initWithUTF8String:(const char *)nullTerminatedCString;
151 + (id)stringWithUTF8String:(const char *)nullTerminatedCString;
152 @end @class NSString, NSURL, NSError;
153 @interface NSData : NSObject <NSCopying, NSMutableCopying, NSCoding> - (NSUInteger)length;
154 + (id)dataWithBytesNoCopy:(void *)bytes length:(NSUInteger)length;
155 + (id)dataWithBytesNoCopy:(void *)bytes length:(NSUInteger)length freeWhenDone:(BOOL)b;
156 @end @class NSLocale, NSDate, NSCalendar, NSTimeZone, NSError, NSArray, NSMutableDictionary;
157 @interface NSDictionary : NSObject <NSCopying, NSMutableCopying, NSCoding, NSFastEnumeration> - (NSUInteger)count;
158 @end @interface NSMutableDictionary : NSDictionary - (void)removeObjectForKey:(id)aKey;
159 - (void)setObject:(id)anObject forKey:(id)aKey;
160 @end @interface NSMutableDictionary (NSMutableDictionaryCreation) + (id)dictionaryWithCapacity:(NSUInteger)numItems;
161 @end typedef double CGFloat;
164 typedef struct CGSize CGSize;
167 typedef struct CGRect CGRect;
168 typedef mach_port_t io_object_t;
169 typedef char io_name_t[128];
170 typedef io_object_t io_iterator_t;
171 typedef io_object_t io_service_t;
172 typedef struct IONotificationPort * IONotificationPortRef;
173 typedef void (*IOServiceMatchingCallback)( void * refcon, io_iterator_t iterator );
174 io_service_t IOServiceGetMatchingService( mach_port_t masterPort, CFDictionaryRef matching );
175 kern_return_t IOServiceGetMatchingServices( mach_port_t masterPort, CFDictionaryRef matching, io_iterator_t * existing );
176 kern_return_t IOServiceAddNotification( mach_port_t masterPort, const io_name_t notificationType, CFDictionaryRef matching, mach_port_t wakePort, uintptr_t reference, io_iterator_t * notification ) __attribute__((deprecated));
177 kern_return_t IOServiceAddMatchingNotification( IONotificationPortRef notifyPort, const io_name_t notificationType, CFDictionaryRef matching, IOServiceMatchingCallback callback, void * refCon, io_iterator_t * notification );
178 CFMutableDictionaryRef IOServiceMatching( const char * name );
179 CFMutableDictionaryRef IOServiceNameMatching( const char * name );
180 CFMutableDictionaryRef IOBSDNameMatching( mach_port_t masterPort, uint32_t options, const char * bsdName );
181 CFMutableDictionaryRef IOOpenFirmwarePathMatching( mach_port_t masterPort, uint32_t options, const char * path );
182 CFMutableDictionaryRef IORegistryEntryIDMatching( uint64_t entryID );
183 typedef struct __DASession * DASessionRef;
184 extern DASessionRef DASessionCreate( CFAllocatorRef allocator );
185 typedef struct __DADisk * DADiskRef;
186 extern DADiskRef DADiskCreateFromBSDName( CFAllocatorRef allocator, DASessionRef session, const char * name );
187 extern DADiskRef DADiskCreateFromIOMedia( CFAllocatorRef allocator, DASessionRef session, io_service_t media );
188 extern CFDictionaryRef DADiskCopyDescription( DADiskRef disk );
189 extern DADiskRef DADiskCopyWholeDisk( DADiskRef disk );
190 @interface NSTask : NSObject - (id)init;
191 @end typedef struct CGColorSpace *CGColorSpaceRef;
192 typedef struct CGImage *CGImageRef;
193 typedef struct CGLayer *CGLayerRef;
194 @interface NSResponder : NSObject <NSCoding> {
196 @end @protocol NSAnimatablePropertyContainer - (id)animator;
197 @end extern NSString *NSAnimationTriggerOrderIn ;
198 @interface NSView : NSResponder <NSAnimatablePropertyContainer> {
200 @end @protocol NSValidatedUserInterfaceItem - (SEL)action;
201 @end @protocol NSUserInterfaceValidations - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)anItem;
202 @end @class NSDate, NSDictionary, NSError, NSException, NSNotification;
203 @interface NSApplication : NSResponder <NSUserInterfaceValidations> {
206 NSTerminateCancel = 0, NSTerminateNow = 1, NSTerminateLater = 2 };
207 typedef NSUInteger NSApplicationTerminateReply;
208 @protocol NSApplicationDelegate <NSObject> @optional - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender;
209 @end @class NSAttributedString, NSEvent, NSFont, NSFormatter, NSImage, NSMenu, NSText, NSView, NSTextView;
210 @interface NSCell : NSObject <NSCopying, NSCoding> {
212 @end @class NSTextField, NSPanel, NSArray, NSWindow, NSImage, NSButton, NSError;
216 @interface CIImage : NSObject <NSCoding, NSCopying> {
218 typedef int CIFormat;
220 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 };
221 typedef mach_error_t DAReturn;
222 typedef const struct __DADissenter * DADissenterRef;
223 extern DADissenterRef DADissenterCreate( CFAllocatorRef allocator, DAReturn status, CFStringRef string );
224 @interface CIContext: NSObject {
226 - (CGImageRef)createCGImage:(CIImage *)im fromRect:(CGRect)r;
227 - (CGImageRef)createCGImage:(CIImage *)im fromRect:(CGRect)r format:(CIFormat)f colorSpace:(CGColorSpaceRef)cs;
228 - (CGLayerRef)createCGLayerWithSize:(CGSize)size info:(CFDictionaryRef)d;
229 @end extern NSString* const QCRendererEventKey;
230 @protocol QCCompositionRenderer - (NSDictionary*) attributes;
231 @end @interface QCRenderer : NSObject <QCCompositionRenderer> {
233 - (id) createSnapshotImageOfType:(NSString*)type;
234 @end extern NSString* const QCViewDidStartRenderingNotification;
235 @interface QCView : NSView <QCCompositionRenderer> {
237 - (id) createSnapshotImageOfType:(NSString*)type;
239 ICEXIFOrientation1 = 1, ICEXIFOrientation2 = 2, ICEXIFOrientation3 = 3, ICEXIFOrientation4 = 4, ICEXIFOrientation5 = 5, ICEXIFOrientation6 = 6, ICEXIFOrientation7 = 7, ICEXIFOrientation8 = 8, };
241 @protocol ICDeviceDelegate <NSObject> @required - (void)didRemoveDevice:(ICDevice*)device;
242 @end extern NSString *const ICScannerStatusWarmingUp;
243 @class ICScannerDevice;
244 @protocol ICScannerDeviceDelegate <ICDeviceDelegate> @optional - (void)scannerDeviceDidBecomeAvailable:(ICScannerDevice*)scanner;
247 typedef long unsigned int __darwin_size_t;
248 typedef __darwin_size_t size_t;
249 typedef unsigned long CFTypeID;
254 typedef struct CGPoint CGPoint;
255 typedef struct CGGradient *CGGradientRef;
256 typedef uint32_t CGGradientDrawingOptions;
257 extern CFTypeID CGGradientGetTypeID(void);
258 extern CGGradientRef CGGradientCreateWithColorComponents(CGColorSpaceRef
259 space, const CGFloat components[], const CGFloat locations[], size_t count);
260 extern CGGradientRef CGGradientCreateWithColors(CGColorSpaceRef space,
261 CFArrayRef colors, const CGFloat locations[]);
262 extern CGGradientRef CGGradientRetain(CGGradientRef gradient);
263 extern void CGGradientRelease(CGGradientRef gradient);
264 typedef struct CGContext *CGContextRef;
265 extern void CGContextDrawLinearGradient(CGContextRef context,
266 CGGradientRef gradient, CGPoint startPoint, CGPoint endPoint,
267 CGGradientDrawingOptions options);
268 extern CGColorSpaceRef CGColorSpaceCreateDeviceRGB(void);
270 //===----------------------------------------------------------------------===//
272 //===----------------------------------------------------------------------===//
274 CFAbsoluteTime f1() {
275 CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
276 CFDateRef date = CFDateCreate(0, t);
279 CFDateGetAbsoluteTime(date); // no-warning
281 t = CFDateGetAbsoluteTime(date); // expected-warning{{Reference-counted object is used after it is released.}}
285 CFAbsoluteTime f2() {
286 CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
287 CFDateRef date = CFDateCreate(0, t);
288 [((NSDate*) date) retain];
290 CFDateGetAbsoluteTime(date); // no-warning
291 [((NSDate*) date) release];
292 t = CFDateGetAbsoluteTime(date); // expected-warning{{Reference-counted object is used after it is released.}}
299 // Test to see if we supresss an error when we store the pointer
302 CFAbsoluteTime f3() {
303 CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
304 CFDateRef date = CFDateCreate(0, t);
305 [((NSDate*) date) retain];
307 CFDateGetAbsoluteTime(date); // no-warning
308 global_x = (NSDate*) date;
309 [((NSDate*) date) release];
310 t = CFDateGetAbsoluteTime(date); // no-warning
314 //---------------------------------------------------------------------------
315 // Test case 'f4' differs for region store and basic store. See
316 // retain-release-region-store.m and retain-release-basic-store.m.
317 //---------------------------------------------------------------------------
321 CFAbsoluteTime f5(int x) {
322 CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
323 CFDateRef date = CFDateCreate(0, t); // expected-warning{{leak}}
331 // Test a leak involving the return.
333 CFDateRef f6(int x) {
334 CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent()); // expected-warning{{leak}}
339 // Test a leak involving an overwrite.
342 CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent()); //expected-warning{{leak}}
344 date = CFDateCreate(0, CFAbsoluteTimeGetCurrent());
348 // Generalization of Create rule. MyDateCreate returns a CFXXXTypeRef, and
349 // has the word create.
350 CFDateRef MyDateCreate();
353 CFDateRef date = MyDateCreate(); // expected-warning{{leak}}
359 CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent());
361 // When allocations fail, CFDateCreate can return null.
362 if (!date) *p = 1; // expected-warning{{null}}
366 // Handle DiskArbitration API:
368 // http://developer.apple.com/DOCUMENTATION/DARWIN/Reference/DiscArbitrationFramework/
370 void f10(io_service_t media, DADiskRef d, CFStringRef s) {
371 DADiskRef disk = DADiskCreateFromBSDName(kCFAllocatorDefault, 0, "hello"); // expected-warning{{leak}}
372 if (disk) NSLog(@"ok");
374 disk = DADiskCreateFromIOMedia(kCFAllocatorDefault, 0, media); // expected-warning{{leak}}
375 if (disk) NSLog(@"ok");
377 CFDictionaryRef dict = DADiskCopyDescription(d); // expected-warning{{leak}}
378 if (dict) NSLog(@"ok");
380 disk = DADiskCopyWholeDisk(d); // expected-warning{{leak}}
381 if (disk) NSLog(@"ok");
383 DADissenterRef dissenter = DADissenterCreate(kCFAllocatorDefault, // expected-warning{{leak}}
384 kDAReturnSuccess, s);
385 if (dissenter) NSLog(@"ok");
387 DASessionRef session = DASessionCreate(kCFAllocatorDefault); // expected-warning{{leak}}
388 if (session) NSLog(@"ok");
391 // Test retain/release checker with CFString and CFMutableArray.
394 CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
397 CFStringRef s1 = CFStringCreateWithCString(0, "hello world",
398 kCFStringEncodingUTF8);
400 // Add the string to the array.
401 CFArrayAppendValue(A, s1);
403 // Decrement the reference count.
404 CFRelease(s1); // no-warning
406 // Get the string. We don't own it.
407 s1 = (CFStringRef) CFArrayGetValueAtIndex(A, 0);
409 // Release the array.
410 CFRelease(A); // no-warning
412 // Release the string. This is a bug.
413 CFRelease(s1); // expected-warning{{Incorrect decrement of the reference count}}
416 // PR 3337: Handle functions declared using typedefs.
417 typedef CFTypeRef CREATEFUN();
418 CREATEFUN MyCreateFun;
421 CFTypeRef o = MyCreateFun(); // expected-warning {{leak}}
424 void f13_autorelease() {
425 CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
426 [(id) A autorelease]; // no-warning
429 void f13_autorelease_b() {
430 CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
431 [(id) A autorelease];
432 [(id) A autorelease]; // expected-warning{{Object sent -autorelease too many times}}
435 CFMutableArrayRef f13_autorelease_c() {
436 CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
437 [(id) A autorelease];
438 [(id) A autorelease];
439 return A; // expected-warning{{Object sent -autorelease too many times}}
442 CFMutableArrayRef f13_autorelease_d() {
443 CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
444 [(id) A autorelease];
445 [(id) A autorelease];
446 CFMutableArrayRef B = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning{{Object sent -autorelease too many times}}
447 CFRelease(B); // no-warning
452 // This case exercises the logic where the leak site is the same as the allocation site.
453 void f14_leakimmediately() {
454 CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning{{leak}}
457 // Test that we track an allocated object beyond the point where the *name*
458 // of the variable storing the reference is no longer live.
461 CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
462 CFMutableArrayRef *B = &A;
463 // At this point, the name 'A' is no longer live.
464 CFRelease(*B); // no-warning
467 // Test when we pass NULL to CFRetain/CFRelease.
468 void f16(int x, CFTypeRef p) {
473 CFRelease(p); // expected-warning{{Null pointer argument in call to CFRelease}}
476 CFRetain(p); // expected-warning{{Null pointer argument in call to CFRetain}}
480 // Test that an object is non-null after being CFRetained/CFReleased.
481 void f17(int x, CFTypeRef p) {
485 CFRelease(0); // no-warning
490 CFRetain(0); // no-warning
494 // Test basic tracking of ivars associated with 'self'. For the retain/release
495 // checker we currently do not want to flag leaks associated with stores
496 // of tracked objects to ivars.
497 @interface SelfIvarTest : NSObject {
500 - (void)test_self_tracking;
503 @implementation SelfIvarTest
504 - (void)test_self_tracking {
505 myObj = (id) CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
509 // Test return of non-owned objects in contexts where an owned object
511 @interface TestReturnNotOwnedWhenExpectedOwned
512 - (NSString*)newString;
515 @implementation TestReturnNotOwnedWhenExpectedOwned
516 - (NSString*)newString {
517 NSString *s = [NSString stringWithUTF8String:"hello"];
518 return s; // expected-warning{{Object with +0 retain counts returned to caller where a +1 (owning) retain count is expected}}
522 // <rdar://problem/6659160>
525 static void rdar_6659160(char *inkind, char *inname)
527 // We currently expect that [NSObject alloc] cannot fail. This
528 // will be a toggled flag in the future. It can indeed return null, but
529 // Cocoa programmers generally aren't expected to reason about out-of-memory
531 NSString *kind = [[NSString alloc] initWithUTF8String:inkind]; // expected-warning{{leak}}
533 // We do allow stringWithUTF8String to fail. This isn't really correct, as
534 // far as returning 0. In most error conditions it will throw an exception.
535 // If allocation fails it could return 0, but again this
537 NSString *name = [NSString stringWithUTF8String:inname];
541 const char *kindC = 0;
542 const char *nameC = 0;
544 // In both cases, we cannot reach a point down below where we
545 // dereference kindC or nameC with either being null. This is because
546 // we assume that [NSObject alloc] doesn't fail and that we have the guard
550 kindC = [kind UTF8String];
552 nameC = [name UTF8String];
553 if(!isFoo(kindC[0])) // expected-warning{{null}}
555 if(!isFoo(nameC[0])) // no-warning
559 [name release]; // expected-warning{{Incorrect decrement of the reference count}}
562 // PR 3677 - 'allocWithZone' should be treated as following the Cocoa naming
563 // conventions with respect to 'return'ing ownership.
564 @interface PR3677: NSObject @end
565 @implementation PR3677
566 + (id)allocWithZone:(NSZone *)inZone {
567 return [super allocWithZone:inZone]; // no-warning
571 // PR 3820 - Reason about calls to -dealloc
572 void pr3820_DeallocInsteadOfRelease(void)
574 id foo = [[NSString alloc] init]; // no-warning
576 // foo is not leaked, since it has been deallocated.
579 void pr3820_ReleaseAfterDealloc(void)
581 id foo = [[NSString alloc] init];
583 [foo release]; // expected-warning{{used after it is release}}
584 // NSInternalInconsistencyException: message sent to deallocated object
587 void pr3820_DeallocAfterRelease(void)
589 NSLog(@"\n\n[%s]", __FUNCTION__);
590 id foo = [[NSString alloc] init];
592 [foo dealloc]; // expected-warning{{used after it is released}}
593 // message sent to released object
596 // From <rdar://problem/6704930>. The problem here is that 'length' binds to
597 // '($0 - 1)' after '--length', but SimpleConstraintManager doesn't know how to
598 // reason about '($0 - 1) > constant'. As a temporary hack, we drop the value
599 // of '($0 - 1)' and conjure a new symbol.
600 void rdar6704930(unsigned char *s, unsigned int length) {
608 name = [[NSString alloc] init]; // no-warning
614 if ((length == 0) && (name != 0)) {
618 if (length == 0) { // no ':' found -> use it all as name
619 name = [[NSString alloc] init]; // no-warning
629 //===----------------------------------------------------------------------===//
630 // <rdar://problem/6833332>
631 // One build of the analyzer accidentally stopped tracking the allocated
632 // object after the 'retain'.
633 //===----------------------------------------------------------------------===//
635 @interface rdar_6833332 : NSObject <NSApplicationDelegate> {
638 @property (nonatomic, retain) NSWindow *window;
641 @implementation rdar_6833332
643 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
644 NSMutableDictionary *dict = [[NSMutableDictionary dictionaryWithCapacity:4] retain]; // expected-warning{{leak}}
646 [dict setObject:@"foo" forKey:@"bar"];
656 //===----------------------------------------------------------------------===//
657 // <rdar://problem/6257780> clang checker fails to catch use-after-release
658 //===----------------------------------------------------------------------===//
660 int rdar_6257780_Case1() {
661 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
662 NSArray *array = [NSArray array];
663 [array release]; // expected-warning{{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
668 //===----------------------------------------------------------------------===//
669 // <rdar://problem/6866843> Checker should understand new/setObject:/release constructs
670 //===----------------------------------------------------------------------===//
672 void rdar_6866843() {
673 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
674 NSMutableDictionary* dictionary = [[NSMutableDictionary alloc] init];
675 NSArray* array = [[NSArray alloc] init];
676 [dictionary setObject:array forKey:@"key"];
678 // Using 'array' here should be fine
679 NSLog(@"array = %@\n", array); // no-warning
680 // Now the array is released
681 [dictionary release];
686 //===----------------------------------------------------------------------===//
687 // <rdar://problem/6877235> Classes typedef-ed to CF objects should get the same treatment as CF objects
688 //===----------------------------------------------------------------------===//
690 typedef CFTypeRef OtherRef;
692 @interface RDar6877235 : NSObject {}
693 - (CFTypeRef)_copyCFTypeRef;
694 - (OtherRef)_copyOtherRef;
697 @implementation RDar6877235
698 - (CFTypeRef)_copyCFTypeRef {
699 return [[NSString alloc] init]; // no-warning
701 - (OtherRef)_copyOtherRef {
702 return [[NSString alloc] init]; // no-warning
706 //===----------------------------------------------------------------------===//
707 //<rdar://problem/6320065> false positive - init method returns an object
709 //===----------------------------------------------------------------------===//
711 @interface RDar6320065 : NSObject {
714 - (id)initReturningNewClass;
715 - (id)_initReturningNewClassBad;
716 - (id)initReturningNewClassBad2;
719 @interface RDar6320065Subclass : RDar6320065
722 @implementation RDar6320065
723 - (id)initReturningNewClass {
725 self = [[RDar6320065Subclass alloc] init]; // no-warning
728 - (id)_initReturningNewClassBad {
730 [[RDar6320065Subclass alloc] init]; // expected-warning {{leak}}
733 - (id)initReturningNewClassBad2 {
735 self = [[RDar6320065Subclass alloc] init];
736 return [self autorelease]; // expected-warning{{Object with +0 retain counts returned to caller where a +1 (owning) retain count is expected}}
741 @implementation RDar6320065Subclass
744 int RDar6320065_test() {
745 RDar6320065 *test = [[RDar6320065 alloc] init]; // no-warning
750 //===----------------------------------------------------------------------===//
751 // <rdar://problem/7129086> -awakeAfterUsingCoder: returns an owned object
752 // and claims the receiver
753 //===----------------------------------------------------------------------===//
755 @interface RDar7129086 : NSObject {} @end
756 @implementation RDar7129086
757 - (id)awakeAfterUsingCoder:(NSCoder *)aDecoder {
758 [self release]; // no-warning
759 return [NSString alloc]; // no-warning
763 //===----------------------------------------------------------------------===//
764 // <rdar://problem/6859457> [NSData dataWithBytesNoCopy] does not return a
766 //===----------------------------------------------------------------------===//
768 @interface RDar6859457 : NSObject {}
769 - (NSString*) NoCopyString;
770 - (NSString*) noCopyString;
773 @implementation RDar6859457
774 - (NSString*) NoCopyString { return [[NSString alloc] init]; } // expected-warning{{leak}}
775 - (NSString*) noCopyString { return [[NSString alloc] init]; } // expected-warning{{leak}}
778 void test_RDar6859457(RDar6859457 *x, void *bytes, NSUInteger dataLength) {
779 [x NoCopyString]; // no-warning
780 [x noCopyString]; // no-warning
781 [NSData dataWithBytesNoCopy:bytes length:dataLength]; // no-warning
782 [NSData dataWithBytesNoCopy:bytes length:dataLength freeWhenDone:1]; // no-warning
785 //===----------------------------------------------------------------------===//
786 // PR 4230 - an autorelease pool is not necessarily leaked during a premature
788 //===----------------------------------------------------------------------===//
790 static void PR4230(void)
792 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // no-warning
793 NSString *object = [[[NSString alloc] init] autorelease]; // no-warning
797 //===----------------------------------------------------------------------===//
798 // Method name that has a null IdentifierInfo* for its first selector slot.
799 // This test just makes sure that we handle it.
800 //===----------------------------------------------------------------------===//
802 @interface TestNullIdentifier
805 @implementation TestNullIdentifier
807 return [[NSString alloc] init]; // expected-warning{{leak}}
811 //===----------------------------------------------------------------------===//
812 // <rdar://problem/6893565> don't flag leaks for return types that cannot be
813 // determined to be CF types
814 //===----------------------------------------------------------------------===//
816 // We don't know if 'struct s6893565' represents a Core Foundation type, so
817 // we shouldn't emit an error here.
818 typedef struct s6893565* TD6893565;
820 @interface RDar6893565 {}
821 -(TD6893565)newThing;
824 @implementation RDar6893565
825 -(TD6893565)newThing {
826 return (TD6893565) [[NSString alloc] init]; // no-warning
830 //===----------------------------------------------------------------------===//
831 // <rdar://problem/6902710> clang: false positives w/QC and CoreImage methods
832 //===----------------------------------------------------------------------===//
834 void rdar6902710(QCView *view, QCRenderer *renderer, CIContext *context,
835 NSString *str, CIImage *img, CGRect rect,
836 CIFormat form, CGColorSpaceRef cs) {
837 [view createSnapshotImageOfType:str]; // expected-warning{{leak}}
838 [renderer createSnapshotImageOfType:str]; // expected-warning{{leak}}
839 [context createCGImage:img fromRect:rect]; // expected-warning{{leak}}
840 [context createCGImage:img fromRect:rect format:form colorSpace:cs]; // expected-warning{{leak}}
843 //===----------------------------------------------------------------------===//
844 // <rdar://problem/6945561> -[CIContext createCGLayerWithSize:info:]
845 // misinterpreted by clang scan-build
846 //===----------------------------------------------------------------------===//
848 void rdar6945561(CIContext *context, CGSize size, CFDictionaryRef d) {
849 [context createCGLayerWithSize:size info:d]; // expected-warning{{leak}}
852 //===----------------------------------------------------------------------===//
853 // <rdar://problem/6961230> add knowledge of IOKit functions to retain/release
855 //===----------------------------------------------------------------------===//
857 void IOBSDNameMatching_wrapper(mach_port_t masterPort, uint32_t options, const char * bsdName) {
858 IOBSDNameMatching(masterPort, options, bsdName); // expected-warning{{leak}}
861 void IOServiceMatching_wrapper(const char * name) {
862 IOServiceMatching(name); // expected-warning{{leak}}
865 void IOServiceNameMatching_wrapper(const char * name) {
866 IOServiceNameMatching(name); // expected-warning{{leak}}
869 CF_RETURNS_RETAINED CFDictionaryRef CreateDict();
871 void IOServiceAddNotification_wrapper(mach_port_t masterPort, const io_name_t notificationType,
872 mach_port_t wakePort, uintptr_t reference, io_iterator_t * notification ) {
874 CFDictionaryRef matching = CreateDict();
876 IOServiceAddNotification(masterPort, notificationType, matching, // expected-warning{{used after it is released}} expected-warning{{deprecated}}
877 wakePort, reference, notification);
880 void IORegistryEntryIDMatching_wrapper(uint64_t entryID ) {
881 IORegistryEntryIDMatching(entryID); // expected-warning{{leak}}
884 void IOOpenFirmwarePathMatching_wrapper(mach_port_t masterPort, uint32_t options,
886 IOOpenFirmwarePathMatching(masterPort, options, path); // expected-warning{{leak}}
889 void IOServiceGetMatchingService_wrapper(mach_port_t masterPort) {
890 CFDictionaryRef matching = CreateDict();
891 IOServiceGetMatchingService(masterPort, matching);
892 CFRelease(matching); // expected-warning{{used after it is released}}
895 void IOServiceGetMatchingServices_wrapper(mach_port_t masterPort, io_iterator_t *existing) {
896 CFDictionaryRef matching = CreateDict();
897 IOServiceGetMatchingServices(masterPort, matching, existing);
898 CFRelease(matching); // expected-warning{{used after it is released}}
901 void IOServiceAddMatchingNotification_wrapper(IONotificationPortRef notifyPort, const io_name_t notificationType,
902 IOServiceMatchingCallback callback, void * refCon, io_iterator_t * notification) {
904 CFDictionaryRef matching = CreateDict();
905 IOServiceAddMatchingNotification(notifyPort, notificationType, matching, callback, refCon, notification);
906 CFRelease(matching); // expected-warning{{used after it is released}}
909 //===----------------------------------------------------------------------===//
910 // Test of handling objects whose references "escape" to containers.
911 //===----------------------------------------------------------------------===//
913 void CFDictionaryAddValue();
915 // <rdar://problem/6539791>
916 void rdar_6539791(CFMutableDictionaryRef y, void* key, void* val_key) {
917 CFMutableDictionaryRef x = CFDictionaryCreateMutable(kCFAllocatorDefault, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
918 CFDictionaryAddValue(y, key, x);
919 CFRelease(x); // the dictionary keeps a reference, so the object isn't deallocated yet
921 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z);
923 CFDictionaryAddValue(x, val_key, value); // no-warning
925 CFDictionaryAddValue(y, val_key, value); // no-warning
929 // <rdar://problem/6560661>
930 // Same issue, except with "AppendValue" functions.
931 void rdar_6560661(CFMutableArrayRef x) {
933 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z);
934 // CFArrayAppendValue keeps a reference to value.
935 CFArrayAppendValue(x, value);
938 CFRelease(value); // no-warning
941 // <rdar://problem/7152619>
942 // Same issue, excwept with "CFAttributeStringSetAttribute".
943 void rdar_7152619(CFStringRef str) {
944 CFAttributedStringRef string = CFAttributedStringCreate(kCFAllocatorDefault, str, 0);
945 CFMutableAttributedStringRef attrString = CFAttributedStringCreateMutableCopy(kCFAllocatorDefault, 100, string);
947 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
948 CFAttributedStringSetAttribute(attrString, CFRangeMake(0, 1), str, number);
951 CFRelease(attrString);
954 //===----------------------------------------------------------------------===//
955 // Test of handling CGGradientXXX functions.
956 //===----------------------------------------------------------------------===//
958 void rdar_7184450(CGContextRef myContext, CGFloat x, CGPoint myStartPoint,
959 CGPoint myEndPoint) {
960 size_t num_locations = 6;
961 CGFloat locations[6] = { 0.0, 0.265, 0.28, 0.31, 0.36, 1.0 };
962 CGFloat components[28] = { 239.0/256.0, 167.0/256.0, 170.0/256.0,
964 207.0/255.0, 39.0/255.0, 39.0/255.0, x,
965 147.0/255.0, 21.0/255.0, 22.0/255.0, x,
966 175.0/255.0, 175.0/255.0, 175.0/255.0, x,
967 255.0/255.0,255.0/255.0, 255.0/255.0, x,
968 255.0/255.0,255.0/255.0, 255.0/255.0, x
971 CGGradientRef myGradient =
972 CGGradientCreateWithColorComponents(CGColorSpaceCreateDeviceRGB(), // expected-warning{{leak}}
973 components, locations, num_locations);
975 CGContextDrawLinearGradient(myContext, myGradient, myStartPoint, myEndPoint,
977 CGGradientRelease(myGradient);
980 void rdar_7184450_pos(CGContextRef myContext, CGFloat x, CGPoint myStartPoint,
981 CGPoint myEndPoint) {
982 size_t num_locations = 6;
983 CGFloat locations[6] = { 0.0, 0.265, 0.28, 0.31, 0.36, 1.0 };
984 CGFloat components[28] = { 239.0/256.0, 167.0/256.0, 170.0/256.0,
986 207.0/255.0, 39.0/255.0, 39.0/255.0, x,
987 147.0/255.0, 21.0/255.0, 22.0/255.0, x,
988 175.0/255.0, 175.0/255.0, 175.0/255.0, x,
989 255.0/255.0,255.0/255.0, 255.0/255.0, x,
990 255.0/255.0,255.0/255.0, 255.0/255.0, x
993 CGGradientRef myGradient =
994 CGGradientCreateWithColorComponents(CGColorSpaceCreateDeviceRGB(), components, locations, num_locations); // expected-warning 2 {{leak}}
996 CGContextDrawLinearGradient(myContext, myGradient, myStartPoint, myEndPoint,
1000 //===----------------------------------------------------------------------===//
1001 // <rdar://problem/7299394> clang false positive: retained instance passed to
1002 // thread in pthread_create marked as leak
1004 // Until we have full IPA, the analyzer should stop tracking the reference
1005 // count of objects passed to pthread_create.
1007 //===----------------------------------------------------------------------===//
1009 struct _opaque_pthread_t {};
1010 struct _opaque_pthread_attr_t {};
1011 typedef struct _opaque_pthread_t *__darwin_pthread_t;
1012 typedef struct _opaque_pthread_attr_t __darwin_pthread_attr_t;
1013 typedef __darwin_pthread_t pthread_t;
1014 typedef __darwin_pthread_attr_t pthread_attr_t;
1016 int pthread_create(pthread_t * restrict, const pthread_attr_t * restrict,
1017 void *(*)(void *), void * restrict);
1019 void *rdar_7299394_start_routine(void *p) {
1023 void rdar_7299394(pthread_attr_t *attr, pthread_t *thread, void *args) {
1024 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1025 pthread_create(thread, attr, rdar_7299394_start_routine, number);
1027 void rdar_7299394_positive(pthread_attr_t *attr, pthread_t *thread) {
1028 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1031 //===----------------------------------------------------------------------===//
1032 // <rdar://problem/7283567> False leak associated with call to
1033 // CVPixelBufferCreateWithBytes ()
1035 // According to the Core Video Reference (ADC), CVPixelBufferCreateWithBytes and
1036 // CVPixelBufferCreateWithPlanarBytes can release (via a callback) the
1037 // pixel buffer object. These test cases show how the analyzer stops tracking
1038 // the reference count for the objects passed for this argument. This
1039 // could be made smarter.
1040 //===----------------------------------------------------------------------===//
1042 typedef int int32_t;
1043 typedef UInt32 FourCharCode;
1044 typedef FourCharCode OSType;
1045 typedef uint64_t CVOptionFlags;
1046 typedef int32_t CVReturn;
1047 typedef struct __CVBuffer *CVBufferRef;
1048 typedef CVBufferRef CVImageBufferRef;
1049 typedef CVImageBufferRef CVPixelBufferRef;
1050 typedef void (*CVPixelBufferReleaseBytesCallback)( void *releaseRefCon, const void *baseAddress );
1052 extern CVReturn CVPixelBufferCreateWithBytes(CFAllocatorRef allocator,
1055 OSType pixelFormatType,
1058 CVPixelBufferReleaseBytesCallback releaseCallback,
1059 void *releaseRefCon,
1060 CFDictionaryRef pixelBufferAttributes,
1061 CVPixelBufferRef *pixelBufferOut) ;
1063 typedef void (*CVPixelBufferReleasePlanarBytesCallback)( void *releaseRefCon, const void *dataPtr, size_t dataSize, size_t numberOfPlanes, const void *planeAddresses[] );
1065 extern CVReturn CVPixelBufferCreateWithPlanarBytes(CFAllocatorRef allocator,
1068 OSType pixelFormatType,
1071 size_t numberOfPlanes,
1072 void *planeBaseAddress[],
1073 size_t planeWidth[],
1074 size_t planeHeight[],
1075 size_t planeBytesPerRow[],
1076 CVPixelBufferReleasePlanarBytesCallback releaseCallback,
1077 void *releaseRefCon,
1078 CFDictionaryRef pixelBufferAttributes,
1079 CVPixelBufferRef *pixelBufferOut) ;
1081 extern CVReturn CVPixelBufferCreateWithBytes(CFAllocatorRef allocator,
1084 OSType pixelFormatType,
1087 CVPixelBufferReleaseBytesCallback releaseCallback,
1088 void *releaseRefCon,
1089 CFDictionaryRef pixelBufferAttributes,
1090 CVPixelBufferRef *pixelBufferOut) ;
1092 CVReturn rdar_7283567(CFAllocatorRef allocator, size_t width, size_t height,
1093 OSType pixelFormatType, void *baseAddress,
1095 CVPixelBufferReleaseBytesCallback releaseCallback,
1096 CFDictionaryRef pixelBufferAttributes,
1097 CVPixelBufferRef *pixelBufferOut) {
1099 // For the allocated object, it doesn't really matter what type it is
1100 // for the purpose of this test. All we want to show is that
1101 // this is freed later by the callback.
1102 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1104 return CVPixelBufferCreateWithBytes(allocator, width, height, pixelFormatType,
1105 baseAddress, bytesPerRow, releaseCallback,
1106 number, // potentially released by callback
1107 pixelBufferAttributes, pixelBufferOut) ;
1110 CVReturn rdar_7283567_2(CFAllocatorRef allocator, size_t width, size_t height,
1111 OSType pixelFormatType, void *dataPtr, size_t dataSize,
1112 size_t numberOfPlanes, void *planeBaseAddress[],
1113 size_t planeWidth[], size_t planeHeight[], size_t planeBytesPerRow[],
1114 CVPixelBufferReleasePlanarBytesCallback releaseCallback,
1115 CFDictionaryRef pixelBufferAttributes,
1116 CVPixelBufferRef *pixelBufferOut) {
1118 // For the allocated object, it doesn't really matter what type it is
1119 // for the purpose of this test. All we want to show is that
1120 // this is freed later by the callback.
1121 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1123 return CVPixelBufferCreateWithPlanarBytes(allocator,
1124 width, height, pixelFormatType, dataPtr, dataSize,
1125 numberOfPlanes, planeBaseAddress, planeWidth,
1126 planeHeight, planeBytesPerRow, releaseCallback,
1127 number, // potentially released by callback
1128 pixelBufferAttributes, pixelBufferOut) ;
1131 //===----------------------------------------------------------------------===//
1132 // <rdar://problem/7358899> False leak associated with
1133 // CGBitmapContextCreateWithData
1134 //===----------------------------------------------------------------------===//
1135 typedef uint32_t CGBitmapInfo;
1136 typedef void (*CGBitmapContextReleaseDataCallback)(void *releaseInfo, void *data);
1138 CGContextRef CGBitmapContextCreateWithData(void *data,
1139 size_t width, size_t height, size_t bitsPerComponent,
1140 size_t bytesPerRow, CGColorSpaceRef space, CGBitmapInfo bitmapInfo,
1141 CGBitmapContextReleaseDataCallback releaseCallback, void *releaseInfo);
1143 void rdar_7358899(void *data,
1144 size_t width, size_t height, size_t bitsPerComponent,
1145 size_t bytesPerRow, CGColorSpaceRef space, CGBitmapInfo bitmapInfo,
1146 CGBitmapContextReleaseDataCallback releaseCallback) {
1148 // For the allocated object, it doesn't really matter what type it is
1149 // for the purpose of this test. All we want to show is that
1150 // this is freed later by the callback.
1151 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1153 CGBitmapContextCreateWithData(data, width, height, bitsPerComponent, // expected-warning{{leak}}
1154 bytesPerRow, space, bitmapInfo, releaseCallback, number);
1157 //===----------------------------------------------------------------------===//
1158 // <rdar://problem/7265711> allow 'new', 'copy', 'alloc', 'init' prefix to
1159 // start before '_' when determining Cocoa fundamental rule
1161 // Previously the retain/release checker just skipped prefixes before the
1162 // first '_' entirely. Now the checker honors the prefix if it results in a
1163 // recognizable naming convention (e.g., 'new', 'init').
1164 //===----------------------------------------------------------------------===//
1166 @interface RDar7265711 {}
1170 void rdar7265711_a(RDar7265711 *x) {
1171 id y = [x new_stuff]; // expected-warning{{leak}}
1174 void rdar7265711_b(RDar7265711 *x) {
1175 id y = [x new_stuff]; // no-warning
1179 //===----------------------------------------------------------------------===//
1180 // <rdar://problem/7306898> clang thinks [NSCursor dragCopyCursor] returns a
1181 // retained reference
1182 //===----------------------------------------------------------------------===//
1184 @interface NSCursor : NSObject
1185 + (NSCursor *)dragCopyCursor;
1188 void rdar7306898(void) {
1189 // 'dragCopyCursor' does not follow Cocoa's fundamental rule. It is a noun, not an sentence
1190 // implying a 'copy' of something.
1191 NSCursor *c = [NSCursor dragCopyCursor]; // no-warning
1192 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1195 //===----------------------------------------------------------------------===//
1196 // <rdar://problem/7252064> sending 'release', 'retain', etc. to a Class
1197 // directly is not likely what the user intended
1198 //===----------------------------------------------------------------------===//
1200 @interface RDar7252064 : NSObject @end
1201 void rdar7252064(void) {
1202 [RDar7252064 release]; // expected-warning{{The 'release' message should be sent to instances of class 'RDar7252064' and not the class directly}}
1203 [RDar7252064 retain]; // expected-warning{{The 'retain' message should be sent to instances of class 'RDar7252064' and not the class directly}}
1204 [RDar7252064 autorelease]; // expected-warning{{The 'autorelease' message should be sent to instances of class 'RDar7252064' and not the class directly}}
1205 [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}}
1208 //===----------------------------------------------------------------------===//
1209 // Tests of ownership attributes.
1210 //===----------------------------------------------------------------------===//
1212 typedef NSString* MyStringTy;
1216 @interface TestOwnershipAttr : NSObject
1217 - (NSString*) returnsAnOwnedString NS_RETURNS_RETAINED; // no-warning
1218 - (NSString*) returnsAnOwnedCFString CF_RETURNS_RETAINED; // no-warning
1219 - (MyStringTy) returnsAnOwnedTypedString NS_RETURNS_RETAINED; // no-warning
1220 - (NSString*) newString NS_RETURNS_NOT_RETAINED; // no-warning
1221 - (NSString*) newStringNoAttr;
1222 - (int) returnsAnOwnedInt NS_RETURNS_RETAINED; // expected-warning{{'ns_returns_retained' attribute only applies to methods that return an Objective-C object}}
1223 - (id) pseudoInit NS_CONSUMES_SELF NS_RETURNS_RETAINED;
1224 + (void) consume:(id) NS_CONSUMED x;
1225 + (void) consume2:(id) CF_CONSUMED x;
1228 static int ownership_attribute_doesnt_go_here NS_RETURNS_RETAINED; // expected-warning{{'ns_returns_retained' attribute only applies to functions and methods}}
1230 void test_attr_1(TestOwnershipAttr *X) {
1231 NSString *str = [X returnsAnOwnedString]; // expected-warning{{leak}}
1234 void test_attr_1b(TestOwnershipAttr *X) {
1235 NSString *str = [X returnsAnOwnedCFString]; // expected-warning{{leak}}
1238 void test_attr1c(TestOwnershipAttr *X) {
1239 NSString *str = [X newString]; // no-warning
1240 NSString *str2 = [X newStringNoAttr]; // expected-warning{{leak}}
1243 void testattr2_a() {
1244 TestOwnershipAttr *x = [TestOwnershipAttr alloc]; // expected-warning{{leak}}
1247 void testattr2_b() {
1248 TestOwnershipAttr *x = [[TestOwnershipAttr alloc] pseudoInit]; // expected-warning{{leak}}
1251 void testattr2_c() {
1252 TestOwnershipAttr *x = [[TestOwnershipAttr alloc] pseudoInit]; // no-warning
1257 TestOwnershipAttr *x = [TestOwnershipAttr alloc]; // no-warning
1258 [TestOwnershipAttr consume:x];
1259 TestOwnershipAttr *y = [TestOwnershipAttr alloc]; // no-warning
1260 [TestOwnershipAttr consume2:y];
1263 void consume_ns(id NS_CONSUMED x);
1264 void consume_cf(id CF_CONSUMED x);
1267 TestOwnershipAttr *x = [TestOwnershipAttr alloc]; // no-warning
1269 TestOwnershipAttr *y = [TestOwnershipAttr alloc]; // no-warning
1274 @interface MyClassTestCFAttr : NSObject {}
1275 - (NSDate*) returnsCFRetained CF_RETURNS_RETAINED;
1276 - (CFDateRef) returnsCFRetainedAsCF CF_RETURNS_RETAINED;
1277 - (CFDateRef) newCFRetainedAsCF CF_RETURNS_NOT_RETAINED;
1278 - (CFDateRef) newCFRetainedAsCFNoAttr;
1279 - (NSDate*) alsoReturnsRetained;
1280 - (CFDateRef) alsoReturnsRetainedAsCF;
1281 - (NSDate*) returnsNSRetained NS_RETURNS_RETAINED;
1285 CFDateRef returnsRetainedCFDate() {
1286 return CFDateCreate(0, CFAbsoluteTimeGetCurrent());
1289 @implementation MyClassTestCFAttr
1290 - (NSDate*) returnsCFRetained {
1291 return (NSDate*) returnsRetainedCFDate(); // No leak.
1294 - (CFDateRef) returnsCFRetainedAsCF {
1295 return returnsRetainedCFDate(); // No leak.
1298 - (CFDateRef) newCFRetainedAsCF {
1299 return (CFDateRef)[(id)[self returnsCFRetainedAsCF] autorelease];
1302 - (CFDateRef) newCFRetainedAsCFNoAttr {
1303 return (CFDateRef)[(id)[self returnsCFRetainedAsCF] autorelease]; // expected-warning{{Object with +0 retain counts returned to caller where a +1 (owning) retain count is expected}}
1306 - (NSDate*) alsoReturnsRetained {
1307 return (NSDate*) returnsRetainedCFDate(); // expected-warning{{leak}}
1310 - (CFDateRef) alsoReturnsRetainedAsCF {
1311 return returnsRetainedCFDate(); // expected-warning{{leak}}
1315 - (NSDate*) returnsNSRetained {
1316 return (NSDate*) returnsRetainedCFDate(); // no-warning
1320 //===----------------------------------------------------------------------===//
1321 // Test that leaks post-dominated by "panic" functions are not reported.
1323 // <rdar://problem/5905851> do not report a leak when post-dominated by a call
1324 // to a noreturn or panic function
1325 //===----------------------------------------------------------------------===//
1327 void panic() __attribute__((noreturn));
1328 void panic_not_in_hardcoded_list() __attribute__((noreturn));
1330 void test_panic_negative() {
1332 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // expected-warning{{leak}}
1335 void test_panic_positive() {
1337 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // no-warning
1341 void test_panic_neg_2(int x) {
1343 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // expected-warning{{leak}}
1348 void test_panic_pos_2(int x) {
1350 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // no-warning
1354 // This showed up in <rdar://problem/7796563>, where we silently missed checking
1355 // the function type for noreturn. "panic()" is a hard-coded known panic function
1356 // that isn't always noreturn.
1357 panic_not_in_hardcoded_list();
1361 //===----------------------------------------------------------------------===//
1362 // Test uses of blocks (closures)
1363 //===----------------------------------------------------------------------===//
1365 void test_blocks_1_pos(void) {
1366 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // expected-warning{{leak}}
1370 void test_blocks_1_indirect_release(void) {
1371 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1372 ^{ [number release]; }();
1375 void test_blocks_1_indirect_retain(void) {
1376 // Eventually this should be reported as a leak.
1377 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1378 ^{ [number retain]; }();
1381 void test_blocks_1_indirect_release_via_call(void) {
1382 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1383 ^(NSObject *o){ [o release]; }(number);
1386 void test_blocks_1_indirect_retain_via_call(void) {
1387 // Eventually this should be reported as a leak.
1388 NSNumber *number = [[NSNumber alloc] initWithInt:5]; // no-warning
1389 ^(NSObject *o){ [o retain]; }(number);
1392 //===--------------------------------------------------------------------===//
1393 // Test sending message to super that returns an object alias. Previously
1394 // this caused a crash in the analyzer.
1395 //===--------------------------------------------------------------------===//
1397 @interface Rdar8015556 : NSObject {} @end
1398 @implementation Rdar8015556
1400 return [super retain];
1404 // <rdar://problem/8272168> - Correcly handle Class<...> in Cocoa Conventions
1407 @protocol Prot_R8272168 @end
1408 Class <Prot_R8272168> GetAClassThatImplementsProt_R8272168();
1410 GetAClassThatImplementsProt_R8272168();
1413 // Test case for <rdar://problem/8356342>, which in the past triggered
1414 // a false positive.
1415 @interface RDar8356342
1416 - (NSDate*) rdar8356342:(NSDate *)inValue;
1419 @implementation RDar8356342
1420 - (NSDate*) rdar8356342:(NSDate*)inValue {
1421 NSDate *outValue = inValue;
1423 outValue = [[NSDate alloc] init]; // no-warning
1425 if (outValue != inValue)
1426 [outValue autorelease];
1432 // <rdar://problem/8724287> - This test case previously crashed because
1433 // of a bug in BugReporter.
1434 extern const void *CFDictionaryGetValue(CFDictionaryRef theDict, const void *key);
1435 typedef struct __CFError * CFErrorRef;
1436 extern const CFStringRef kCFErrorUnderlyingErrorKey;
1437 extern CFDictionaryRef CFErrorCopyUserInfo(CFErrorRef err);
1439 static void rdar_8724287(CFErrorRef error)
1441 CFErrorRef error_to_dump;
1443 error_to_dump = error;
1444 while (error_to_dump != ((void*)0)) {
1445 CFDictionaryRef info;
1447 info = CFErrorCopyUserInfo(error_to_dump); // expected-warning{{Potential leak of an object allocated on line 1447 and stored into 'info'}}
1449 if (info != ((void*)0)) {
1452 error_to_dump = (CFErrorRef) CFDictionaryGetValue(info, kCFErrorUnderlyingErrorKey);