retain-release.m revision 4da0427a20f31db9b6934b280d49ab264236b34c
1// RUN: clang-cc -analyze -checker-cfref -verify %s &&
2// RUN: clang-cc -analyze -checker-cfref -analyzer-store=region -verify %s
3
4
5//===----------------------------------------------------------------------===//
6// The following code is reduced using delta-debugging from
7// Foundation.h (Mac OS X).
8//
9// It includes the basic definitions for the test cases below.
10// Not including Foundation.h directly makes this test case both svelte and
11// portable to non-Mac platforms.
12//===----------------------------------------------------------------------===//
13
14typedef unsigned int __darwin_natural_t;
15typedef struct {} div_t;
16typedef unsigned long UInt32;
17typedef signed long CFIndex;
18typedef const void * CFTypeRef;
19typedef const struct __CFString * CFStringRef;
20typedef const struct __CFAllocator * CFAllocatorRef;
21extern const CFAllocatorRef kCFAllocatorDefault;
22extern CFTypeRef CFRetain(CFTypeRef cf);
23extern void CFRelease(CFTypeRef cf);
24typedef struct {
25}
26CFArrayCallBacks;
27extern const CFArrayCallBacks kCFTypeArrayCallBacks;
28typedef const struct __CFArray * CFArrayRef;
29typedef struct __CFArray * CFMutableArrayRef;
30extern CFMutableArrayRef CFArrayCreateMutable(CFAllocatorRef allocator, CFIndex capacity, const CFArrayCallBacks *callBacks);
31extern const void *CFArrayGetValueAtIndex(CFArrayRef theArray, CFIndex idx);
32extern void CFArrayAppendValue(CFMutableArrayRef theArray, const void *value);
33typedef const struct __CFDictionary * CFDictionaryRef;
34typedef UInt32 CFStringEncoding;
35enum {
36kCFStringEncodingMacRoman = 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  };
37extern CFStringRef CFStringCreateWithCString(CFAllocatorRef alloc, const char *cStr, CFStringEncoding encoding);
38typedef double CFTimeInterval;
39typedef CFTimeInterval CFAbsoluteTime;
40extern CFAbsoluteTime CFAbsoluteTimeGetCurrent(void);
41typedef const struct __CFDate * CFDateRef;
42extern CFDateRef CFDateCreate(CFAllocatorRef allocator, CFAbsoluteTime at);
43extern CFAbsoluteTime CFDateGetAbsoluteTime(CFDateRef theDate);
44typedef __darwin_natural_t natural_t;
45typedef natural_t mach_port_name_t;
46typedef mach_port_name_t mach_port_t;
47typedef struct {
48}
49CFRunLoopObserverContext;
50typedef signed char BOOL;
51typedef unsigned int NSUInteger;
52@class NSString, Protocol;
53extern void NSLog(NSString *format, ...) __attribute__((format(__NSString__, 1, 2)));
54typedef struct _NSZone NSZone;
55@class NSInvocation, NSMethodSignature, NSCoder, NSString, NSEnumerator;
56@protocol NSObject  - (BOOL)isEqual:(id)object;
57- (id)retain;
58- (oneway void)release;
59- (id)autorelease;
60@end  @protocol NSCopying  - (id)copyWithZone:(NSZone *)zone;
61@end  @protocol NSMutableCopying  - (id)mutableCopyWithZone:(NSZone *)zone;
62@end  @protocol NSCoding  - (void)encodeWithCoder:(NSCoder *)aCoder;
63@end
64@interface NSObject <NSObject> {}
65+ (id)alloc;
66+ (id)allocWithZone:(NSZone *)zone;
67@end   typedef float CGFloat;
68@interface NSString : NSObject <NSCopying, NSMutableCopying, NSCoding>    - (NSUInteger)length;
69- (const char *)UTF8String;
70- (id)initWithUTF8String:(const char *)nullTerminatedCString;
71+ (id)stringWithUTF8String:(const char *)nullTerminatedCString;
72- (id)init;
73- (void)dealloc;
74@end   extern NSString * const NSCurrentLocaleDidChangeNotification ;
75@protocol NSLocking  - (void)lock;
76@end  extern NSString * const NSUndoManagerCheckpointNotification;
77typedef enum {
78ACL_READ_DATA = (1<<1),  ACL_LIST_DIRECTORY = (1<<1),  ACL_WRITE_DATA = (1<<2),  ACL_ADD_FILE = (1<<2),  ACL_EXECUTE = (1<<3),  ACL_SEARCH = (1<<3),  ACL_DELETE = (1<<4),  ACL_APPEND_DATA = (1<<5),  ACL_ADD_SUBDIRECTORY = (1<<5),  ACL_DELETE_CHILD = (1<<6),  ACL_READ_ATTRIBUTES = (1<<7),  ACL_WRITE_ATTRIBUTES = (1<<8),  ACL_READ_EXTATTRIBUTES = (1<<9),  ACL_WRITE_EXTATTRIBUTES = (1<<10),  ACL_READ_SECURITY = (1<<11),  ACL_WRITE_SECURITY = (1<<12),  ACL_CHANGE_OWNER = (1<<13) }
79acl_entry_id_t;
80typedef int kern_return_t;
81typedef kern_return_t mach_error_t;
82typedef mach_port_t io_object_t;
83typedef io_object_t io_service_t;
84typedef struct __DASession * DASessionRef;
85extern DASessionRef DASessionCreate( CFAllocatorRef allocator );
86typedef struct __DADisk * DADiskRef;
87extern DADiskRef DADiskCreateFromBSDName( CFAllocatorRef allocator, DASessionRef session, const char * name );
88extern DADiskRef DADiskCreateFromIOMedia( CFAllocatorRef allocator, DASessionRef session, io_service_t media );
89extern CFDictionaryRef DADiskCopyDescription( DADiskRef disk );
90extern DADiskRef DADiskCopyWholeDisk( DADiskRef disk );
91@interface NSResponder : NSObject <NSCoding> {
92}
93@end  @class NSColor, NSFont, NSNotification;
94typedef struct __CFlags {
95}
96_CFlags;
97@interface NSCell : NSObject <NSCopying, NSCoding> {
98}
99@end  @class NSDate, NSDictionary, NSError, NSException, NSNotification;
100@interface NSManagedObjectContext : NSObject <NSCoding, NSLocking> {
101}
102@end enum {
103kDAReturnSuccess = 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 };
104typedef mach_error_t DAReturn;
105typedef const struct __DADissenter * DADissenterRef;
106extern DADissenterRef DADissenterCreate( CFAllocatorRef allocator, DAReturn status, CFStringRef string );
107
108
109
110
111//===----------------------------------------------------------------------===//
112// Test cases.
113//===----------------------------------------------------------------------===//
114
115CFAbsoluteTime f1() {
116  CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
117  CFDateRef date = CFDateCreate(0, t);
118  CFRetain(date);
119  CFRelease(date);
120  CFDateGetAbsoluteTime(date); // no-warning
121  CFRelease(date);
122  t = CFDateGetAbsoluteTime(date);   // expected-warning{{Reference-counted object is used after it is released.}}
123  return t;
124}
125
126CFAbsoluteTime f2() {
127  CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
128  CFDateRef date = CFDateCreate(0, t);  
129  [((NSDate*) date) retain];
130  CFRelease(date);
131  CFDateGetAbsoluteTime(date); // no-warning
132  [((NSDate*) date) release];
133  t = CFDateGetAbsoluteTime(date);   // expected-warning{{Reference-counted object is used after it is released.}}
134  return t;
135}
136
137
138NSDate* global_x;
139
140// Test to see if we supresss an error when we store the pointer
141// to a global.
142
143CFAbsoluteTime f3() {
144  CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
145  CFDateRef date = CFDateCreate(0, t);  
146  [((NSDate*) date) retain];
147  CFRelease(date);
148  CFDateGetAbsoluteTime(date); // no-warning
149  global_x = (NSDate*) date;  
150  [((NSDate*) date) release];
151  t = CFDateGetAbsoluteTime(date);   // no-warning
152  return t;
153}
154
155//---------------------------------------------------------------------------
156// Test case 'f4' differs for region store and basic store.  See
157// retain-release-region-store.m and retain-release-basic-store.m.
158//---------------------------------------------------------------------------
159
160// Test a leak.
161
162CFAbsoluteTime f5(int x) {  
163  CFAbsoluteTime t = CFAbsoluteTimeGetCurrent();
164  CFDateRef date = CFDateCreate(0, t); // expected-warning{{leak}}
165  
166  if (x)
167    CFRelease(date);
168  
169  return t;
170}
171
172// Test a leak involving the return.
173
174CFDateRef f6(int x) {  
175  CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent());  // expected-warning{{leak}}
176  CFRetain(date);
177  return date;
178}
179
180// Test a leak involving an overwrite.
181
182CFDateRef f7() {
183  CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent());  //expected-warning{{leak}}
184  CFRetain(date);
185  date = CFDateCreate(0, CFAbsoluteTimeGetCurrent());
186  return date;
187}
188
189// Generalization of Create rule.  MyDateCreate returns a CFXXXTypeRef, and
190// has the word create.
191CFDateRef MyDateCreate();
192
193CFDateRef f8() {
194  CFDateRef date = MyDateCreate(); // expected-warning{{leak}}
195  CFRetain(date);  
196  return date;
197}
198
199CFDateRef f9() {
200  CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent());
201  int *p = 0;
202  // When allocations fail, CFDateCreate can return null.
203  if (!date) *p = 1; // expected-warning{{null}}
204  return date;
205}
206
207// Handle DiskArbitration API:
208//
209// http://developer.apple.com/DOCUMENTATION/DARWIN/Reference/DiscArbitrationFramework/
210//
211void f10(io_service_t media, DADiskRef d, CFStringRef s) {
212  DADiskRef disk = DADiskCreateFromBSDName(kCFAllocatorDefault, 0, "hello"); // expected-warning{{leak}}
213  if (disk) NSLog(@"ok");
214  
215  disk = DADiskCreateFromIOMedia(kCFAllocatorDefault, 0, media); // expected-warning{{leak}}
216  if (disk) NSLog(@"ok");
217
218  CFDictionaryRef dict = DADiskCopyDescription(d);  // expected-warning{{leak}}
219  if (dict) NSLog(@"ok"); 
220  
221  disk = DADiskCopyWholeDisk(d); // expected-warning{{leak}}
222  if (disk) NSLog(@"ok");
223    
224  DADissenterRef dissenter = DADissenterCreate(kCFAllocatorDefault,   // expected-warning{{leak}}
225                                                kDAReturnSuccess, s);
226  if (dissenter) NSLog(@"ok");
227  
228  DASessionRef session = DASessionCreate(kCFAllocatorDefault);  // expected-warning{{leak}}
229  if (session) NSLog(@"ok");
230}
231
232// Test retain/release checker with CFString and CFMutableArray.
233void f11() {
234  // Create the array.
235  CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
236
237  // Create a string.
238  CFStringRef s1 = CFStringCreateWithCString(0, "hello world",
239                                             kCFStringEncodingUTF8);
240
241  // Add the string to the array.
242  CFArrayAppendValue(A, s1);
243  
244  // Decrement the reference count.
245  CFRelease(s1); // no-warning
246  
247  // Get the string.  We don't own it.
248  s1 = (CFStringRef) CFArrayGetValueAtIndex(A, 0);
249  
250  // Release the array.
251  CFRelease(A); // no-warning
252  
253  // Release the string.  This is a bug.
254  CFRelease(s1); // expected-warning{{Incorrect decrement of the reference count}}
255}
256
257// PR 3337: Handle functions declared using typedefs.
258typedef CFTypeRef CREATEFUN();
259CREATEFUN MyCreateFun;
260
261void f12() {
262  CFTypeRef o = MyCreateFun(); // expected-warning {{leak}}
263}
264
265void f13_autorelease() {
266  CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
267  [(id) A autorelease]; // no-warning
268}
269
270// This case exercises the logic where the leak site is the same as the allocation site.
271void f14_leakimmediately() {
272  CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // expected-warning{{leak}}
273}
274
275// Test that we track an allocated object beyond the point where the *name*
276// of the variable storing the reference is no longer live.
277void f15() {
278  // Create the array.
279  CFMutableArrayRef A = CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks);
280  CFMutableArrayRef *B = &A;
281  // At this point, the name 'A' is no longer live.
282  CFRelease(*B);  // no-warning
283}
284
285
286// Test basic tracking of ivars associated with 'self'.  For the retain/release
287// checker we currently do not want to flag leaks associated with stores
288// of tracked objects to ivars.
289@interface SelfIvarTest : NSObject {
290  id myObj;
291}
292- (void)test_self_tracking;
293@end
294
295@implementation SelfIvarTest
296- (void)test_self_tracking {
297  myObj = (id) CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
298}
299@end
300
301// <rdar://problem/6659160>
302int isFoo(char c);
303
304static void rdar_6659160(char *inkind, char *inname)
305{
306  // We currently expect that [NSObject alloc] cannot fail.  This
307  // will be a toggled flag in the future.  It can indeed return null, but
308  // Cocoa programmers generally aren't expected to reason about out-of-memory
309  // conditions.
310  NSString *kind = [[NSString alloc] initWithUTF8String:inkind];  // expected-warning{{leak}}
311  
312  // We do allow stringWithUTF8String to fail.  This isn't really correct, as
313  // far as returning 0.  In most error conditions it will throw an exception.
314  // If allocation fails it could return 0, but again this
315  // isn't expected.
316  NSString *name = [NSString stringWithUTF8String:inname];
317  if(!name)
318    return;
319
320  const char *kindC = 0;
321  const char *nameC = 0;
322  
323  // In both cases, we cannot reach a point down below where we
324  // dereference kindC or nameC with either being null.  This is because
325  // we assume that [NSObject alloc] doesn't fail and that we have the guard
326  // up above.
327  
328  if(kind)
329    kindC = [kind UTF8String];
330  if(name)
331    nameC = [name UTF8String];
332  if(!isFoo(kindC[0])) // expected-warning{{null}}
333    return;
334  if(!isFoo(nameC[0])) // no-warning
335    return;
336
337  [kind release];
338  [name release]; // expected-warning{{Incorrect decrement of the reference count}}
339}
340
341// PR 3677 - 'allocWithZone' should be treated as following the Cocoa naming
342//  conventions with respect to 'return'ing ownership.
343@interface PR3677: NSObject @end
344@implementation PR3677
345+ (id)allocWithZone:(NSZone *)inZone {
346  return [super allocWithZone:inZone];  // no-warning
347}
348@end
349
350// PR 3820 - Reason about calls to -dealloc
351void pr3820_DeallocInsteadOfRelease(void)
352{
353  id foo = [[NSString alloc] init]; // no-warning
354  [foo dealloc];
355  // foo is not leaked, since it has been deallocated.
356}
357
358void pr3820_ReleaseAfterDealloc(void)
359{
360  id foo = [[NSString alloc] init];
361  [foo dealloc];
362  [foo release];  // expected-warning{{used after it is release}}
363  // NSInternalInconsistencyException: message sent to deallocated object
364}
365
366void pr3820_DeallocAfterRelease(void)
367{
368  NSLog(@"\n\n[%s]", __FUNCTION__);
369  id foo = [[NSString alloc] init];
370  [foo release];
371  [foo dealloc]; // expected-warning{{used after it is released}}
372  // message sent to released object
373}
374
375// From <rdar://problem/6704930>.  The problem here is that 'length' binds to
376// '($0 - 1)' after '--length', but SimpleConstraintManager doesn't know how to
377// reason about '($0 - 1) > constant'.  As a temporary hack, we drop the value
378// of '($0 - 1)' and conjure a new symbol.
379void rdar6704930(unsigned char *s, unsigned int length) {
380  NSString* name = 0;
381  if (s != 0) {
382    if (length > 0) {
383      while (length > 0) {
384        if (*s == ':') {
385          ++s;
386          --length;
387          name = [[NSString alloc] init]; // no-warning
388          break;
389        }
390        ++s;
391        --length;
392      }
393      if ((length == 0) && (name != 0)) {
394        [name release];
395        name = 0;
396      }
397      if (length == 0) { // no ':' found -> use it all as name
398        name = [[NSString alloc] init]; // no-warning
399      }
400    }
401  }
402
403  if (name != 0) {
404    [name release];
405  }
406}
407
408//===----------------------------------------------------------------------===//
409// Tests of ownership attributes.
410//===----------------------------------------------------------------------===//
411
412@interface TestOwnershipAttr : NSObject
413- (NSString*) returnsAnOwnedString __attribute__((objc_ownership_returns));
414- (void) myRetain:(id)__attribute__((objc_ownership_retain))obj;
415@end
416
417void test_attr_1(TestOwnershipAttr *X) {
418  NSString *str = [X returnsAnOwnedString]; // expected-warning{{leak}}
419}
420
421void test_attr_2(TestOwnershipAttr *X) {
422  NSString *str = [X returnsAnOwnedString]; // expected-warning{{leak}}
423  [X myRetain:str];
424  [str release];
425}
426
427
428