From 616ee9276b74b0d2694c330766fdabf5db24001d Mon Sep 17 00:00:00 2001 From: Dulma Churchill Date: Thu, 24 Nov 2016 09:38:34 -0800 Subject: [PATCH] [clang] Adding model for NSString length to avoid false positive npes. Reviewed By: akotulski Differential Revision: D4231656 fbshipit-source-id: 4201e57 --- infer/models/objc/src/NSString.m | 13 +++++++++++++ infer/tests/codetoanalyze/objc/errors/Makefile | 1 + .../objc/errors/npe/Nsstring_length_no_npe.m | 13 +++++++++++++ 3 files changed, 27 insertions(+) create mode 100644 infer/tests/codetoanalyze/objc/errors/npe/Nsstring_length_no_npe.m diff --git a/infer/models/objc/src/NSString.m b/infer/models/objc/src/NSString.m index 2cc19a48c..84850c327 100644 --- a/infer/models/objc/src/NSString.m +++ b/infer/models/objc/src/NSString.m @@ -12,6 +12,8 @@ void __get_array_length(const UInt8); +void __infer_assume(bool cond); + @implementation NSString + (instancetype)stringWithUTF8String:(const char*)bytes { @@ -57,4 +59,15 @@ void __get_array_length(const UInt8); self->value = format->value; return self; } + +- (int)length { + if (self == nil) { + return 0; + } else { + int res; + __infer_assume(res >= 0); + return res; + } +} + @end diff --git a/infer/tests/codetoanalyze/objc/errors/Makefile b/infer/tests/codetoanalyze/objc/errors/Makefile index ec81b8dd5..efb6b727b 100644 --- a/infer/tests/codetoanalyze/objc/errors/Makefile +++ b/infer/tests/codetoanalyze/objc/errors/Makefile @@ -33,6 +33,7 @@ SOURCES_DEFAULT = \ npe/Npe_with_equal_names.m \ npe/block.m \ npe/skip_method_with_nil_object.m \ + npe/Nsstring_length_no_npe.m \ procdescs/MethodCall.m \ property/main.c \ resource_leaks/ResourceLeakExample.m \ diff --git a/infer/tests/codetoanalyze/objc/errors/npe/Nsstring_length_no_npe.m b/infer/tests/codetoanalyze/objc/errors/npe/Nsstring_length_no_npe.m new file mode 100644 index 000000000..c093771f2 --- /dev/null +++ b/infer/tests/codetoanalyze/objc/errors/npe/Nsstring_length_no_npe.m @@ -0,0 +1,13 @@ +#include +@interface Nsstring_length_no_npe : NSObject +@end + +@implementation Nsstring_length_no_npe + +- (NSDictionary*)logMessage:(NSString* __nullable)message { + if (message.length > 0) { + return @{ @"key" : message }; // No NPE because of model of NSString length. + } else + return nil; +} +@end