retain-release.m revision d7d5f0223bd30dfd618762349c6209dd1d5ea3e6
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 basic tracking of ivars associated with 'self'.  For the retain/release
276// checker we currently do not want to flag leaks associated with stores
277// of tracked objects to ivars.
278@interface SelfIvarTest : NSObject {
279  id myObj;
280}
281- (void)test_self_tracking;
282@end
283
284@implementation SelfIvarTest
285- (void)test_self_tracking {
286  myObj = (id) CFArrayCreateMutable(0, 10, &kCFTypeArrayCallBacks); // no-warning
287}
288@end
289
290// <rdar://problem/6659160>
291int isFoo(char c);
292
293static void rdar_6659160(char *inkind, char *inname)
294{
295  // We currently expect that [NSObject alloc] cannot fail.  This
296  // will be a toggled flag in the future.  It can indeed return null, but
297  // Cocoa programmers generally aren't expected to reason about out-of-memory
298  // conditions.
299  NSString *kind = [[NSString alloc] initWithUTF8String:inkind];  // expected-warning{{leak}}
300  
301  // We do allow stringWithUTF8String to fail.  This isn't really correct, as
302  // far as returning 0.  In most error conditions it will throw an exception.
303  // If allocation fails it could return 0, but again this
304  // isn't expected.
305  NSString *name = [NSString stringWithUTF8String:inname];
306  if(!name)
307    return;
308
309  const char *kindC = 0;
310  const char *nameC = 0;
311  
312  // In both cases, we cannot reach a point down below where we
313  // dereference kindC or nameC with either being null.  This is because
314  // we assume that [NSObject alloc] doesn't fail and that we have the guard
315  // up above.
316  
317  if(kind)
318    kindC = [kind UTF8String];
319  if(name)
320    nameC = [name UTF8String];
321  if(!isFoo(kindC[0])) // expected-warning{{null}}
322    return;
323  if(!isFoo(nameC[0])) // no-warning
324    return;
325
326  [kind release];
327  [name release];
328}
329
330// PR 3677 - 'allocWithZone' should be treated as following the Cocoa naming
331//  conventions with respect to 'return'ing ownership.
332@interface PR3677: NSObject @end
333@implementation PR3677
334+ (id)allocWithZone:(NSZone *)inZone {
335  return [super allocWithZone:inZone];  // no-warning
336}
337@end
338
339// PR 3820 - Reason about calls to -dealloc
340void pr3820_DeallocInsteadOfRelease(void)
341{
342  id foo = [[NSString alloc] init]; // no-warning
343  [foo dealloc];
344  // foo is not leaked, since it has been deallocated.
345}
346
347void pr3820_ReleaseAfterDealloc(void)
348{
349  id foo = [[NSString alloc] init];
350  [foo dealloc];
351  [foo release];  // expected-warning{{used after it is release}}
352  // NSInternalInconsistencyException: message sent to deallocated object
353}
354
355void pr3820_DeallocAfterRelease(void)
356{
357  NSLog(@"\n\n[%s]", __FUNCTION__);
358  id foo = [[NSString alloc] init];
359  [foo release];
360  [foo dealloc]; // expected-warning{{used after it is released}}
361  // message sent to released object
362}
363
364// From <rdar://problem/6704930>.  The problem here is that 'length' binds to
365// '($0 - 1)' after '--length', but SimpleConstraintManager doesn't know how to
366// reason about '($0 - 1) > constant'.  As a temporary hack, we drop the value
367// of '($0 - 1)' and conjure a new symbol.
368void rdar6704930(unsigned char *s, unsigned int length) {
369  NSString* name = 0;
370  if (s != 0) {
371    if (length > 0) {
372      while (length > 0) {
373        if (*s == ':') {
374          ++s;
375          --length;
376          name = [[NSString alloc] init]; // no-warning
377          break;
378        }
379        ++s;
380        --length;
381      }
382      if ((length == 0) && (name != 0)) {
383        [name release];
384        name = 0;
385      }
386      if (length == 0) { // no ':' found -> use it all as name
387        name = [[NSString alloc] init]; // no-warning
388      }
389    }
390  }
391
392  if (name != 0) {
393    [name release];
394  }
395}
396
397