retain-release.m revision b9d8db86ab1d9c95c09083d8e9792414ae9fcd6d
1//>>SLICER
2// RUN: clang-cc -analyze -checker-cfref -verify %s &&
3// RUN: clang-cc -analyze -checker-cfref -analyzer-store=region -verify %s
4
5//===----------------------------------------------------------------------===//
6// The following code is reduced using delta-debugging from Mac OS X headers:
7//
8// #include <Cocoa/Cocoa.h>
9// #include <CoreFoundation/CoreFoundation.h>
10// #include <DiskArbitration/DiskArbitration.h>
11// #include <QuartzCore/QuartzCore.h>
12// #include <Quartz/Quartz.h>
13//
14// It includes the basic definitions for the test cases below.
15//===----------------------------------------------------------------------===//
16
17typedef unsigned int __darwin_natural_t;
18typedef unsigned int UInt32;
19typedef signed long CFIndex;
20typedef const void * CFTypeRef;
21typedef const struct __CFString * CFStringRef;
22typedef const struct __CFAllocator * CFAllocatorRef;
23extern CFTypeRef CFRetain(CFTypeRef cf);
24extern void CFRelease(CFTypeRef cf);
25extern const CFAllocatorRef kCFAllocatorDefault;
26typedef struct {
27}
28CFArrayCallBacks;
29extern const CFArrayCallBacks kCFTypeArrayCallBacks;
30typedef const struct __CFArray * CFArrayRef;
31typedef struct __CFArray * CFMutableArrayRef;
32extern CFMutableArrayRef CFArrayCreateMutable(CFAllocatorRef allocator, CFIndex capacity, const CFArrayCallBacks *callBacks);
33extern const void *CFArrayGetValueAtIndex(CFArrayRef theArray, CFIndex idx);
34extern void CFArrayAppendValue(CFMutableArrayRef theArray, const void *value);
35typedef const struct __CFDictionary * CFDictionaryRef;
36typedef UInt32 CFStringEncoding;
37enum {
38kCFStringEncodingMacRoman = 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  };
39extern CFStringRef CFStringCreateWithCString(CFAllocatorRef alloc, const char *cStr, CFStringEncoding encoding);
40typedef double CFTimeInterval;
41typedef CFTimeInterval CFAbsoluteTime;
42extern CFAbsoluteTime CFAbsoluteTimeGetCurrent(void);
43typedef const struct __CFDate * CFDateRef;
44extern CFDateRef CFDateCreate(CFAllocatorRef allocator, CFAbsoluteTime at);
45CFAbsoluteTime CFDateGetAbsoluteTime(CFDateRef theDate);
46enum {
47kCFCalendarComponentsWrap = (1UL << 0) };
48typedef __darwin_natural_t natural_t;
49typedef natural_t mach_port_name_t;
50typedef mach_port_name_t mach_port_t;
51typedef int kern_return_t;
52typedef kern_return_t mach_error_t;
53typedef signed char BOOL;
54typedef unsigned long NSUInteger;
55typedef struct _NSZone NSZone;
56@class NSInvocation, NSMethodSignature, NSCoder, NSString, NSEnumerator;
57@protocol NSObject  - (BOOL)isEqual:(id)object;
58- (id)retain;
59- (oneway void)release;
60- (id)autorelease;
61@end  @protocol NSCopying  - (id)copyWithZone:(NSZone *)zone;
62@end  @protocol NSMutableCopying  - (id)mutableCopyWithZone:(NSZone *)zone;
63@end  @protocol NSCoding  - (void)encodeWithCoder:(NSCoder *)aCoder;
64@end    @interface NSObject <NSObject> {
65}
66+ (id)allocWithZone:(NSZone *)zone;
67+ (id)alloc;
68- (void)dealloc;
69@end      extern id NSAllocateObject(Class aClass, NSUInteger extraBytes, NSZone *zone);
70typedef struct {
71}
72NSFastEnumerationState;
73@protocol NSFastEnumeration  - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len;
74@end      @interface NSArray : NSObject <NSCopying, NSMutableCopying, NSCoding, NSFastEnumeration>  - (NSUInteger)count;
75@end  @interface NSArray (NSArrayCreation)  + (id)array;
76@end        @interface NSAutoreleasePool : NSObject {
77}
78- (void)drain;
79@end    typedef double NSTimeInterval;
80@interface NSDate : NSObject <NSCopying, NSCoding>  - (NSTimeInterval)timeIntervalSinceReferenceDate;
81@end  enum {
82NSWrapCalendarComponents = kCFCalendarComponentsWrap, };
83@interface NSString : NSObject <NSCopying, NSMutableCopying, NSCoding>    - (NSUInteger)length;
84- ( const char *)UTF8String;
85- (id)initWithUTF8String:(const char *)nullTerminatedCString;
86+ (id)stringWithUTF8String:(const char *)nullTerminatedCString;
87@end      @interface NSData : NSObject <NSCopying, NSMutableCopying, NSCoding>  - (NSUInteger)length;
88+ (id)dataWithBytesNoCopy:(void *)bytes length:(NSUInteger)length;
89+ (id)dataWithBytesNoCopy:(void *)bytes length:(NSUInteger)length freeWhenDone:(BOOL)b;
90@end      @interface NSDictionary : NSObject <NSCopying, NSMutableCopying, NSCoding, NSFastEnumeration>  - (NSUInteger)count;
91@end    @interface NSMutableDictionary : NSDictionary  - (void)removeObjectForKey:(id)aKey;
92- (void)setObject:(id)anObject forKey:(id)aKey;
93@end  @interface NSMutableDictionary (NSMutableDictionaryCreation)  + (id)dictionaryWithCapacity:(NSUInteger)numItems;
94struct CGRect {
95};
96typedef struct CGRect CGRect;
97- (id)init;
98typedef mach_port_t io_object_t;
99typedef io_object_t io_service_t;
100typedef struct __DASession * DASessionRef;
101extern DASessionRef DASessionCreate( CFAllocatorRef allocator );
102typedef struct __DADisk * DADiskRef;
103extern DADiskRef DADiskCreateFromBSDName( CFAllocatorRef allocator, DASessionRef session, const char * name );
104extern DADiskRef DADiskCreateFromIOMedia( CFAllocatorRef allocator, DASessionRef session, io_service_t media );
105extern CFDictionaryRef DADiskCopyDescription( DADiskRef disk );
106extern DADiskRef DADiskCopyWholeDisk( DADiskRef disk );
107typedef struct CGColorSpace *CGColorSpaceRef;
108typedef struct CGImage *CGImageRef;
109@end   @class CIContext;
110@class NSArray, NSError, NSEvent, NSMenu, NSUndoManager, NSWindow;
111@interface NSResponder : NSObject <NSCoding> {
112}
113@end    @protocol NSAnimatablePropertyContainer      - (id)animator;
114@end  extern NSString *NSAnimationTriggerOrderIn ;
115@interface NSView : NSResponder  <NSAnimatablePropertyContainer>  {
116}
117@end   @class NSColor, NSFont, NSNotification;
118@protocol NSValidatedUserInterfaceItem - (SEL)action;
119@end   @protocol NSUserInterfaceValidations - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)anItem;
120@end    typedef struct NSThreadPrivate _NSThreadPrivate;
121@interface NSApplication : NSResponder <NSUserInterfaceValidations> {
122}
123@end   enum {
124NSTerminateCancel = 0,         NSTerminateNow = 1,         NSTerminateLater = 2 };
125typedef NSUInteger NSApplicationTerminateReply;
126@protocol NSApplicationDelegate <NSObject> @optional        - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender;
127@end    enum {
128NSUserInterfaceLayoutDirectionLeftToRight = 0,     NSUserInterfaceLayoutDirectionRightToLeft = 1 };
129@interface CIImage : NSObject <NSCoding, NSCopying> {
130}
131typedef int CIFormat;
132typedef struct __SFlags {
133}
134_SFlags;
135@end    extern NSString * const kCAGravityCenter     __attribute__((visibility("default")));
136enum {
137kDAReturnSuccess = 0,     kDAReturnError = (((0x3e)&0x3f)<<26) | (((0x368)&0xfff)<<14) | 0x01,     kDAReturnBusy = (((0x3e)&0x3f)<<26) | (((0x368)&0xfff)<<14) | 0x02,     kDAReturnBadArgument = (((0x3e)&0x3f)<<26) | (((0x368)&0xfff)<<14) | 0x03,     kDAReturnExclusiveAccess = (((0x3e)&0x3f)<<26) | (((0x368)&0xfff)<<14) | 0x04,     kDAReturnNoResources = (((0x3e)&0x3f)<<26) | (((0x368)&0xfff)<<14) | 0x05,     kDAReturnNotFound = (((0x3e)&0x3f)<<26) | (((0x368)&0xfff)<<14) | 0x06,     kDAReturnNotMounted = (((0x3e)&0x3f)<<26) | (((0x368)&0xfff)<<14) | 0x07,     kDAReturnNotPermitted = (((0x3e)&0x3f)<<26) | (((0x368)&0xfff)<<14) | 0x08,     kDAReturnNotPrivileged = (((0x3e)&0x3f)<<26) | (((0x368)&0xfff)<<14) | 0x09,     kDAReturnNotReady = (((0x3e)&0x3f)<<26) | (((0x368)&0xfff)<<14) | 0x0A,     kDAReturnNotWritable = (((0x3e)&0x3f)<<26) | (((0x368)&0xfff)<<14) | 0x0B,     kDAReturnUnsupported = (((0x3e)&0x3f)<<26) | (((0x368)&0xfff)<<14) | 0x0C };
138typedef mach_error_t DAReturn;
139typedef const struct __DADissenter * DADissenterRef;
140extern DADissenterRef DADissenterCreate( CFAllocatorRef allocator, DAReturn status, CFStringRef string );
141@interface CIContext: NSObject {
142}
143- (CGImageRef)createCGImage:(CIImage *)im fromRect:(CGRect)r;
144- (CGImageRef)createCGImage:(CIImage *)im fromRect:(CGRect)r     format:(CIFormat)f colorSpace:(CGColorSpaceRef)cs;
145@end     @protocol QCCompositionRenderer      @end   @interface QCRenderer : NSObject <QCCompositionRenderer> {
146}
147- (id) createSnapshotImageOfType:(NSString*)type;
148@end     @interface QCView : NSView <QCCompositionRenderer> {
149}
150- (id) createSnapshotImageOfType:(NSString*)type;
151@end
152extern void NSLog(NSString *format, ...) __attribute__((format(__NSString__, 1, 2)));
153
154//===----------------------------------------------------------------------===//
155// Test cases.
156//===----------------------------------------------------------------------===//
157
158CFAbsoluteTime f1() {
159  CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
160  CFDateRef date = CFDateCreate(0, t);
161  CFRetain(date);
162  CFRelease(date);
163  CFDateGetAbsoluteTime(date); // no-warning
164  CFRelease(date);
165  t = CFDateGetAbsoluteTime(date);   // expected-warning{{Reference-counted object is used after it is released.}}
166  return t;
167}
168
169CFAbsoluteTime f2() {
170  CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
171  CFDateRef date = CFDateCreate(0, t);  
172  [((NSDate*) date) retain];
173  CFRelease(date);
174  CFDateGetAbsoluteTime(date); // no-warning
175  [((NSDate*) date) release];
176  t = CFDateGetAbsoluteTime(date);   // expected-warning{{Reference-counted object is used after it is released.}}
177  return t;
178}
179
180
181NSDate* global_x;
182
183// Test to see if we supresss an error when we store the pointer
184// to a global.
185
186CFAbsoluteTime f3() {
187  CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
188  CFDateRef date = CFDateCreate(0, t);  
189  [((NSDate*) date) retain];
190  CFRelease(date);
191  CFDateGetAbsoluteTime(date); // no-warning
192  global_x = (NSDate*) date;  
193  [((NSDate*) date) release];
194  t = CFDateGetAbsoluteTime(date);   // no-warning
195  return t;
196}
197
198//---------------------------------------------------------------------------
199// Test case 'f4' differs for region store and basic store.  See
200// retain-release-region-store.m and retain-release-basic-store.m.
201//---------------------------------------------------------------------------
202
203// Test a leak.
204
205CFAbsoluteTime f5(int x) {  
206  CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
207  CFDateRef date = CFDateCreate(0, t); // expected-warning{{leak}}
208  
209  if (x)
210    CFRelease(date);
211  
212  return t;
213}
214
215// Test a leak involving the return.
216
217CFDateRef f6(int x) {  
218  CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent());  // expected-warning{{leak}}
219  CFRetain(date);
220  return date;
221}
222
223// Test a leak involving an overwrite.
224
225CFDateRef f7() {
226  CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent());  //expected-warning{{leak}}
227  CFRetain(date);
228  date = CFDateCreate(0, CFAbsoluteTimeGetCurrent());
229  return date;
230}
231
232// Generalization of Create rule.  MyDateCreate returns a CFXXXTypeRef, and
233// has the word create.
234CFDateRef MyDateCreate();
235
236CFDateRef f8() {
237  CFDateRef date = MyDateCreate(); // expected-warning{{leak}}
238  CFRetain(date);  
239  return date;
240}
241
242CFDateRef f9() {
243  CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent());
244  int *p = 0;
245  // When allocations fail, CFDateCreate can return null.
246  if (!date) *p = 1; // expected-warning{{null}}
247  return date;
248}
249
250// Handle DiskArbitration API:
251//
252// http://developer.apple.com/DOCUMENTATION/DARWIN/Reference/DiscArbitrationFramework/
253//
254void f10(io_service_t media, DADiskRef d, CFStringRef s) {
255  DADiskRef disk = DADiskCreateFromBSDName(kCFAllocatorDefault, 0, "hello"); // expected-warning{{leak}}
256  if (disk) NSLog(@"ok");
257  
258  disk = DADiskCreateFromIOMedia(kCFAllocatorDefault, 0, media); // expected-warning{{leak}}
259  if (disk) NSLog(@"ok");
260
261  CFDictionaryRef dict = DADiskCopyDescription(d);  // expected-warning{{leak}}
262  if (dict) NSLog(@"ok"); 
263  
264  disk = DADiskCopyWholeDisk(d); // expected-warning{{leak}}
265  if (disk) NSLog(@"ok");
266    
267  DADissenterRef dissenter = DADissenterCreate(kCFAllocatorDefault,   // expected-warning{{leak}}
268                                                kDAReturnSuccess, s);
269  if (dissenter) NSLog(@"ok");
270  
271  DASessionRef session = DASessionCreate(kCFAllocatorDefault);  // expected-warning{{leak}}
272  if (session) NSLog(@"ok");
273}
274
275// Test retain/release checker with CFString and CFMutableArray.
276void f11() {
277  // Create the array.
278  CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
279
280  // Create a string.
281  CFStringRef s1 = CFStringCreateWithCString(0, "hello world",
282                                             kCFStringEncodingUTF8);
283
284  // Add the string to the array.
285  CFArrayAppendValue(A, s1);
286  
287  // Decrement the reference count.
288  CFRelease(s1); // no-warning
289  
290  // Get the string.  We don't own it.
291  s1 = (CFStringRef) CFArrayGetValueAtIndex(A, 0);
292  
293  // Release the array.
294  CFRelease(A); // no-warning
295  
296  // Release the string.  This is a bug.
297  CFRelease(s1); // expected-warning{{Incorrect decrement of the reference count}}
298}
299
300// PR 3337: Handle functions declared using typedefs.
301typedef CFTypeRef CREATEFUN();
302CREATEFUN MyCreateFun;
303
304void f12() {
305  CFTypeRef o = MyCreateFun(); // expected-warning {{leak}}
306}
307
308void f13_autorelease() {
309  CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
310  [(id) A autorelease]; // no-warning
311}
312
313void f13_autorelease_b() {
314  CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
315  [(id) A autorelease];
316  [(id) A autorelease]; // expected-warning{{Object sent -autorelease too many times}}
317}
318
319CFMutableArrayRef f13_autorelease_c() {
320  CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
321  [(id) A autorelease];
322  [(id) A autorelease]; 
323  return A; // expected-warning{{Object sent -autorelease too many times}}
324}
325
326CFMutableArrayRef f13_autorelease_d() {
327  CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
328  [(id) A autorelease];
329  [(id) A autorelease]; 
330  CFMutableArrayRef B = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning{{Object sent -autorelease too many times}}
331  CFRelease(B); // no-warning
332}
333
334
335// This case exercises the logic where the leak site is the same as the allocation site.
336void f14_leakimmediately() {
337  CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning{{leak}}
338}
339
340// Test that we track an allocated object beyond the point where the *name*
341// of the variable storing the reference is no longer live.
342void f15() {
343  // Create the array.
344  CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
345  CFMutableArrayRef *B = &A;
346  // At this point, the name 'A' is no longer live.
347  CFRelease(*B);  // no-warning
348}
349
350
351// Test basic tracking of ivars associated with 'self'.  For the retain/release
352// checker we currently do not want to flag leaks associated with stores
353// of tracked objects to ivars.
354@interface SelfIvarTest : NSObject {
355  id myObj;
356}
357- (void)test_self_tracking;
358@end
359
360@implementation SelfIvarTest
361- (void)test_self_tracking {
362  myObj = (id) CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
363}
364@end
365
366// Test return of non-owned objects in contexts where an owned object
367// is expected.
368@interface TestReturnNotOwnedWhenExpectedOwned
369- (NSString*)newString;
370@end
371
372@implementation TestReturnNotOwnedWhenExpectedOwned
373- (NSString*)newString {
374  NSString *s = [NSString stringWithUTF8String:"hello"];
375  return s; // expected-warning{{Object with +0 retain counts returned to caller where a +1 (owning) retain count is expected}}
376}
377@end
378
379// <rdar://problem/6659160>
380int isFoo(char c);
381
382static void rdar_6659160(char *inkind, char *inname)
383{
384  // We currently expect that [NSObject alloc] cannot fail.  This
385  // will be a toggled flag in the future.  It can indeed return null, but
386  // Cocoa programmers generally aren't expected to reason about out-of-memory
387  // conditions.
388  NSString *kind = [[NSString alloc] initWithUTF8String:inkind];  // expected-warning{{leak}}
389  
390  // We do allow stringWithUTF8String to fail.  This isn't really correct, as
391  // far as returning 0.  In most error conditions it will throw an exception.
392  // If allocation fails it could return 0, but again this
393  // isn't expected.
394  NSString *name = [NSString stringWithUTF8String:inname];
395  if(!name)
396    return;
397
398  const char *kindC = 0;
399  const char *nameC = 0;
400  
401  // In both cases, we cannot reach a point down below where we
402  // dereference kindC or nameC with either being null.  This is because
403  // we assume that [NSObject alloc] doesn't fail and that we have the guard
404  // up above.
405  
406  if(kind)
407    kindC = [kind UTF8String];
408  if(name)
409    nameC = [name UTF8String];
410  if(!isFoo(kindC[0])) // expected-warning{{null}}
411    return;
412  if(!isFoo(nameC[0])) // no-warning
413    return;
414
415  [kind release];
416  [name release]; // expected-warning{{Incorrect decrement of the reference count}}
417}
418
419// PR 3677 - 'allocWithZone' should be treated as following the Cocoa naming
420//  conventions with respect to 'return'ing ownership.
421@interface PR3677: NSObject @end
422@implementation PR3677
423+ (id)allocWithZone:(NSZone *)inZone {
424  return [super allocWithZone:inZone];  // no-warning
425}
426@end
427
428// PR 3820 - Reason about calls to -dealloc
429void pr3820_DeallocInsteadOfRelease(void)
430{
431  id foo = [[NSString alloc] init]; // no-warning
432  [foo dealloc];
433  // foo is not leaked, since it has been deallocated.
434}
435
436void pr3820_ReleaseAfterDealloc(void)
437{
438  id foo = [[NSString alloc] init];
439  [foo dealloc];
440  [foo release];  // expected-warning{{used after it is release}}
441  // NSInternalInconsistencyException: message sent to deallocated object
442}
443
444void pr3820_DeallocAfterRelease(void)
445{
446  NSLog(@"\n\n[%s]", __FUNCTION__);
447  id foo = [[NSString alloc] init];
448  [foo release];
449  [foo dealloc]; // expected-warning{{used after it is released}}
450  // message sent to released object
451}
452
453// From <rdar://problem/6704930>.  The problem here is that 'length' binds to
454// '($0 - 1)' after '--length', but SimpleConstraintManager doesn't know how to
455// reason about '($0 - 1) > constant'.  As a temporary hack, we drop the value
456// of '($0 - 1)' and conjure a new symbol.
457void rdar6704930(unsigned char *s, unsigned int length) {
458  NSString* name = 0;
459  if (s != 0) {
460    if (length > 0) {
461      while (length > 0) {
462        if (*s == ':') {
463          ++s;
464          --length;
465          name = [[NSString alloc] init]; // no-warning
466          break;
467        }
468        ++s;
469        --length;
470      }
471      if ((length == 0) && (name != 0)) {
472        [name release];
473        name = 0;
474      }
475      if (length == 0) { // no ':' found -> use it all as name
476        name = [[NSString alloc] init]; // no-warning
477      }
478    }
479  }
480
481  if (name != 0) {
482    [name release];
483  }
484}
485
486//===----------------------------------------------------------------------===//
487// <rdar://problem/6833332>
488// One build of the analyzer accidentally stopped tracking the allocated
489// object after the 'retain'.
490//===----------------------------------------------------------------------===//
491
492@interface rdar_6833332 : NSObject <NSApplicationDelegate> {
493    NSWindow *window;
494}
495@property (nonatomic, retain) NSWindow *window;
496@end
497
498@implementation rdar_6833332
499@synthesize window;
500- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
501 NSMutableDictionary *dict = [[NSMutableDictionary dictionaryWithCapacity:4] retain]; // expected-warning{{leak}}
502
503 [dict setObject:@"foo" forKey:@"bar"];
504
505 NSLog(@"%@", dict);
506}
507- (void)dealloc {
508    [window release];
509    [super dealloc];
510}
511@end
512
513//===----------------------------------------------------------------------===//
514// <rdar://problem/6257780> clang checker fails to catch use-after-release
515//===----------------------------------------------------------------------===//
516                                 
517int rdar_6257780_Case1() {
518  NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
519  NSArray *array = [NSArray array];
520  [array release]; // expected-warning{{Incorrect decrement of the reference count of an object is not owned at this point by the caller}}
521  [pool drain];
522  return 0;
523}
524
525//===----------------------------------------------------------------------===//
526// <rdar://problem/6866843> Checker should understand new/setObject:/release constructs
527//===----------------------------------------------------------------------===//
528
529void rdar_6866843() {
530 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
531 NSMutableDictionary* dictionary = [[NSMutableDictionary alloc] init];
532 NSArray* array = [[NSArray alloc] init];
533 [dictionary setObject:array forKey:@"key"];
534 [array release];
535 // Using 'array' here should be fine
536 NSLog(@"array = %@\n", array); // no-warning
537 // Now the array is released
538 [dictionary release];
539 [pool drain];
540}
541
542
543//===----------------------------------------------------------------------===//
544// <rdar://problem/6877235> Classes typedef-ed to CF objects should get the same treatment as CF objects
545//===----------------------------------------------------------------------===//
546
547typedef CFTypeRef OtherRef;
548
549@interface RDar6877235 : NSObject {}
550- (CFTypeRef)_copyCFTypeRef;
551- (OtherRef)_copyOtherRef;
552@end
553
554@implementation RDar6877235
555- (CFTypeRef)_copyCFTypeRef {
556  return [[NSString alloc] init]; // no-warning
557}
558- (OtherRef)_copyOtherRef {
559  return [[NSString alloc] init]; // no-warning
560}
561@end
562
563//===----------------------------------------------------------------------===//
564//<rdar://problem/6320065> false positive - init method returns an object owned by caller
565//===----------------------------------------------------------------------===//
566
567@interface RDar6320065 : NSObject {
568  NSString *_foo;
569}
570- (id)initReturningNewClass;
571- (id)initReturningNewClassBad;
572- (id)initReturningNewClassBad2;
573@end
574
575@interface RDar6320065Subclass : RDar6320065
576@end
577
578@implementation RDar6320065
579- (id)initReturningNewClass {
580  [self release];
581  self = [[RDar6320065Subclass alloc] init]; // no-warning
582  return self;
583}
584- (id)initReturningNewClassBad {
585  [self release];
586  [[RDar6320065Subclass alloc] init]; // expected-warning {{leak}}
587  return self;
588}
589- (id)initReturningNewClassBad2 {
590  [self release];
591  self = [[RDar6320065Subclass alloc] init];
592  return [self autorelease]; // expected-warning{{Object with +0 retain counts returned to caller where a +1 (owning) retain count is expected}}
593}
594
595@end
596
597@implementation RDar6320065Subclass
598@end
599
600int RDar6320065_test() {
601  RDar6320065 *test = [[RDar6320065 alloc] init]; // no-warning
602  [test release];
603  return 0;
604}
605
606//===----------------------------------------------------------------------===//
607// <rdar://problem/6859457> [NSData dataWithBytesNoCopy] does not return a retained object
608//===----------------------------------------------------------------------===//
609
610@interface RDar6859457 : NSObject {}
611- (NSString*) NoCopyString;
612- (NSString*) noCopyString;
613@end
614
615@implementation RDar6859457 
616- (NSString*) NoCopyString { return [[NSString alloc] init]; } // no-warning
617- (NSString*) noCopyString { return [[NSString alloc] init]; } // no-warning
618@end
619
620void test_RDar6859457(RDar6859457 *x, void *bytes, NSUInteger dataLength) {
621  [x NoCopyString]; // expected-warning{{leak}}
622  [x noCopyString]; // expected-warning{{leak}}
623  [NSData dataWithBytesNoCopy:bytes length:dataLength];  // no-warning
624  [NSData dataWithBytesNoCopy:bytes length:dataLength freeWhenDone:1]; // no-warning
625}
626
627//===----------------------------------------------------------------------===//
628// PR 4230 - an autorelease pool is not necessarily leaked during a premature
629//  return
630//===----------------------------------------------------------------------===//
631
632static void PR4230(void)
633{
634  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // no-warning
635  NSString *object = [[[NSString alloc] init] autorelease]; // no-warning
636  return;
637}
638
639//===----------------------------------------------------------------------===//
640// Method name that has a null IdentifierInfo* for its first selector slot.
641// This test just makes sure that we handle it.
642//===----------------------------------------------------------------------===//
643
644@interface TestNullIdentifier
645@end
646
647@implementation TestNullIdentifier
648+ (id):(int)x, ... {
649  return [[NSString alloc] init]; // expected-warning{{leak}}
650}
651@end
652
653//===----------------------------------------------------------------------===//
654// <rdar://problem/6893565> don't flag leaks for return types that cannot be 
655//                          determined to be CF types
656//===----------------------------------------------------------------------===//
657
658// We don't know if 'struct s6893565' represents a Core Foundation type, so
659// we shouldn't emit an error here.
660typedef struct s6893565* TD6893565;
661
662@interface RDar6893565 {}
663-(TD6893565)newThing;
664@end
665
666@implementation RDar6893565
667-(TD6893565)newThing {  
668  return (TD6893565) [[NSString alloc] init]; // no-warning
669}
670@end
671
672//===----------------------------------------------------------------------===//
673// <rdar://problem/6902710> clang: false positives w/QC and CoreImage methods
674//===----------------------------------------------------------------------===//
675
676void rdar6902710(QCView *view, QCRenderer *renderer, CIContext *context,
677                 NSString *str, CIImage *img, CGRect rect,
678                 CIFormat form, CGColorSpaceRef cs) {
679  [view createSnapshotImageOfType:str]; // expected-warning{{leak}}
680  [renderer createSnapshotImageOfType:str]; // expected-warning{{leak}}
681  [context createCGImage:img fromRect:rect]; // expected-warning{{leak}}
682  [context createCGImage:img fromRect:rect format:form colorSpace:cs]; // expected-warning{{leak}}
683}
684
685//===----------------------------------------------------------------------===//
686// Tests of ownership attributes.
687//===----------------------------------------------------------------------===//
688
689typedef NSString* MyStringTy;
690
691@interface TestOwnershipAttr : NSObject
692- (NSString*) returnsAnOwnedString  __attribute__((ns_returns_retained)); // no-warning
693- (NSString*) returnsAnOwnedCFString  __attribute__((cf_returns_retained)); // no-warning
694- (MyStringTy) returnsAnOwnedTypedString __attribute__((ns_returns_retained)); // no-warning
695- (int) returnsAnOwnedInt __attribute__((ns_returns_retained)); // expected-warning{{'ns_returns_retained' attribute only applies to functions or methods that return a pointer or Objective-C object}}
696@end
697
698static int ownership_attribute_doesnt_go_here __attribute__((ns_returns_retained)); // expected-warning{{'ns_returns_retained' attribute only applies to function or method types}}
699
700void test_attr_1(TestOwnershipAttr *X) {
701  NSString *str = [X returnsAnOwnedString]; // expected-warning{{leak}}
702}
703
704void test_attr_1b(TestOwnershipAttr *X) {
705  NSString *str = [X returnsAnOwnedCFString]; // expected-warning{{leak}}
706}
707
708@interface MyClassTestCFAttr : NSObject {}
709- (NSDate*) returnsCFRetained __attribute__((cf_returns_retained));
710- (NSDate*) alsoReturnsRetained;
711- (NSDate*) returnsNSRetained __attribute__((ns_returns_retained));
712@end
713
714__attribute__((cf_returns_retained))
715CFDateRef returnsRetainedCFDate()  {
716  return CFDateCreate(0, CFAbsoluteTimeGetCurrent());
717}
718
719@implementation MyClassTestCFAttr
720- (NSDate*) returnsCFRetained {
721  return (NSDate*) returnsRetainedCFDate(); // No leak.
722}
723
724- (NSDate*) alsoReturnsRetained {
725  return (NSDate*) returnsRetainedCFDate(); // expected-warning{{leak}}
726}
727
728- (NSDate*) returnsNSRetained {
729  return (NSDate*) returnsRetainedCFDate(); // no-warning
730}
731@end
732
733
734
735