From: Anna Zaks Date: Fri, 22 Jun 2012 22:42:30 +0000 (+0000) Subject: [analyzer] Teach malloc checker that initWith[Bytes|Characters}NoCopy X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=7186dc63094d3ba24e57e16a66a226d21448dd4f;p=clang [analyzer] Teach malloc checker that initWith[Bytes|Characters}NoCopy relinquish memory. git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@159043 91177308-0d34-0410-b5e6-96231b3b80d8 --- diff --git a/lib/StaticAnalyzer/Checkers/MallocChecker.cpp b/lib/StaticAnalyzer/Checkers/MallocChecker.cpp index b0fcb25079..50d4273e48 100644 --- a/lib/StaticAnalyzer/Checkers/MallocChecker.cpp +++ b/lib/StaticAnalyzer/Checkers/MallocChecker.cpp @@ -504,7 +504,9 @@ void MallocChecker::checkPreObjCMessage(const ObjCMessage &Msg, // Ex: [NSData dataWithBytesNoCopy:bytes length:10]; // Unless 'freeWhenDone' param set to 0. // TODO: Check that the memory was allocated with malloc. - if (S.getNameForSlot(0) == "dataWithBytesNoCopy" && + if ((S.getNameForSlot(0) == "dataWithBytesNoCopy" || + S.getNameForSlot(0) == "initWithBytesNoCopy" || + S.getNameForSlot(0) == "initWithCharactersNoCopy") && !isFreeWhenDoneSetToZero(Call, S)){ unsigned int argIdx = 0; C.addTransition(FreeMemAux(C, Call.getArg(argIdx), diff --git a/test/Analysis/malloc.mm b/test/Analysis/malloc.mm index 64135b2366..7a9d881b15 100644 --- a/test/Analysis/malloc.mm +++ b/test/Analysis/malloc.mm @@ -21,6 +21,16 @@ void testNSDataFreeWhenDoneYES2(NSUInteger dataLength) { NSData *nsdata = [[NSData alloc] initWithBytesNoCopy:data length:dataLength freeWhenDone:1]; // no-warning } +void testNSStringFreeWhenDoneYES3(NSUInteger dataLength) { + unsigned char *data = (unsigned char *)malloc(42); + NSString *nsstr = [[NSString alloc] initWithBytesNoCopy:data length:dataLength encoding:NSUTF8StringEncoding freeWhenDone:1]; +} + +void testNSStringFreeWhenDoneYES4(NSUInteger dataLength) { + unichar *data = (unichar*)malloc(42); + NSString *nsstr = [[NSString alloc] initWithCharactersNoCopy:data length:dataLength freeWhenDone:1]; + free(data); //expected-warning {{Attempt to free non-owned memory}} +} void testNSStringFreeWhenDoneYES(NSUInteger dataLength) { unsigned char *data = (unsigned char *)malloc(42);