Commit Graph

2651 Commits

Author SHA1 Message Date
Artem Dergachev cad151491e [analyzer] Fix a crash in CloneDetector when calling functions by pointers.
CallExpr may have a null direct callee when the callee function is not
known in compile-time. Do not try to take callee name in this case.

Patch by Raphael Isemann!

Differential Revision: https://reviews.llvm.org/D23320

llvm-svn: 278238
2016-08-10 16:25:16 +00:00
Artem Dergachev 6a76a1639f [analyzer] Change -analyze-function to accept qualified names.
Both -analyze-function and -analyzer-display-progress now share the same
convention for naming functions, which allows discriminating between
methods with the same name in different classes, C++ overloads, and also
presents Objective-C instance and class methods in the convenient notation.

This also allows looking up the name for the particular function you're trying
to restrict analysis to in the -analyzer-display-progress output,
in case it was not instantly obvious.

Differential Revision: https://reviews.llvm.org/D22856

llvm-svn: 278018
2016-08-08 16:01:02 +00:00
Gabor Horvath c430990d0b [analyzer] Command line option to show enabled checker list.
This patch adds a command line option to list the checkers that were enabled
by analyzer-checker and not disabled by -analyzer-disable-checker.

It can be very useful to debug long command lines when it is not immediately
apparent which checkers are turned on and which checkers are turned off.

Differential Revision: https://reviews.llvm.org/D23060

llvm-svn: 278006
2016-08-08 13:41:04 +00:00
Gabor Horvath 44583ce65a [analyzer] Model base to derived casts more precisely.
Dynamic casts are handled relatively well by the static analyzer.
BaseToDerived casts however are treated conservatively. This can cause some
false positives with the NewDeleteLeaks checker.

This patch alters the behavior of BaseToDerived casts. In case a dynamic cast
would succeed use the same semantics. Otherwise fall back to the conservative
approach.

Differential Revision: https://reviews.llvm.org/D23014

llvm-svn: 277989
2016-08-08 09:22:59 +00:00
Artem Dergachev 7a0088bbae [analyzer] Make CloneDetector recognize different variable patterns.
CloneDetector should be able to detect clones with renamed variables.
However, if variables are referenced multiple times around the code sample,
the usage patterns need to be recognized.

For example, (x < y ? y : x) and (y < x ? y : x) are no longer clones,
however (a < b ? b : a) is still a clone of the former.

Variable patterns are computed and compared during a separate filtering pass.

Patch by Raphael Isemann!

Differential Revision: https://reviews.llvm.org/D22982

llvm-svn: 277757
2016-08-04 19:37:00 +00:00
Artem Dergachev 7a7004a999 [analyzer] Hotfix for buildbot failure due to unspecified triple in r277449
If a target triple is not specified, the default host triple is used,
which is not good for compiling inline assembler code.

Patch by Raphael Isemann!

llvm-svn: 277473
2016-08-02 15:16:06 +00:00
Artem Dergachev 78692ea590 [analyzer] Respect statement-specific data in CloneDetection.
So far the CloneDetector only respected the kind of each statement when
searching for clones. This patch refines the way the CloneDetector collects data
from each statement by providing methods for each statement kind,
that will read the kind-specific attributes.

For example, statements 'a < b' and 'a > b' are no longer considered to be
clones, because they are different in operation code, which is an attribute
specific to the BinaryOperator statement kind.

Patch by Raphael Isemann!

Differential Revision: https://reviews.llvm.org/D22514

llvm-svn: 277449
2016-08-02 12:21:09 +00:00
Artem Dergachev ba816326f3 [analyzer] Add basic capabilities to detect source code clones.
This patch adds the CloneDetector class which allows searching source code
for clones.

For every statement or group of statements within a compound statement,
CloneDetector computes a hash value, and finds clones by detecting
identical hash values.

This initial patch only provides a simple hashing mechanism
that hashes the kind of each sub-statement.

This patch also adds CloneChecker - a simple static analyzer checker
that uses CloneDetector to report copy-pasted code.

Patch by Raphael Isemann!

Differential Revision: https://reviews.llvm.org/D20795

llvm-svn: 276782
2016-07-26 18:13:12 +00:00
Devin Coughlin f57f90dfd1 [analyzer] Add checker modeling potential C++ self-assignment
This checker checks copy and move assignment operators whether they are
protected against self-assignment. Since C++ core guidelines discourages
explicit checking for `&rhs==this` in general we take a different approach: in
top-frame analysis we branch the exploded graph for two cases, where &rhs==this
and &rhs!=this and let existing checkers (e.g. unix.Malloc) do the rest of the
work. It is important that we check all copy and move assignment operator in top
frame even if we checked them already since self-assignments may happen
undetected even in the same translation unit (e.g. using random indices for an
array what may or may not be the same).

This reapplies r275820 after fixing a string-lifetime issue discovered by the
bots.

A patch by Ádám Balogh!

Differential Revision: https://reviews.llvm.org/D19311

llvm-svn: 276365
2016-07-21 23:42:31 +00:00
Devin Coughlin d2387432bb Revert "[analyzer] Add checker modeling potential C++ self-assignment"
This reverts commit r275820. It is failing on the bots.

llvm-svn: 275880
2016-07-18 18:57:50 +00:00
Devin Coughlin eea0737a34 [analyzer] Add checker modeling potential C++ self-assignment
This checker checks copy and move assignment operators whether they are
protected against self-assignment. Since C++ core guidelines discourages
explicit checking for `&rhs==this` in general we take a different approach: in
top-frame analysis we branch the exploded graph for two cases, where &rhs==this
and &rhs!=this and let existing checkers (e.g. unix.Malloc) do the rest of the
work. It is important that we check all copy and move assignment operator in top
frame even if we checked them already since self-assignments may happen
undetected even in the same translation unit (e.g. using random indices for an
array what may or may not be the same).

A patch by Ádám Balogh!

Differential Revision: https://reviews.llvm.org/D19311

llvm-svn: 275820
2016-07-18 17:23:30 +00:00
Devin Coughlin cad622742e [analyzer] Add rudimentary handling of AtomicExpr.
This proposed patch adds crude handling of atomics to the static analyzer.
Rather than ignore AtomicExprs, as we now do, this patch causes the analyzer
to escape the arguments. This is imprecise -- and we should model the
expressions fully in the future -- but it is less wrong than ignoring their
effects altogether.

This is rdar://problem/25353187

Differential Revision: http://reviews.llvm.org/D21667

llvm-svn: 274816
2016-07-08 00:53:18 +00:00
Devin Coughlin 0a53fdf00c [analyzer] Suppress false positives in std::shared_ptr
The analyzer does not model C++ temporary destructors completely and so
reports false alarms about leaks of memory allocated by the internals of
shared_ptr:

  std::shared_ptr<int> p(new int(1));
  p = nullptr; // 'Potential leak of memory pointed to by field __cntrl_'

This patch suppresses all diagnostics where the end of the path is inside
a method in std::shared_ptr.

It also reorganizes the tests for suppressions in the C++ standard library
to use a separate simulated header for library functions with bugs
that were deliberately inserted to test suppression. This will prevent
other tests from using these as models.

rdar://problem/23652766

llvm-svn: 274691
2016-07-06 21:52:55 +00:00
Stephan Bergmann bf95fff9bd DeadStoresChecker: Don't warn about dead stores into volatile variables
llvm-svn: 273689
2016-06-24 16:26:43 +00:00
Devin Coughlin 9d5057cce5 [analyzer] Teach ObjCDeallocChecker about XCTestCase
Like with SenTestCase, subclasses of XCTestCase follow a "tear down" idiom to
release instance variables and so typically do not release ivars in -dealloc.
This commit applies the existing special casing for SenTestCase to XCTestCase
as well.

rdar://problem/25884696

llvm-svn: 273441
2016-06-22 17:03:10 +00:00
Devin Coughlin 803ee03117 [analyzer] Teach trackNullOrUndefValue() about class property accessors.
Teach trackNullOrUndefValue() how to properly look through PseudoObjectExprs
to find the underlying semantic method call for property getters. This fixes a
crash when looking through class property getters that I introduced in r265839.

rdar://problem/26796666

llvm-svn: 273340
2016-06-22 00:20:00 +00:00
Devin Coughlin 160f19cdda [analyzer] Add checker to verify the correct usage of the MPI API
This commit adds a static analysis checker to verify the correct usage of the MPI API in C
and C++. This version updates the reverted r271981 to fix a memory corruption found by the
ASan bots.

Three path-sensitive checks are included:
- Double nonblocking: Double request usage by nonblocking calls without intermediate wait
- Missing wait: Nonblocking call without matching wait.
- Unmatched wait: Waiting for a request that was never used by a nonblocking call

Examples of how to use the checker can be found at https://github.com/0ax1/MPI-Checker

A patch by Alexander Droste!

Reviewers: zaks.anna, dcoughlin

Differential Revision: http://reviews.llvm.org/D21081

llvm-svn: 272529
2016-06-13 03:22:41 +00:00
Devin Coughlin fd6d0821eb Revert "[analyzer] Reapply r271907 (2nd try)."
Even with the fix in r271981, ASan is finding a stack use after return.

This reverts commits r271977 and r271981.

llvm-svn: 271984
2016-06-07 05:37:02 +00:00
Devin Coughlin cc1fb35705 [analyzer] Reapply r271907 (2nd try).
Second try at reapplying
"[analyzer] Add checker for correct usage of MPI API in C and C++."

Special thanks to Dan Liew for helping test the fix for the template
specialization compiler error with gcc.

The original patch is by Alexander Droste!

Differential Revision: http://reviews.llvm.org/D12761

llvm-svn: 271977
2016-06-07 04:23:08 +00:00
Devin Coughlin 917a42d8b5 Revert "Reapply "[analyzer] Add checker for correct usage of MPI API in C and C++.""
This reverts commit r271914. It is still breaking bots.

llvm-svn: 271920
2016-06-06 18:29:43 +00:00
Devin Coughlin 8027409be4 Reapply "[analyzer] Add checker for correct usage of MPI API in C and C++."
Reapply r271907 with a fix for the compiler error with gcc about specializing
clang::ento::ProgramStateTrait in a different namespace.

Differential Revision: http://reviews.llvm.org/D12761

llvm-svn: 271914
2016-06-06 18:08:35 +00:00
Devin Coughlin cc73e62ebe Revert "[analyzer] Add checker for correct usage of MPI API in C and C++."
This reverts commit r271907. It broke a bunch of bots with compile errors
about specializations in different namespaces.

llvm-svn: 271909
2016-06-06 17:01:08 +00:00
Devin Coughlin 83ccd1a994 [analyzer] Add checker for correct usage of MPI API in C and C++.
This commit adds a static analysis checker to check for the correct usage of the
MPI API in C and C++.

3 path-sensitive checks are included:

- Double nonblocking: Double request usage by nonblocking calls
  without intermediate wait.
- Missing wait: Nonblocking call without matching wait.
- Unmatched wait: Waiting for a request that was never used by a
  nonblocking call.

Examples of how to use the checker can be found
at https://github.com/0ax1/MPI-Checker

Reviewers: zaks.anna

A patch by Alexander Droste!

Differential Revision: http://reviews.llvm.org/D12761

llvm-svn: 271907
2016-06-06 16:47:16 +00:00
Sean Eveson c24501dd13 [Analyzer] Correct stack address escape diagnostic
Summary:
Leaking a stack address via a static variable refers to it in the diagnostic as a 'global'. This patch corrects the diagnostic for static variables.


Patch by Phil Camp, SN Systems

Reviewers: dcoughlin, zaks.anna

Subscribers: xazax.hun, cfe-commits

Differential Revision: http://reviews.llvm.org/D19866

Patch by Phil Camp

llvm-svn: 270849
2016-05-26 14:02:17 +00:00
Anton Yartsev 8a88b90817 [analyzer] Fix for PR23790 : constrain return value of strcmp() rather than returning a concrete value.
The function strcmp() can return any value, not just {-1,0,1} : "The strcmp(const char *s1, const char *s2) function returns an integer greater than, equal to, or less than zero, accordingly as the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2." [C11 7.24.4.2p3]
https://llvm.org/bugs/show_bug.cgi?id=23790
http://reviews.llvm.org/D16317

llvm-svn: 270154
2016-05-19 23:03:49 +00:00
Richard Smith 301bc21fd0 Make Sema::getPrintingPolicy less ridiculously expensive. This used to perform
an identifier table lookup, *and* copy the LangOptions (including various
std::vector<std::string>s). Twice. We call this function once each time we start
parsing a declaration specifier sequence, and once for each call to Sema::Diag.

This reduces the compile time for a sample .c file from the linux kernel by 20%.

llvm-svn: 270009
2016-05-19 01:39:10 +00:00
Devin Coughlin c1bfafd309 [analyzer] Fix crash in ObjCGenericsChecker
Fix a crash in the generics checker where DynamicTypePropagation tries
to get the superclass of a root class.

This is a spot-fix for a deeper issue where the checker makes assumptions
that may not hold about subtyping between the symbolically-tracked type of
a value and the compile-time types of a cast on that value.

I've added a TODO to address the underlying issue.

rdar://problem/26086914

llvm-svn: 269227
2016-05-11 20:28:41 +00:00
Devin Coughlin 3d066e13d7 [analyzer] Add tests for Objective-C class properties
Add basic tests to ensure the analyzer has support for class properties. This
is a test-only change.

rdar://problem/25256807

llvm-svn: 268773
2016-05-06 18:24:50 +00:00
Devin Coughlin 97dc0c8c29 [analyzer] Add path note for localizability checker.
Add a path note indicating the location of the non-localized string
literal in NonLocalizedStringChecker.

rdar://problem/25981525

llvm-svn: 267924
2016-04-28 19:44:40 +00:00
Artem Dergachev 70247e69b1 [analyzer] Let TK_PreserveContents span across the whole base region.
If an address of a field is passed through a const pointer,
the whole structure's base region should receive the
TK_PreserveContents trait and avoid invalidation.

Additionally, include a few FIXME tests shown up during testing.

Differential Revision: http://reviews.llvm.org/D19057

llvm-svn: 267413
2016-04-25 14:44:25 +00:00
Devin Coughlin 4ac12425ba [analyzer] Nullability: Suppress diagnostic on bind with cast.
Update the nullability checker to allow an explicit cast to nonnull to
suppress a warning on an assignment of nil to a nonnull:

id _Nonnull x = (id _Nonnull)nil; // no-warning

This suppression as already possible for diagnostics on returns and
function/method arguments.

rdar://problem/25381178

llvm-svn: 266219
2016-04-13 17:59:24 +00:00
Devin Coughlin b2d2a018d6 [analyzer] Nullability: Treat nil _Nonnull ivar as invariant violation.
Treat a _Nonnull ivar that is nil as an invariant violation in a similar
fashion to how a nil _Nonnull parameter is treated as a precondition violation.

This avoids warning on defensive returns of nil on defensive internal
checks, such as the following common idiom:

@class InternalImplementation
@interface PublicClass {
  InternalImplementation * _Nonnull _internal;
}
-(id _Nonnull)foo;
@end

@implementation PublicClass
-(id _Nonnull)foo {
  if (!_internal)
    return nil; // no-warning

  return [_internal foo];
}
@end

rdar://problem/24485171

llvm-svn: 266157
2016-04-13 00:41:54 +00:00
Devin Coughlin 49bd58f1eb [analyzer] Nullability: Suppress return diagnostics in inlined functions.
The nullability checker can sometimes miss detecting nullability precondition
violations in inlined functions because the binding for the parameter
that violated the precondition becomes dead before the return:

int * _Nonnull callee(int * _Nonnull p2) {
  if (!p2)
    // p2 becomes dead here, so binding removed.
    return 0; // warning here because value stored in p2 is symbolic.
  else
   return p2;
}

int *caller(int * _Nonnull p1) {
  return callee(p1);
}

The fix, which is quite blunt, is to not warn about null returns in inlined
methods/functions. This won’t lose much coverage for ObjC because the analyzer
always analyzes each ObjC method at the top level in addition to inlined. It
*will* lose coverage for C — but there aren’t that many codebases with C
nullability annotations.

rdar://problem/25615050

llvm-svn: 266109
2016-04-12 19:29:52 +00:00
Devin Coughlin b40d14f3d5 [analyzer] Fix assertion in ReturnVisitor for body-farm synthesized getters
Don't emit a path note marking the return site if the return statement does not
have a valid location. This fixes an assertion failure I introduced in r265839.

llvm-svn: 266031
2016-04-12 00:53:26 +00:00
Devin Coughlin ebaa56bb26 [analyzer] Teach trackNullOrUndefValue about calls to property accessors.
Teach trackNullOrUndefValue() how to look through PseudoObjectExprs to find
the underlying method call for property getters. This makes over-suppression
of 'return nil' in getters consistent with the similar over-suppression for
method and function calls.

rdar://problem/24437252

llvm-svn: 265839
2016-04-08 19:59:16 +00:00
Devin Coughlin c239dd1349 [analyzer] Prefer accessor method in extension over category in CallEvent.
In ObjCMethodCall:getRuntimeDefinition(), if the method is an accessor in a
category, and it doesn't have a self declaration, first try to find the method
in a class extension. This works around a bug in Sema where multiple accessors
are synthesized for properties in class extensions that are redeclared in a
category. The implicit parameters are not filled in for the method on the
category, which causes a crash when trying to synthesize a getter for the
property in BodyFarm. The Sema bug is tracked as rdar://problem/25481164.

rdar://problem/25056531

llvm-svn: 265103
2016-04-01 03:24:13 +00:00
Devin Coughlin 7646ebe6f9 [analyzer] Use BodyFarm-synthesized body even when actual body available.
Change body autosynthesis to use the BodyFarm-synthesized body even when
an actual body exists. This enables the analyzer to use the simpler,
analyzer-provided body to model the behavior of the function rather than trying
to understand the actual body. Further, this makes the analyzer robust against
changes in headers that expose the implementations of those bodies.

rdar://problem/25145950

llvm-svn: 264687
2016-03-28 23:55:58 +00:00
Devin Coughlin 77942db0b8 [analyzer] Nullability: Don't warn along paths where null returned from non-null.
Change the nullability checker to not warn along paths where null is returned from
a method with a non-null return type, even when the diagnostic for this return
has been suppressed. This prevents warning from methods with non-null return types
that inline methods that themselves return nil but that suppressed the diagnostic.

Also change the PreconditionViolated state component to be called "InvariantViolated"
because it is set when a post-condition is violated, as well.

rdar://problem/25393539

llvm-svn: 264647
2016-03-28 20:30:25 +00:00
Devin Coughlin b8076292ab [analyzer] Add CIFIlter modeling to DeallocChecker.
The -dealloc method in CIFilter is highly unusual in that it will release
instance variables belonging to its *subclasses* if the variable name
starts with "input" or backs a property whose name starts with "input".
Subclasses should not release these ivars in their own -dealloc method --
doing so could result in an over release.

Before this commit, the DeallocChecker would warn about missing releases for
such "input" properties -- which could cause users of the analyzer to add
over releases to silence the warning.

To avoid this, DeallocChecker now treats CIFilter "input-prefixed" ivars
as MustNotReleaseDirectly and so will not require a release. Further, it
will now warn when such an ivar is directly released in -dealloc.

rdar://problem/25364901

llvm-svn: 264463
2016-03-25 21:18:22 +00:00
Anna Zaks 30d4668774 [analyzer] Fix missed leak from MSVC specific allocation functions
Add the wide character strdup variants (wcsdup, _wcsdup) and the MSVC
version of alloca (_alloca) and other differently named function used
by the Malloc checker.

A patch by Alexander Riccio!

Differential Revision: http://reviews.llvm.org/D17688

llvm-svn: 262894
2016-03-08 01:21:51 +00:00
Richard Smith 4f902c7ecc P0188R1: add support for standard [[fallthrough]] attribute. This is almost
exactly the same as clang's existing [[clang::fallthrough]] attribute, which
has been updated to have the same semantics. The one significant difference
is that [[fallthrough]] is ill-formed if it's not used immediately before a
switch label (even when -Wimplicit-fallthrough is disabled). To support that,
we now build a CFG of any function that uses a '[[fallthrough]];' statement
to check.

In passing, fix some bugs with our support for statement attributes -- in
particular, diagnose their use on declarations, rather than asserting.

llvm-svn: 262881
2016-03-08 00:32:55 +00:00
Devin Coughlin a1d9d75a88 [analyzer] Nullability: add option to not report on calls to system headers.
Add an -analyzer-config 'nullability:NoDiagnoseCallsToSystemHeaders' option to
the nullability checker. When enabled, this option causes the analyzer to not
report about passing null/nullable values to functions and methods declared
in system headers.

This option is motivated by the observation that large projects may have many
nullability warnings. These projects may find warnings about nullability
annotations that they have explicitly added themselves higher priority to fix
than warnings on calls to system libraries.

llvm-svn: 262763
2016-03-05 01:32:43 +00:00
Devin Coughlin a604679897 [analyzer] Add diagnostic in ObjCDeallocChecker for use of -dealloc instead of -release.
In dealloc methods, the analyzer now warns when -dealloc is called directly on
a synthesized retain/copy ivar instead of -release. This is intended to find mistakes of
the form:

- (void)dealloc {
  [_ivar dealloc]; // Mistaken call to -dealloc instead of -release

  [super dealloc];
}

rdar://problem/16227989

llvm-svn: 262729
2016-03-04 18:09:58 +00:00
Devin Coughlin 578a20a82e [analyzer] ObjCDeallocChecker: Only check for nil-out when type is retainable.
This fixes a crash when setting a property of struct type in -dealloc.

llvm-svn: 262659
2016-03-03 21:38:39 +00:00
Devin Coughlin 2b2f8996ce [analyzer] Move ObjCSuperDeallocChecker out of the alpha package.
It will now be on by default on Darwin.

rdar://problem/6953275

llvm-svn: 262526
2016-03-02 22:01:03 +00:00
Devin Coughlin 2b77c4603d [analyzer] Move ObjCDeallocChecker out of the alpha package.
It will now be on by default on Darwin.

rdar://problem/6927496

llvm-svn: 262524
2016-03-02 21:50:54 +00:00
Devin Coughlin dce8d8b3f1 [analyzer] Fix capitalization in ObjCSuperDeallocChecker diagnostic.
llvm-svn: 262520
2016-03-02 21:22:48 +00:00
Devin Coughlin 6d0c8a036e [analyzer] Update CheckObjCDealloc diagnostic for missing -dealloc.
Update the diagnostic for classes missing -dealloc to mention an instance
variable that needs to be released.

llvm-svn: 262277
2016-03-01 00:39:04 +00:00
Devin Coughlin 093594938b [analyzer] Teach CheckObjCDealloc about Block_release().
It now treats Block_release(b) as a release in addition to [b release].

llvm-svn: 262272
2016-02-29 23:57:10 +00:00
Devin Coughlin 3fc67e47e5 [analyzer] Don't treat calls to system headers as escaping in CheckObjCDealloc.
This prevents false negatives when a -dealloc method, for example, removes itself as
as an observer with [[NSNotificationCenter defaultCenter] removeObserver:self]. It is
unlikely that passing 'self' to a system header method will release 'self''s instance
variables, so this is unlikely to produce false positives.

A challenge here is that while CheckObjCDealloc no longer treats these calls as
escaping, the rest of the analyzer still does. In particular, this means that loads
from the same instance variable before and after a call to a system header will
result in different symbols being loaded by the region store. To account for this,
the checker now treats different ivar symbols with the same instance and ivar decl as
the same for the purpose of release checking and more eagerly removes a release
requirement when an instance variable is assumed to be nil. This was not needed before
because when an ivar escaped its release requirement was always removed -- now the
requirement is not removed for calls to system headers.

llvm-svn: 262261
2016-02-29 21:44:08 +00:00
Devin Coughlin 896dffe752 [analyzer] Shorten ObjcSuperDeallocChecker diagnostics.
Change "use of 'self' after it has been freed with call to [super dealloc]" to
"use of 'self' after it has been deallocated" and "use of instance variable
'_ivar' after the instance has been freed with call to [super dealloc]" to
"use of instance variable '_ivar' after 'self' has been deallocated".

llvm-svn: 261945
2016-02-26 00:47:42 +00:00
Devin Coughlin 591991c86f [analyzer] Warn on use of 'self' after call to to [super dealloc].
Referring to 'self' after a call to [super dealloc] is a use-after-free in
Objective-C because NSObject's -dealloc frees the memory pointed to by self.
This patch extends the ObjCSuperDeallocChecker to catch this error.

rdar://problem/6953275

Differential Revision: http://reviews.llvm.org/D17528

llvm-svn: 261935
2016-02-25 23:36:52 +00:00
Devin Coughlin ad9f53e959 [analyzer] Reapply r261917 with a fix.
This reapplies "[analyzer] Make ObjCDeallocChecker path sensitive." (r261917)
with a fix for an error on some bots about specializing a template
from another namespace.

llvm-svn: 261929
2016-02-25 21:15:16 +00:00
Devin Coughlin ea02bba5a1 Revert "[analyzer] Make ObjCDeallocChecker path sensitive."
This reverts commit r261917. It broke the bots.

llvm-svn: 261921
2016-02-25 19:13:43 +00:00
Devin Coughlin 88691c1fcb [analyzer] Make ObjCDeallocChecker path sensitive.
Convert the ObjCDeallocChecker to be path sensitive. The primary
motivation for this change is to prevent false positives when -dealloc calls
helper invalidation methods to release instance variables, but it additionally
improves precision when -dealloc contains control flow. It also reduces the need
for pattern matching. The check for missing -dealloc methods remains AST-based.

Part of rdar://problem/6927496

Differential Revision: http://reviews.llvm.org/D17511

llvm-svn: 261917
2016-02-25 18:55:24 +00:00
Devin Coughlin c289b74bd6 [analyzer] Find ObjC 'self' decl even when block captures local named 'self'.
When looking up the 'self' decl in block captures, make sure to find the actual
self declaration even when the block captures a local variable named 'self'.

rdar://problem/24751280

llvm-svn: 261703
2016-02-23 22:26:04 +00:00
Gabor Horvath d1abcf799e [analyzer] Improve pointer arithmetic checker.
This patch is intended to improve pointer arithmetic checker.
From now on it only warns when the pointer arithmetic is likely to cause an
error. For example when the pointer points to a single object, or an array of
derived types.

Differential Revision: http://reviews.llvm.org/D14203

llvm-svn: 261632
2016-02-23 12:34:39 +00:00
Devin Coughlin eb6673cfed [analyzer] Detect duplicate [super dealloc] calls
Add an alpha path checker that warns about duplicate calls to [super dealloc].
This will form the foundation of a checker that will detect uses of
'self' after calling [super dealloc].

Part of rdar://problem/6953275.

Based on a patch by David Kilzer!

Differential Revision: http://reviews.llvm.org/D5238

llvm-svn: 261545
2016-02-22 17:56:24 +00:00
Devin Coughlin 8d922aa746 [analyzer] Add checker callback for beginning of function.
Add a checker callback that is called when the analyzer starts analyzing a
function either at the top level or when inlined. This will be used by a
follow-on patch making the DeallocChecker path sensitive.

Differential Revision: http://reviews.llvm.org/D17418

llvm-svn: 261293
2016-02-19 01:35:10 +00:00
Devin Coughlin 069a1073dd [analyzer] Improve modeling of ObjC synthesized property setters.
When modeling a call to a setter for a property that is synthesized to be
backed by an instance variable, don't invalidate the entire instance
but rather only the storage for the updated instance variable itself.

This still doesn't model the effect of the setter completely. It doesn't
bind the set value to the ivar storage location because doing so would cause
the set value to escape, removing valuable diagnostics about potential
leaks of the value from the retain count checker.

llvm-svn: 261243
2016-02-18 19:13:30 +00:00
Devin Coughlin 982c42da64 [analyzer] Improve pattern matching in ObjCDealloc checker.
Look through PseudoObjectExpr and OpaqueValueExprs when scanning for
release-like operations. This commit also adds additional tests in anticipation
of re-writing this as a path-sensitive checker.

llvm-svn: 260608
2016-02-11 22:13:20 +00:00
Devin Coughlin 480a0c00ca [analyzer] Avoid crash when attempting to evaluate binary operation on LazyCompoundVal.
Instead, return UnknownValue if either operand is a nonloc::LazyCompoundVal. This is a
spot fix for PR 24951.

rdar://problem/23682244

llvm-svn: 260066
2016-02-08 00:28:24 +00:00
Devin Coughlin 9165df129e [analyzer] Invalidate destination of std::copy() and std::copy_backward().
Now that the libcpp implementations of these methods has a branch that doesn't call
memmove(), the analyzer needs to invalidate the destination for these methods explicitly.

rdar://problem/23575656

llvm-svn: 260043
2016-02-07 16:55:44 +00:00
Devin Coughlin 38e0e2970c [analyzer] DeallocChecker: Don't warn on release of readonly assign property in dealloc.
It is common for the ivars for read-only assign properties to always be stored retained,
so don't warn for a release in dealloc for the ivar backing these properties.

llvm-svn: 259998
2016-02-06 17:17:32 +00:00
Devin Coughlin 084e363517 [analyzer] Suppress localization diagnostics in debug classes and methods.
If the class or method name case-insensitively contains the term "debug",
suppress warnings about string constants flowing to user-facing UI APIs.

llvm-svn: 259875
2016-02-05 04:22:15 +00:00
Yury Gribov 0826bf2211 Forgot to remove file in previous commit.
llvm-svn: 259647
2016-02-03 13:36:31 +00:00
Yury Gribov 8f7d8b6c32 [analyzer] AnalysisConsumer: print fully-qualified function name while displaying progress
-analyzer-display progress option prints only function names which may be ambiguous. This patch forces AnalysisConsumer to print fully-qualified function names.
Patch by Alex Sidorin!

Differential Revision: http://reviews.llvm.org/D16804

llvm-svn: 259646
2016-02-03 13:35:33 +00:00
Artem Dergachev f8d0f18fac [analyzer] Use a wider integer type for an array index.
Avoids unexpected overflows while performing pointer arithmetics in 64-bit code.
Moreover, neither PointerDiffType nor 'int' can be used as a common array index
type because arrays may have size (and indexes) more than PTRDIFF_MAX but less
than SIZE_MAX.

Patch by Aleksei Sidorin!

Differential Revision: http://reviews.llvm.org/D16063

llvm-svn: 259345
2016-02-01 09:29:17 +00:00
Devin Coughlin 4be27d4db9 [analyzer] Make suppression of macro defensive checks work with -analyzer-eagerly-assume.
This is the default for the analyzer but the flag is added by the driver so
our suppression tests didn't cover this case.

llvm-svn: 259288
2016-01-30 01:59:33 +00:00
Devin Coughlin 07c451fa4a [analyzer] Suppress null reports from defensive checks in function-like macros.
We already do this for case splits introduced as a result of defensive null
checks in functions and methods, so do the same for function-like macros.

rdar://problem/19640441

llvm-svn: 259222
2016-01-29 18:47:13 +00:00
Anna Zaks ad9e7ea6d7 [analyzer] Improve Nullability checker diagnostics
- Include the position of the argument on which the nullability is violated
- Differentiate between a 'method' and a 'function' in the message wording
- Test for the error message text in the tests
- Fix a bug with setting 'IsDirectDereference' which resulted in regular dereferences assumed to have call context.

llvm-svn: 259221
2016-01-29 18:43:15 +00:00
Devin Coughlin de21767a4d [analyzer] Suppress nullability warnings in copy, mutableCopy, and init families.
There are multiple, common idioms of defensive nil-checks in copy,
mutableCopy, and init methods in ObjC. The analyzer doesn't currently have the
capability to distinguish these idioms from true positives, so suppress all
warnings about returns in those families. This is a pretty blunt suppression
that we should improve later.

rdar://problem/24395811

llvm-svn: 259099
2016-01-28 22:23:34 +00:00
Devin Coughlin 3075134739 [analyzer] ObjCDeallocChecker: Only operate on classes with retained properties.
Previously the ObjC Dealloc Checker only checked classes with ivars, not
retained properties, which caused three bugs:

- False positive warnings about a missing -dealloc method in classes with only
ivars.
- Missing warnings about a missing -dealloc method on classes with only
properties.
- Missing warnings about an over-released or under-released ivar associated with
a retained property in classes with only properties.

The fix is to check only classes with at least one retained synthesized
property.

This also exposed a bug when reporting an over-released or under-released
property that did not contain a synthesize statement. The checker tried to
associate the warning with an @synthesize statement that did not exist, which
caused an assertion failure in debug builds. The fix is to fall back to the
@property statement in this case.

A patch by David Kilzer!

Part of rdar://problem/6927496

Differential Revision: http://reviews.llvm.org/D5023

llvm-svn: 258896
2016-01-27 01:41:58 +00:00
Devin Coughlin b7e810bdc1 [analyzer] Body farm: Look for property ivar in shadowing readwrite property.
After r251874, readonly properties that are shadowed by a readwrite property
in a class extension no longer have an instance variable, which caused the body
farm to not synthesize getters. Now, if a readonly property does not have an
instance variable look for a shadowing property and try to get the instance
variable from there.

rdar://problem/24060091

llvm-svn: 258886
2016-01-26 23:58:48 +00:00
Devin Coughlin 4a330201ff [analyzer] Suppress nullability warning for defensive super initializer idiom.
A common idiom in Objective-C initializers is for a defensive nil-check on the
result of a call to a super initializer:
  if (self = [super init]) {
     ...
  }
  return self;

To avoid warning on this idiom, the nullability checker now suppress diagnostics
for returns of nil on syntactic 'return self' even in initializers with non-null
return types.

llvm-svn: 258461
2016-01-22 01:01:11 +00:00
Devin Coughlin 5a3843e506 [analyzer] Nullability: Look through implicit casts when suppressing warnings on return.
In r256567 I changed the nullability checker to suppress warnings about returning a null
value from a function/method with a non-null return type when the type of the returned
expression is itself nonnull. This enables the programmer to silence nullability warnings
by casting to _Nonnull:

  return (SomeObject * _Nonnull)nil;

Unfortunately, under ObjC automated reference counting, Sema adds implicit casts to
_Nonnull to return expressions of nullable or unspecified types in functions with
non-null function/method return types. With r256567, these casts cause all nullability
warnings for returns of reference-counted types to be suppressed under ARC, leading to
false negatives.

This commit updates the nullability checker to look through implicit casts before
determining the type of the returned expression. It also updates the tests to turn on
ARC for the nullability_nullonly.mm testfile and adds a new testfile to test when ARC
is turned off.

rdar://problem/24200117

llvm-svn: 258061
2016-01-18 18:53:33 +00:00
Artem Dergachev 91c45e8f46 [analyzer] Fix an off-by-one in evalIntegralCast()
Make sure that we do not add SymbolCast at the very boundary of
the range in which the cast would not certainly happen.

Differential Revision: http://reviews.llvm.org/D16178

llvm-svn: 258039
2016-01-18 10:17:16 +00:00
Devin Coughlin 851da71c8f [analyzer] Check for return of nil in ObjC methods with nonnull return type.
Update NullabilityChecker so that it checks return statements in ObjC methods.
Previously it was returning early because methods do not have a function type.

Also update detection of violated parameter _Nonnull preconditions to handle
ObjC methods.

rdar://problem/24200560

llvm-svn: 257938
2016-01-15 21:35:40 +00:00
Artem Dergachev 895242f9fb [analyzer] Provide .def-files and visitors for SVal/SymExpr/MemRegion, v2.
Provide separate visitor templates for the three hierarchies, and also
the `FullSValVisitor' class, which is a union of all three visitors.

Additionally, add a particular example visitor, `SValExplainer', in order to
test the visitor templates. This visitor is capable of explaining the SVal,
SymExpr, or MemRegion in a natural language.

Compared to the reverted r257605, this fixes the test that used to fail
on some triples, and fixes build failure under -fmodules.

Differential Revision: http://reviews.llvm.org/D15448

llvm-svn: 257893
2016-01-15 15:22:05 +00:00
Artem Dergachev 26ec8acc84 Revert "[analyzer] Provide .def-files and visitors for SVal/SymExpr/MemRegion."
This reverts commit r257605.

The test fails on architectures that use unsigned int as size_t.
SymbolManager.h fails with compile errors on some platforms.

llvm-svn: 257608
2016-01-13 15:52:25 +00:00
Artem Dergachev beb02b5b8f [analyzer] Provide .def-files and visitors for SVal/SymExpr/MemRegion.
Provide separate visitor templates for the three hierarchies, and also
the `FullSValVisitor' class, which is a union of all three visitors.

Additionally, add a particular example visitor, `SValExplainer', in order to
test the visitor templates. This visitor is capable of explaining the SVal,
SymExpr, or MemRegion in a natural language.

Differential Revision: http://reviews.llvm.org/D15448

llvm-svn: 257605
2016-01-13 15:13:48 +00:00
Pierre Gousseau bdd9da14d6 [analyzer] Fix RangeConstraintManager's pinning of single value ranges.
This fix a bug in RangeSet::pin causing single value ranges to be considered non conventionally ordered.

Differential Revision: http://reviews.llvm.org/D12901

llvm-svn: 257467
2016-01-12 10:40:45 +00:00
Pierre Gousseau e961b445ad [analyzer] Evaluate integral casts as cast symbols if truncations are detected.
The current workaround for truncations not being modelled is that the evaluation of integer to integer casts are simply bypassed and so the original symbol is used as the new casted symbol (cf SimpleSValBuilder::evalCastFromNonLoc).
This lead to the issue described in PR25078, as the RangeConstraintManager associates ranges with symbols.

The new evalIntegralCast method added by this patch wont bypass the cast if it finds the range of the symbol to be greater than the maximum value of the target type.

The fix to RangeSet::pin mentioned in the initial review will be committed separately.

Differential Revision: http://reviews.llvm.org/D12901

llvm-svn: 257464
2016-01-12 10:07:56 +00:00
Yury Gribov 054873b0be AnalysisConsumer: use canonical decl for both lookup and store of
visited decls.

Due to redeclarations, the function may have different declarations used
in CallExpr and in the definition. However, we need to use a unique
declaration for both store and lookup in VisitedCallees. This patch
fixes issues with analysis in topological order. A simple test is
included.

Patch by Alex Sidorin!

Differential Revision: http://reviews.llvm.org/D15410

llvm-svn: 257318
2016-01-11 09:38:48 +00:00
Anna Zaks 03f483353c [analyzer] Fix false warning about memory leak for QApplication::postEvent
According to Qt documentation Qt takes care of memory allocated for QEvent:
http://doc.qt.io/qt-4.8/qcoreapplication.html#postEvent

A patch by Evgeniy Dushistov!

Differential Revision: http://reviews.llvm.org/D14170

llvm-svn: 256887
2016-01-06 00:32:56 +00:00
Anna Zaks ac4c8a639c [analyzer] Suppress reports coming from std::__independent_bits_engine
The analyzer reports a shift by a negative value in the constructor. The bug can
be easily triggered by calling std::random_shuffle on a vector
(<rdar://problem/19658126>).

(The shift by a negative value is reported because __w0_ gets constrained to
63 by the conditions along the path:__w0_ < _WDt && __w0_ >= _WDt-1,
where _WDt is 64. In normal execution, __w0_ is not 63, it is 1 and there is
no overflow. The path is infeasible, but the analyzer does not know about that.)

llvm-svn: 256886
2016-01-06 00:32:52 +00:00
Anna Zaks c9f16fe48c [analyzer] Don't report null dereferences on address_space annotated memory
llvm-svn: 256885
2016-01-06 00:32:49 +00:00
Devin Coughlin 3369867aa7 [analyzer] Handle another Android assert function.
Android's assert can call both the __assert and __assert2 functions under the cover, but
the NoReturnFunctionChecker does not handle the latter. This commit fixes that.

A patch by Yury Gribov!

Differential Revision: http://reviews.llvm.org/D15810

llvm-svn: 256605
2015-12-30 00:08:59 +00:00
Devin Coughlin 3ab8b2e7d4 [analyzer] Suppress nullability warning for _Nonnull locals zero-initialized by ObjC ARC.
Prevent the analyzer from warning when a _Nonnnull local variable is implicitly
zero-initialized because of Objective-C automated reference counting. This avoids false
positives in cases where a _Nonnull local variable cannot be initialized with an
initialization expression, such as:
  NSString * _Nonnull s; // no-warning
  @autoreleasepool {
    s = ...;
  }

The nullability checker will still warn when a _Nonnull local variable is explicitly
initialized with nil.

This suppression introduces the potential for false negatives if the local variable
is used before it is assigned a _Nonnull value. Based on a discussion with Anna Zaks,
Jordan Rose, and John McCall, I've added a FIXME to treat implicitly zero-initialized
_Nonnull locals as uninitialized in Sema's UninitializedValues analysis to avoid these
false negatives.

rdar://problem/23522311

llvm-svn: 256603
2015-12-29 23:44:19 +00:00
Devin Coughlin 755baa4050 [analyzer] Nullability: allow cast to _Nonnull to suppress warning about returning nil.
The nullability checker currently allows casts to suppress warnings when a nil
literal is passed as an argument to a parameter annotated as _Nonnull:

  foo((NSString * _Nonnull)nil); // no-warning

It does so by suppressing the diagnostic when the *type* of the argument expression
is _Nonnull -- even when the symbolic value returned is known to be nil.

This commit updates the nullability checker to similarly honor such casts in the analogous
scenario when nil is returned from a function with a _Nonnull return type:

  return (NSString * _Nonnull)nil; // no-warning

This commit also normalizes variable naming between the parameter and return cases and
adds several tests demonstrating the limitations of this suppression mechanism (such as
when nil is cast to _Nonnull and then stored into a local variable without a nullability
qualifier). These tests are marked with FIXMEs.

rdar://problem/23176782

llvm-svn: 256567
2015-12-29 17:40:49 +00:00
Devin Coughlin 412c0af2b8 [analyzer] Better detect when C++ object was constructed into existing region.
When the analyzer evaluates a CXXConstructExpr, it looks ahead in the CFG for
the current block to detect what region the object should be constructed into.
If the constructor was directly constructed into a local variable or field
region then there is no need to explicitly bind the constructed value to
the local or field when analyzing the DeclStmt or CXXCtorInitializer that
called the constructor.

Unfortunately, there were situations in which the CXXConstructExpr was
constructed into a temporary region but when evaluating the corresponding
DeclStmt or CXXCtorInitializer the analyzer assumed the object was constructed
into the local or field. This led to spurious warnings about uninitialized
values (PR25777).

To avoid these false positives, this commit factors out the logic for
determining when a CXXConstructExpr will be directly constructed into existing
storage, adds the inverse logic to detect when the corresponding later bind can
be safely skipped, and adds assertions to make sure these two checks are in
sync.

rdar://problem/21947725

llvm-svn: 255859
2015-12-17 00:28:33 +00:00
NAKAMURA Takumi b4a6884844 clang/test/Analysis/padding_c.c: Suppress a test incompatible to i686-linux.
error: 'warning' diagnostics expected but not seen:
    File clang/test/Analysis/padding_c.c Line 194 (directive at clang/test/Analysis/padding_c.c:193): Excessive padding in 'struct DefaultAttrAlign'
  1 error generated.

llvm-svn: 255636
2015-12-15 09:37:01 +00:00
Ben Craig 97c191c473 [PATCH] Adding checker to detect excess padding in records
The intent of this checker is to generate a report for any class / structure
that could reduce its padding by reordering the fields.  This results in a very
noisy checker.  To reduce the noise, this checker will currently only warn when
the number of bytes over "optimal" is more than 24.  This value is configurable
with -analyzer-config performance.Padding:AllowedPad=N.  Small values of
AllowedPad have the potential to generate hundreds of reports, and gigabytes
of HTML reports.

The checker searches for padding violations in two main ways.  First, it goes
record by record.  A report is generated if the fields could be reordered in a
way that reduces the padding by more than AllowedPad bytes.  Second, the
checker will generate a report if an array will cause more than AllowedPad
padding bytes to be generated.

The record checker currently skips many ABI specific cases.  Classes with base
classes are skipped because base class tail padding is ABI specific.  Bitfields
are just plain hard, and duplicating that code seems like a bad idea.  VLAs are
both uncommon and non-trivial to fix.

The array checker isn't very thorough right now.  It only checks to see if the
element type's fields could be reordered, and it doesn't recursively check to
see if any of the fields' fields could be reordered.  At some point in the
future, it would be nice if "arrays" could also look at array new usages and
malloc patterns that appear to be creating arrays.

llvm-svn: 255545
2015-12-14 21:38:59 +00:00
Artem Dergachev 733e71b73b [analyzer] Fix symbolic element index lifetime.
SymbolReaper was destroying the symbol too early when it was referenced only
from an index SVal of a live ElementRegion.

In order to test certain aspects of this patch, extend the debug.ExprInspection
checker to allow testing SymbolReaper in a direct manner.

Differential Revision: http://reviews.llvm.org/D12726

llvm-svn: 255236
2015-12-10 09:28:06 +00:00
Devin Coughlin 7bdca8b24f [analyzer] Fix crash when lambda captures a variable-length array.
When a C++ lambda captures a variable-length array, it creates a capture
field to store the size of the array. The initialization expression for this
capture is null, which led the analyzer to crash when initializing the field.
To avoid this, use the size expression from the VLA type to determine the
initialization value.

rdar://problem/23748072

llvm-svn: 254962
2015-12-07 23:01:53 +00:00
Devin Coughlin 46089867de [analyzer] Fix MemRegion crash casting non-struct to derived struct (PR25426).
This commit prevents MemRegion::getAsOffset() from crashing when the analyzed
program casts a symbolic region of a non-record type to some derived type and
then attempts to access a field of the base type.

rdar://problem/23458069

llvm-svn: 254806
2015-12-05 00:22:36 +00:00
Gabor Horvath e86cb2e822 [analyzer] Improve modelling of nullptr_t in the analyzer. Fix PR25414.
Differential Revision: http://reviews.llvm.org/D15007

llvm-svn: 254718
2015-12-04 15:02:30 +00:00
Devin Coughlin ebeed88078 [analyzer] Support inlining lambda-converted blocks.
clang converts C++ lambdas to blocks with an implicit user-defined conversion
operator method on the lambda record. This method returns a block that captures a copy
of the lambda. To inline a lambda-converted block, the analyzer now calls the lambda
records's call operator method on the lambda captured by the block.

llvm-svn: 254702
2015-12-04 05:00:36 +00:00
Devin Coughlin dfde655461 [analyzer] Suppress stack address escape on CK_CopyAndAutoreleaseBlockObject.
Don't warn about addresses of stack-allocated blocks escaping if the block
region was cast with CK_CopyAndAutoreleaseBlockObject. These casts, which
are introduced in the implicit conversion operator for lambda-to-block
conversions, cause the block to be copied to the heap -- so the warning is
spurious.

llvm-svn: 254639
2015-12-03 19:41:24 +00:00
Gabor Horvath fe2c0ff942 [analyzer] Fix IssueHash generation.
Differential Revision: http://reviews.llvm.org/D14919 

Original patch by: Gyorgy Orban!

llvm-svn: 254394
2015-12-01 09:00:41 +00:00
Devin Coughlin 2c2c3cb3d0 [analyzer] Add tests for generalized lambda capture (C++14). NFC.
Add tests demonstrating that the analyzer supports generalized lambda capture. This
support falls out naturally from the work Gábor Horváth did adding C++11 lambdas to
the analyzer.

llvm-svn: 254114
2015-11-26 00:11:23 +00:00
Devin Coughlin b6029b7ef4 [analyzer] Include block capture copy expressions in the CFG.
This prevents spurious dead store warnings when a C++ lambda is casted to a block.

I've also added several tests documenting our still-incomplete support for lambda-to-block
casts.

rdar://problem/22236293

llvm-svn: 254107
2015-11-25 22:35:37 +00:00
Devin Coughlin c1986638a7 [analyzer] Pass value expression for inlined defensive checks when binding null to nonnull.
The nullability checker was not suppressing false positives resulting from
inlined defensive checks when null was bound to a nonnull variable because it
was passing the entire bind statement rather than the value expression to
trackNullOrUndefValue().

This commit changes that checker to synactically match on the bind statement to
extract the value expression so it can be passed to trackNullOrUndefValue().

rdar://problem/23575439

llvm-svn: 254007
2015-11-24 19:15:11 +00:00
Devin Coughlin c7315b3ebf [analyzer] DeadStoresChecker: Treat locals captured by reference in C++ lambdas as escaped.
The analyzer currently reports dead store false positives when a local variable
is captured by reference in a C++ lambda.

For example:

  int local = 0; auto lambda = [&local]() {
    local++;
  };
  local = 7; // False Positive: Value stored to 'local' is never read
  lambda();

In this case, the assignment setting `local` to 7 is not a dead store because
the called lambda will later read that assigned value.

This commit silences this source of false positives by treating locals captured
by reference in C++ lambdas as escaped, similarly to how the DeadStoresChecker
deals with locals whose address is taken.

rdar://problem/22165179

llvm-svn: 253630
2015-11-20 01:53:44 +00:00
Anna Zaks 61fcb521fa [analyzer] Improve modeling of static initializers.
Conversions between unrelated pointer types (e.g. char * and void *) involve
bitcasts which were not properly modeled in case of static initializers. The
patch fixes this problem.

The problem was originally spotted by Artem Dergachev. Patched by Yuri Gribov!

Differential Revision: http://reviews.llvm.org/D14652

llvm-svn: 253532
2015-11-19 01:25:28 +00:00
Devin Coughlin 6e644abd46 [analyzer] Skip checking blocks in dependent contexts.
Since we don't check functions in dependent contexts, we should skip blocks
in those contexts as well. This avoids an assertion failure when the
DeadStoresChecker attempts to evaluate an array subscript expression with
a dependent name type.

rdar://problem/23564220

llvm-svn: 253516
2015-11-18 22:46:52 +00:00
Devin Coughlin 1d4058322d [analyzer] Handle calling ObjC super method from inside C++ lambda.
When calling a ObjC method on super from inside a C++ lambda, look at the
captures to find "self". This mirrors how the analyzer handles calling super in
an ObjC block and fixes an assertion failure.

rdar://problem/23550077

llvm-svn: 253176
2015-11-15 17:48:22 +00:00
Devin Coughlin e69b043088 [analyzer] Refer to capture field to determine if capture is reference.
The analyzer incorrectly treats captures as references if either the original
captured variable is a reference or the variable is captured by reference.
This causes the analyzer to crash when capturing a reference type by copy
(PR24914). Fix this by refering solely to the capture field to determine when a
DeclRefExpr for a lambda capture should be treated as a reference type.

https://llvm.org/bugs/show_bug.cgi?id=24914
rdar://problem/23524412

llvm-svn: 253157
2015-11-15 03:07:17 +00:00
Matthias Gehre 09a134eca3 CFG: Delay creating Dtors for CompoundStmts which end in ReturnStmt
Summary:
VisitReturnStmt would create a new block with including Dtors, so the Dtors created
in VisitCompoundStmts would be in an unreachable block.

Example:

struct S {
  ~S();
};

void f()
{
  S s;
  return;
}

void g()
{
  S s;
}

Before this patch, f has one additional unreachable block containing just the
destructor of S. With this patch, both f and g have the same blocks.

Reviewers: krememek

Subscribers: cfe-commits

Differential Revision: http://reviews.llvm.org/D13973

llvm-svn: 253107
2015-11-14 00:36:50 +00:00
Anna Zaks de14eb5b4e [static analyzer] Don't flag nil storage into NSMutableDictionary.
This is now allowed and has the behavior of removing the mapping.

llvm-svn: 252679
2015-11-11 00:49:22 +00:00
Devin Coughlin 9c76869bc3 [analyzer] Fix assertion failure invalidating on const member function calls (PR25392).
We now return early when the 'this' value cannot be converted to a MemRegion.

llvm-svn: 252506
2015-11-09 19:50:29 +00:00
Petar Jovanovic 73d1044abe Fix __builtin_signbit for ppcf128 type
Function__builtin_signbit returns wrong value for type ppcf128 on big endian
machines. This patch fixes how value is generated in that case.

Patch by Aleksandar Beserminji.

Differential Revision: http://reviews.llvm.org/D14149

llvm-svn: 252307
2015-11-06 14:52:46 +00:00
Yury Gribov 22b4164e7d [analyzer] Add VforkChecker to find unsafe code in vforked process.
This checker looks for unsafe constructs in vforked process:
function calls (excluding whitelist), memory write and returns.
This was originally motivated by a vfork-related bug in xtables package.

Patch by Yury Gribov.

Differential revision: http://reviews.llvm.org/D14014

llvm-svn: 252285
2015-11-06 11:16:31 +00:00
Devin Coughlin e949add687 [analyzer] Update RegionStoreManager::getBinding to handle BlockDataRegions
Update RegionStoreManager::getBinding() to return UnknownVal when trying to get
the binding for a BlockDataRegion. Previously, getBinding() would try to cast the
BlockDataRegion to a TypedValueRegion and crash. This happened when a block
was passed as a parameter to an inlined function for which
StackHintGeneratorForSymbol::getMessage() tried to generate a stack hint message.

rdar://problem/21291971

llvm-svn: 252185
2015-11-05 18:56:42 +00:00
Devin Coughlin 0500c70beb [analyzer] Add 'optin' checker package and move localizability checkers into it.
This commit creates a new 'optin' top-level checker package and moves several of
the localizability checkers into it.

This package is for checkers that are not alpha and that would normally be on by
default but where the driver does not have enough information to determine when
they are applicable. The localizability checkers fit this criterion because the
driver cannot determine whether a project is localized or not -- this is best
determined at the IDE or build-system level.

This new package is *not* intended for checkers that are too noisy to be on by
default.

The hierarchy under 'optin' mirrors that in 'alpha': checkers under 'optin'
should be organized in the hierarchy they would have had if they were truly top
level (e.g., optin.osx.cocoa.MyOptInChecker).

Differential Revision: http://reviews.llvm.org/D14303

llvm-svn: 252080
2015-11-04 21:33:41 +00:00
Devin Coughlin 6bc780ccc0 [analyzer] Move the ObjCGenericsChecker out of the alpha package.
It is now in the osx.cocoa package and so will be on by default for Apple
toolchains.

llvm-svn: 251966
2015-11-03 19:38:03 +00:00
Sean Eveson 70eece21c2 Reapply r251621 "[Analyzer] Widening loops which do not exit"
It was not the cause of the build bot failure.

llvm-svn: 251702
2015-10-30 15:23:57 +00:00
Sean Eveson 4c7b3bf6ba Revert r251621 "[Analyzer] Widening loops which do not exit" (bot failure)
Seems to be causing clang-cmake-mips build bot to fail (timeout)

http://lab.llvm.org:8011/builders/clang-cmake-mips/builds/10299

llvm-svn: 251697
2015-10-30 11:13:07 +00:00
Sean Eveson 83390e45b3 [Analyzer] Widening loops which do not exit
Summary:
Dear All,

We have been looking at the following problem, where any code after the constant bound loop is not analyzed because of the limit on how many times the same block is visited, as described in bugzillas #7638 and #23438. This problem is of interest to us because we have identified significant bugs that the checkers are not locating. We have been discussing a solution involving ranges as a longer term project, but I would like to propose a patch to improve the current implementation.

Example issue:
```
for (int i = 0; i < 1000; ++i) {...something...}
int *p = 0;
*p = 0xDEADBEEF;
```

The proposal is to go through the first and last iterations of the loop. The patch creates an exploded node for the approximate last iteration of constant bound loops, before the max loop limit / block visit limit is reached. It does this by identifying the variable in the loop condition and finding the value which is “one away” from the loop being false. For example, if the condition is (x < 10), then an exploded node is created where the value of x is 9. Evaluating the loop body with x = 9 will then result in the analysis continuing after the loop, providing x is incremented.

The patch passes all the tests, with some modifications to coverage.c, in order to make the ‘function_which_gives_up’ continue to give up, since the changes allowed the analysis to progress past the loop.

This patch does introduce possible false positives, as a result of not knowing the state of variables which might be modified in the loop. I believe that, as a user, I would rather have false positives after loops than do no analysis at all. I understand this may not be the common opinion and am interested in hearing your views. There are also issues regarding break statements, which are not considered. A more advanced implementation of this approach might be able to consider other conditions in the loop, which would allow paths leading to breaks to be analyzed.

Lastly, I have performed a study on large code bases and I think there is little benefit in having “max-loop” default to 4 with the patch. For variable bound loops this tends to result in duplicated analysis after the loop, and it makes little difference to any constant bound loop which will do more than a few iterations. It might be beneficial to lower the default to 2, especially for the shallow analysis setting.

Please let me know your opinions on this approach to processing constant bound loops and the patch itself.

Regards,

Sean Eveson
SN Systems - Sony Computer Entertainment Group

Reviewers: jordan_rose, krememek, xazax.hun, zaks.anna, dcoughlin

Subscribers: krememek, xazax.hun, cfe-commits

Differential Revision: http://reviews.llvm.org/D12358

llvm-svn: 251621
2015-10-29 10:04:41 +00:00
Anna Zaks fe1eca5169 [analyzer] Assume escape is possible through system functions taking void*
The analyzer assumes that system functions will not free memory or modify the
arguments in other ways, so we assume that arguments do not escape when
those are called. However, this may lead to false positive leak errors. For
example, in code like this where the pointers added to the rb_tree are freed
later on:

		struct alarm_event *e = calloc(1, sizeof(*e));
<snip>

		rb_tree_insert_node(&alarm_tree, e);

Add a heuristic to assume that calls to system functions taking void*
arguments allow for pointer escape.

llvm-svn: 251449
2015-10-27 20:19:45 +00:00
Gabor Horvath ba7d9071fe [analyzer] Fix lambdas that are capturing constants.
llvm-svn: 251407
2015-10-27 13:46:39 +00:00
Gabor Horvath 244d27149a [analyzer] Fix another crash when analyzing lambda functions.
llvm-svn: 251404
2015-10-27 12:36:26 +00:00
Gabor Horvath 2f929b4093 [analyzer] Added a missing test case for r251289.
llvm-svn: 251313
2015-10-26 17:42:14 +00:00
Gabor Horvath b89658f649 Attempt to fix build bot test failures.
llvm-svn: 251014
2015-10-22 13:23:18 +00:00
Gabor Horvath efec16307c [analyzer] Bug identification
This patch adds hashes to the plist and html output to be able to identfy bugs
for suppressing false positives or diff results against a baseline. This hash
aims to be resilient for code evolution and is usable to identify bugs in two
different snapshots of the same software. One missing piece however is a 
permanent unique identifier of the checker that produces the warning. Once that
issue is resolved, the hashes generated are going to change. Until that point
this feature is marked experimental, but it is suitable for early adoption.

Differential Revision: http://reviews.llvm.org/D10305 

Original patch by: Bence Babati!

llvm-svn: 251011
2015-10-22 11:53:04 +00:00
Devin Coughlin 4f770dee54 [analyzer] Don’t invalidate CXXThis when conservatively evaluating const methods (PR 21606)
Prevent invalidation of `this' when a method is const; fixing PR 21606.

A patch by Sean Eveson!

Differential Revision: http://reviews.llvm.org/D13099

llvm-svn: 250237
2015-10-13 22:20:52 +00:00
David Majnemer c10b8381f7 Update tests touched by r249656
These test updates almost exclusively around the change in behavior
around enum: enums without a definition are considered incomplete except
when targeting MSVC ABIs.  Since these tests are interested in the
'incomplete-enum' behavior, restrict them to %itanium_abi_triple.

llvm-svn: 249660
2015-10-08 06:31:22 +00:00
Devin Coughlin 0da2e93345 [analyzer] When memcpy'ing into a fixed-size array, do not invalidate entire region.
Change the analyzer's modeling of memcpy to be more precise when copying into fixed-size
array fields. With this change, instead of invalidating the entire containing region the
analyzer now invalidates only offsets for the array itself when it can show that the
memcpy stays within the bounds of the array.

This addresses false positive memory leak warnings of the kind reported by
krzysztof in https://llvm.org/bugs/show_bug.cgi?id=22954

(This is the second attempt, now with assertion failures resolved.)

A patch by Pierre Gousseau!

Differential Revision: http://reviews.llvm.org/D12571

llvm-svn: 248516
2015-09-24 16:52:56 +00:00
NAKAMURA Takumi 0cc61b2d30 clang/test/Analysis/malloc-overflow2.c: Appease 32-bit targets.
size_t is not unsigned long for targeting i686 (and Windows x64).

llvm-svn: 248458
2015-09-24 02:49:00 +00:00
Devin Coughlin 683dfd3124 [analyzer] Discard malloc-overflow bug-report when a known size is malloc'ed.
This patch ignores malloc-overflow bug in two cases:
Case1:
x = a/b; where n < b
malloc (x*n); Then x*n will not overflow.

Case2:
x = a; // when 'a' is a known value.
malloc (x*n);

Also replaced isa with dyn_cast.

Reject multiplication by zero cases in MallocOverflowSecurityChecker
Currently MallocOverflowSecurityChecker does not catch cases like:
malloc(n * 0 * sizeof(int));

This patch rejects such cases.

Two test cases added. malloc-overflow2.c has an example inspired from a code
in linux kernel where the current checker flags a warning while it should not.

A patch by Aditya Kumar!

Differential Revision: http://reviews.llvm.org/D9924

llvm-svn: 248446
2015-09-23 23:27:55 +00:00
Devin Coughlin 9f21f68bfe [analyzer] Improve localizability checks for iOS / OS X.
Various improvements to the localization checker:
* Adjusted copy to be consistent with diagnostic text in other Apple
  API checkers.
* Added in ~150 UIKit / AppKit methods that require localized strings in
  UnlocalizedStringsChecker.
* UnlocalizedStringChecker now checks for UI methods up the class hierarchy and
  UI methods that conform for a certain Objective-C protocol.
* Added in alpha version of PluralMisuseChecker and some regression tests. False
  positives are still not ideal.

(This is the second attempt, with the memory issues on Linux resolved.)

A patch by Kulpreet Chilana!

Differential Revision: http://reviews.llvm.org/D12417

llvm-svn: 248432
2015-09-23 21:43:21 +00:00
Devin Coughlin 749de2355c Revert "[analyzer] Improve localizability checks for iOS / OS X."
This reverts commit r248350. The pluralization checks are failing on some bots.

llvm-svn: 248351
2015-09-23 00:17:52 +00:00
Devin Coughlin ab58314357 [analyzer] Improve localizability checks for iOS / OS X.
Various improvements to the localization checker:
* Adjusted copy to be consistent with diagnostic text in other Apple
  API checkers.
* Added in ~150 UIKit / AppKit methods that require localized strings in
  UnlocalizedStringsChecker.
* UnlocalizedStringChecker now checks for UI methods up the class hierarchy and
  UI methods that conform for a certain Objective-C protocol.
* Added in alpha version of PluralMisuseChecker and some regression tests. False
  positives are still not ideal.

A patch by Kulpreet Chilana!

Differential Revision: http://reviews.llvm.org/D12417

llvm-svn: 248350
2015-09-22 23:58:04 +00:00
Devin Coughlin 8177173757 [analyzer] Make realloc(ptr, 0) handling equivalent to malloc(0).
Currently realloc(ptr, 0) is treated as free() which seems to be not correct. C
standard (N1570) establishes equivalent behavior for malloc(0) and realloc(ptr,
0): "7.22.3 Memory management functions calloc, malloc, realloc: If the size of
the space requested is zero, the behavior is implementation-defined: either a
null pointer is  returned, or the behavior is as if the size were some nonzero
value, except that the returned pointer shall not be used to access an object."
The patch equalizes the processing of malloc(0) and realloc(ptr,0). The patch
also enables unix.Malloc checker to detect references to zero-allocated memory
returned by realloc(ptr,0) ("Use of zero-allocated memory" warning).

A patch by Антон Ярцев!

Differential Revision: http://reviews.llvm.org/D9040

llvm-svn: 248336
2015-09-22 22:47:14 +00:00
Devin Coughlin eb538abfbd [analyzer] Create one state for a range switch case instead of multiple.
This fixes PR16833, in which the analyzer was using large amounts of memory
for switch statements with large case ranges.

rdar://problem/14685772

A patch by Aleksei Sidorin!

Differential Revision: http://reviews.llvm.org/D5102

llvm-svn: 248318
2015-09-22 20:31:19 +00:00
Ismail Pazarbasi d60db64e7d Analyzer: Teach analyzer how to handle TypeTraitExpr
Summary:
`TypeTraitExpr`s are not supported by the ExprEngine today. Analyzer
creates a sink, and aborts the block. Therefore, certain bugs that
involve type traits intrinsics cannot be detected (see PR24710).

This patch creates boolean `SVal`s for `TypeTraitExpr`s, which are
evaluated by the compiler.

Test within the patch is a summary of PR24710.

Reviewers: zaks.anna, dcoughlin, krememek

Subscribers: cfe-commits

Differential Revision: http://reviews.llvm.org/D12482

llvm-svn: 248314
2015-09-22 19:33:15 +00:00
Gabor Horvath 659842d0fc [Static Analyzer] Fixed a false positive case in DynamicTypeChecker when dealing with forward declarations.
llvm-svn: 248065
2015-09-18 23:38:57 +00:00
Ismail Pazarbasi d347e7a920 Analyzer: Fix a crasher in UbigraphViz
Summary:
Name `Out` refers to the parameter. It is moved into the member `Out`
in ctor-init. Dereferencing null pointer will crash clang, if user
passes '-analyzer-viz-egraph-ubigraph' argument.

Reviewers: zaks.anna, krememek

Subscribers: cfe-commits

Differential Revision: http://reviews.llvm.org/D12119

llvm-svn: 248050
2015-09-18 21:54:47 +00:00
Gabor Horvath dce40c518d [Static Analyzer] General type checker based on dynamic type information.
Differential Revision: http://reviews.llvm.org/D12973

llvm-svn: 248041
2015-09-18 21:15:37 +00:00
Gabor Horvath c4b28a8f74 [analyzer] A fix for substraction of an integer from a pointer.
Patch by Artem Dergachev!

Differential Revision: http://reviews.llvm.org/D12725

llvm-svn: 248021
2015-09-18 19:13:22 +00:00
Gabor Horvath 6165d31a83 [Static Analyzer] Use generics related information to infer dynamic types.
Differential Revision: http://reviews.llvm.org/D12916

llvm-svn: 248002
2015-09-18 16:43:27 +00:00
Gabor Horvath 3ef9ef2227 [Static Analyzer] Generics Checker: When an ObjC method returns a specialized object, track it properly.
Differential Revision: http://reviews.llvm.org/D12889

llvm-svn: 247861
2015-09-16 22:44:36 +00:00
Devin Coughlin e39bd407ba [analyzer] Add generateErrorNode() APIs to CheckerContext.
The analyzer trims unnecessary nodes from the exploded graph before reporting
path diagnostics. However, in some cases it can trim all nodes (including the
error node), leading to an assertion failure (see
https://llvm.org/bugs/show_bug.cgi?id=24184).

This commit addresses the issue by adding two new APIs to CheckerContext to
explicitly create error nodes. Unless the client provides a custom tag, these
APIs tag the node with the checker's tag -- preventing it from being trimmed.
The generateErrorNode() method creates a sink error node, while
generateNonFatalErrorNode() creates an error node for a path that should
continue being explored.

The intent is that one of these two methods should be used whenever a checker
creates an error node.

This commit updates the checkers to use these APIs. These APIs
(unlike addTransition() and generateSink()) do not take an explicit Pred node.
This is because there are not any error nodes in the checkers that were created
with an explicit different than the default (the CheckerContext's Pred node).

It also changes generateSink() to require state and pred nodes (previously
these were optional) to reduce confusion.

Additionally, there were several cases where checkers did check whether a
generated node could be null; we now explicitly check for null in these places.

This commit also includes a test case written by Ying Yi as part of
http://reviews.llvm.org/D12163 (that patch originally addressed this issue but
was reverted because it introduced false positive regressions).

Differential Revision: http://reviews.llvm.org/D12780

llvm-svn: 247859
2015-09-16 22:03:05 +00:00
Gabor Horvath 6864cbced6 [Static Analyzer] Added an XFAIL test for inlining when the type inference involves generic types.
llvm-svn: 247739
2015-09-15 23:14:01 +00:00
Devin Coughlin ca5ab2b0d4 [analyzer] Skip Pre/Post handlers for ObjC calls when receiver is nil.
In Objective-C, method calls with nil receivers are essentially no-ops. They
do not fault (although the returned value may be garbage depending on the
declared return type and architecture). Programmers are aware of this
behavior and will complain about a false alarm when the analyzer
diagnoses API violations for method calls when the receiver is known to
be nil.

Rather than require each individual checker to be aware of this behavior
and suppress a warning when the receiver is nil, this commit
changes ExprEngineObjC so that VisitObjCMessage skips calling checker
pre/post handlers when the receiver is definitely nil. Instead, it adds a
new event, ObjCMessageNil, that is only called in that case.

The CallAndMessageChecker explicitly cares about this case, so I've changed it
to add a callback for ObjCMessageNil and moved the logic in PreObjCMessage
that handles nil receivers to the new callback.

rdar://problem/18092611

Differential Revision: http://reviews.llvm.org/D12123

llvm-svn: 247653
2015-09-15 01:13:53 +00:00
Gabor Horvath dfedc0f884 [Static Analyzer] Moving nullability checkers out of alpha.
llvm-svn: 247595
2015-09-14 18:48:55 +00:00
Gabor Horvath 2930735c1e [Static Analyzer] Moving nullability checkers to a top level package.
Differential Revision: http://reviews.llvm.org/D12852

llvm-svn: 247590
2015-09-14 18:31:34 +00:00
Gabor Horvath c0c7a5df6e [Static Analyzer] Merge the Objective-C Generics Checker into Dynamic Type Propagation checker.
Differential Revision: http://reviews.llvm.org/D12381

llvm-svn: 247532
2015-09-13 23:02:24 +00:00
Devin Coughlin 0123af994e [analyzer] Add -analyzer-config option for function size the inliner considers as large
Add an option (-analyzer-config min-blocks-for-inline-large=14) to control the function
size the inliner considers as large, in relation to "max-times-inline-large". The option
defaults to the original hard coded behaviour, which I believe should be adjustable with
the other inlining settings.

The analyzer-config test has been modified so that the analyzer will reach the
getMinBlocksForInlineLarge() method and store the result in the ConfigTable, to ensure it
is dumped by the debug checker.

A patch by Sean Eveson!

Differential Revision: http://reviews.llvm.org/D12406

llvm-svn: 247463
2015-09-11 20:14:05 +00:00
Gabor Horvath 15843343b6 [Static Analyzer] Lambda support.
Differential Revision: http://reviews.llvm.org/D12652

llvm-svn: 247426
2015-09-11 16:55:01 +00:00
Devin Coughlin 00691e3169 Revert "[Static Analyzer] BugReporter.cpp:2869: Assertion failed: !RemainingNodes.empty() && "No error node found in the trimmed graph""
This is making our internal build bot fail because it results in extra warnings being
emitted past what should be sink nodes. (There is actually an example of this in the
updated malloc.c test in the reverted commit.)

I'm working on a patch to fix the original issue by adding a new checker API to explicitly
create error nodes. This API will ensure that error nodes are always tagged in order to
prevent them from being reclaimed.

This reverts commit r246188.

llvm-svn: 247103
2015-09-08 23:50:22 +00:00
Gabor Horvath 1cbf435cd6 [Static Analyzer] Objective-C Generics Checker improvements.
Differential Revision: http://reviews.llvm.org/D12701

llvm-svn: 247071
2015-09-08 21:04:14 +00:00
Gabor Horvath b47128aaf3 [Static Analyzer] Remove sinks from nullability checks.
Differential Revision: http://reviews.llvm.org/D12445 

llvm-svn: 246818
2015-09-03 23:16:21 +00:00
Gabor Horvath 742fd989b5 Revert r246345 until an assertion is fixed.
llvm-svn: 246479
2015-08-31 20:10:35 +00:00
Devin Coughlin 35d5dd2986 [analyzer] When memcpy'ing into a fixed-size array, do not invalidate entire region.
Change the analyzer's modeling of memcpy to be more precise when copying into fixed-size
array fields. With this change, instead of invalidating the entire containing region the
analyzer now invalidates only offsets for the array itself when it can show that the
memcpy stays within the bounds of the array.

This addresses false positive memory leak warnings of the kind reported by
krzysztof in https://llvm.org/bugs/show_bug.cgi?id=22954

A patch by Pierre Gousseau!

Differential Revision: http://reviews.llvm.org/D11832

llvm-svn: 246345
2015-08-28 22:26:05 +00:00
Gabor Horvath e9984b28ef [Static Analyzer] BugReporter.cpp:2869: Assertion failed: !RemainingNodes.empty() && "No error node found in the trimmed graph"
The assertion is caused by reusing a “filler” ExplodedNode as an error node.
The “filler” nodes are only used for intermediate processing and are not
essential for analyzer history, so they can be reclaimed when the
ExplodedGraph is trimmed by the “collectNode” function. When a checker finds a
bug, they generate a new transition in the ExplodedGraph. The analyzer will
try to reuse the existing predecessor node. If it cannot, it creates a new
ExplodedNode, which always has a tag to uniquely identify the creation site.
The assertion is caused when the analyzer reuses a “filler” node.

In the test case, some “filler” nodes were reused and then reclaimed later
when the ExplodedGraph was trimmed. This caused an assertion because the node
was needed to generate the report. The “filler” nodes should not be reused as
error nodes. The patch adds a constraint to prevent this happening, which
solves the problem and makes the test cases pass.

Differential Revision: http://reviews.llvm.org/D11433

Patch by Ying Yi!

llvm-svn: 246188
2015-08-27 18:57:00 +00:00
Charles Li 430db1e717 [Tests] Modified Lit Tests to be C++11 compatibile
This 2nd patch should not change the test results, but it is useful if clang's
default C++ language is ever changed from gnu++98.

llvm-svn: 246183
2015-08-27 18:49:15 +00:00
Gabor Horvath 8d3ad6b617 [Static Analyzer] Make NonNullParamChecker emit implicit null dereference events.
Differential Revision: http://reviews.llvm.org/D11433

llvm-svn: 246182
2015-08-27 18:49:07 +00:00
Gabor Horvath 28690925ed [Static Analyzer] Checks to catch nullability related issues.
Differential Revision: http://reviews.llvm.org/D11468

llvm-svn: 246105
2015-08-26 23:17:43 +00:00
Gabor Horvath 03dc473385 [Static Analyzer] Fix tests to reflect the change in the diagnostic message.
llvm-svn: 245951
2015-08-25 16:38:05 +00:00
Gabor Horvath 717b51c821 [Static Analyzer] Add checker to catch lightweight generics related type errors in Objective-C.
Differential Revision: http://reviews.llvm.org/D11427

llvm-svn: 245646
2015-08-21 00:18:28 +00:00
Aaron Ballman 6569387327 Do not crash when static analysis encounters a FunctionDecl that has a delayed template parse of its body.
llvm-svn: 245616
2015-08-20 21:27:35 +00:00
Anna Zaks e5d74caf2a [analyzer] Add checkers for OS X / iOS localizability issues
Add checkers that detect code-level localizability issues for OS X / iOS:
  - A path sensitive checker that warns about uses of non-localized
    NSStrings passed to UI methods expecting localized strings.
  - A syntax checker that warns against not including a comment in
    NSLocalizedString macros.

A patch by Kulpreet Chilana!

(This is the second attempt with the compilation issue on Windows and
the random test failures resolved.)

llvm-svn: 245093
2015-08-14 20:22:22 +00:00
Daniel Marjamaki 30e2a44a06 [Static Analyzer] Warn when inner and outer conditions are identical. The inner condition is always true.
Reviewed in http://reviews.llvm.org/D10892.

llvm-svn: 244435
2015-08-10 07:18:29 +00:00
Anna Zaks 9592df7901 Revert "[analyzer] Add checkers for OS X / iOS localizability issues"
This reverts commit fc885033a30b6e30ccf82398ae7c30e646727b10.

Revert all localization checker commits until the proper fix is implemented.

llvm-svn: 244394
2015-08-08 04:53:04 +00:00
Anna Zaks 38b496a05d [analyzer] Add checkers for OS X / iOS localizability issues
Add checkers that detect code-level localizability issues for OS X / iOS:
 - A path sensitive checker that warns about uses of non-localized
 NSStrings passed to UI methods expecting localized strings.
 - A syntax checker that warns against not including a comment in
 NSLocalizedString macros.

A patch by Kulpreet Chilana!

llvm-svn: 244389
2015-08-08 01:49:26 +00:00
Devin Coughlin de2cc01cd4 [analyzer] Don't issue alarm in ObjCSuperCallChecker for the super class itself.
The ObjCSuperCallChecker issues alarms for various Objective-C APIs that require
a subclass to call to its superclass's version of a method when overriding it.
So, for example, it raises an alarm when the -viewDidLoad method in a subclass
of UIViewController does not call [super viewDidLoad].

This patch fixes a false alarm where the analyzer erroneously required the
implementation of the superclass itself (e.g., UIViewController) to call
super.

rdar://problem/18416944

Differential Revision: http://reviews.llvm.org/D11842

llvm-svn: 244386
2015-08-08 01:31:51 +00:00
Tanya Lattner 4a08e931b6 Update mailing list references to lists.llvm.org
llvm-svn: 244000
2015-08-05 03:55:23 +00:00
Gabor Horvath 5311a0b363 [Static Analyzer] Some tests do not turn on core checkers. Running the analyzers without the core checkers is not supported.
Differential Revision: http://reviews.llvm.org/D11432

llvm-svn: 243088
2015-07-24 03:25:13 +00:00
Jordan Rose 9503501dae [analyzer] When forced to fake a block type, do it correctly.
BlockDecl has a poor AST representation because it doesn't carry its type
with it. Instead, the containing BlockExpr has the full type. This almost
never matters for the analyzer, but if the block decl contains static
local variables we need to synthesize a region to put them in, and this
region will necessarily not have the right type.

Even /that/ doesn't matter, unless

(1) the block calls the function or method containing the block, and
(2) the value of the block expr is used in some interesting way.

In this case, we actually end up needing the type of the block region,
and it will be set to our synthesized type. It turns out we've been doing
a terrible job faking that type -- it wasn't a block pointer type at all.
This commit fixes that to at least guarantee a block pointer type, using
the signature written by the user if there is one.

This is not really a correct answer because the block region's type will
/still/ be wrong, but further efforts to make this right in the analyzer
would probably be silly. We should just change the AST.

rdar://problem/21698099

llvm-svn: 241944
2015-07-10 21:41:59 +00:00
Gabor Horvath fc4c4d4441 [Static Analyzer] Basic per checker command line option validation.
Differential Revision: http://reviews.llvm.org/D8077

llvm-svn: 241863
2015-07-09 21:43:45 +00:00
Anna Zaks 3849dea8c9 [static analyzer] Analyzer is skipping forward declared C/C++ functions
A patch by Karthik Bhat!

This patch fixes a regression introduced by r224398. Prior to r224398
we were able to analyze the following code in test-include.c and report
a null deref in this case. But post r224398 this analysis is being skipped.

E.g.
  // test-include.c
  #include "test-include.h"
  void test(int * data) {
    data = 0;
    *data = 1;
  }

   // test-include.h
  void test(int * data);

This patch uses the function body (instead of its declaration) as the location
of the function when deciding if the Decl should be analyzed with path-sensitive
analysis. (Prior to r224398, the call graph was guaranteed to have a definition
when available.)

llvm-svn: 240800
2015-06-26 17:42:58 +00:00
Daniel Marjamaki 0dadfa8d05 Fix a crash by division by zero in analyzer
Patch by takeshi-yoshimura!

Differential Revision: http://reviews.llvm.org/D10145

llvm-svn: 240643
2015-06-25 14:06:02 +00:00
Douglas Gregor aea7afdc13 Replace __double_underscored type nullability qualifiers with _Uppercase_underscored
Addresses a conflict with glibc's __nonnull macro by renaming the type
nullability qualifiers as follows:

  __nonnull -> _Nonnull
  __nullable -> _Nullable
  __null_unspecified -> _Null_unspecified

This is the major part of rdar://problem/21530726, but does not yet
provide the Darwin-specific behavior for the old names.

llvm-svn: 240596
2015-06-24 22:02:08 +00:00
Douglas Gregor 9960a8638d CF_RETURNS_[NOT_]RETAINED on a param makes the inner pointer __nullable.
That is,

  void cf2(CFTypeRef * __nullable p CF_RETURNS_NOT_RETAINED);

is equivalent to

  void cf2(CFTypeRef __nullable * __nullable p CF_RETURNS_NOT_RETAINED);

More rdar://problem/18742441

llvm-svn: 240186
2015-06-19 23:17:51 +00:00
Douglas Gregor eb6e64ca8f Allow the cf_returns_[not_]retained attributes to appear on out-parameters.
Includes a simple static analyzer check and not much else, but we'll also
be able to take advantage of this in Swift.

This feature can be tested for using __has_feature(cf_returns_on_parameters).

This commit also contains two fixes:
- Look through non-typedef sugar when deciding whether something is a CF type.
- When (cf|ns)_returns(_not)?_retained is applied to invalid properties,
  refer to "property" instead of "method" in the error message.

rdar://problem/18742441

llvm-svn: 240185
2015-06-19 23:17:46 +00:00
Devin Coughlin 0bee1d7ff1 [analyzer] Remove ObjCContainersChecker size information when a CFMutableArrayRef escapes
Update ObjCContainersChecker to be notified when pointers escape so it can
remove size information for escaping CFMutableArrayRefs. When such pointers
escape, un-analyzed code could mutate the array and cause the size information
to be incorrect.

rdar://problem/19406485

llvm-svn: 239709
2015-06-15 01:00:42 +00:00
Yunzhong Gao cb77930d6b Implementing C99 partial re-initialization behavior (DR-253)
Based on previous discussion on the mailing list, clang currently lacks support
for C99 partial re-initialization behavior:
Reference: http://lists.cs.uiuc.edu/pipermail/cfe-dev/2013-April/029188.html
Reference: http://www.open-std.org/jtc1/sc22/wg14/www/docs/dr_253.htm

This patch attempts to fix this problem.

Given the following code snippet,

struct P1 { char x[6]; };
struct LP1 { struct P1 p1; };

struct LP1 l = { .p1 = { "foo" }, .p1.x[2] = 'x' };
// this example is adapted from the example for "struct fred x[]" in DR-253;
// currently clang produces in l: { "\0\0x" },
//   whereas gcc 4.8 produces { "fox" };
// with this fix, clang will also produce: { "fox" };


Differential Review: http://reviews.llvm.org/D5789

llvm-svn: 239446
2015-06-10 00:27:52 +00:00
Ismail Pazarbasi e5768d1717 Detect uses of mismatching forms of 'new' and 'delete'
Emit warning when operand to `delete` is allocated with `new[]` or
operand to `delete[]` is allocated with `new`.

rev 2 update:
`getNewExprFromInitListOrExpr` should return `dyn_cast_or_null`
instead of `dyn_cast`, since `E` might be null.

Reviewers: rtrieu, jordan_rose, rsmith

Subscribers: majnemer, cfe-commits

Differential Revision: http://reviews.llvm.org/D4661

llvm-svn: 237608
2015-05-18 19:59:11 +00:00
Diego Novillo c324b92c35 Revert "Detect uses of mismatching forms of 'new' and 'delete'"
This reverts commit 742dc9b6c9686ab52860b7da39c3a126d8a97fbc.

This is generating multiple segfaults in our internal builds.
Test case coming up shortly.

llvm-svn: 237391
2015-05-14 20:57:48 +00:00
Ismail Pazarbasi 538ef53c13 Detect uses of mismatching forms of 'new' and 'delete'
Emit warning when operand to `delete` is allocated with `new[]` or
operand to `delete[]` is allocated with `new`.

Reviewers: rtrieu, jordan_rose, rsmith

Subscribers: majnemer, cfe-commits

Differential Revision: http://reviews.llvm.org/D4661

llvm-svn: 237368
2015-05-14 16:14:57 +00:00
Anton Yartsev b50f4ba461 [analyzer] This implements potential undefbehavior.ZeroAllocDereference checker.
TODO: support realloc(). Currently it is not possible due to the present realloc() handling. Currently RegionState is not being attached to realloc() in case of a zero Size argument. 
llvm-svn: 234889
2015-04-14 14:18:04 +00:00
Jordan Rose ad176b5e10 [analyzer] Add test for previous commit.
Again, this is being applied in a separate commit so that the previous commit
can be reverted while leaving the test in place.

rdar://problem/20335433

llvm-svn: 233593
2015-03-30 20:18:04 +00:00
Jordan Rose 3da3f8e045 [analyzer] Disable all retain count diagnostics on values that come from ivars.
This is imitating a pre-r228174 state where ivars are not considered tracked by
default, but with the addition that even ivars /with/ retain count information
(e.g. "[_ivar retain]; [ivar _release];") are not being tracked as well. This is
to ensure that we don't regress on values accessed through both properties and
ivars, which is what r228174 was trying to fix.

The issue occurs in code like this:

  [_contentView retain];
  [_contentView removeFromSuperview];
  [self addSubview:_contentView]; // invalidates 'self'
  [_contentView release];

In this case, the call to -addSubview: may change the value of self->_contentView,
and so the analyzer can't be sure that we didn't leak the original _contentView.
This is a correct conservative view of the world, but not a useful one. Until we
have a heuristic that allows us to not consider this a leak, not emitting a
diagnostic is our best bet.

This commit disables all of the ivar-related retain count tests, but does not
remove them to ensure that we don't crash trying to evaluate either valid or
erroneous code. The next commit will add a new test for the example above so
that this commit (and the previous one) can be reverted wholesale when a better
solution is implemented.

Rest of rdar://problem/20335433

llvm-svn: 233592
2015-03-30 20:18:00 +00:00
Jordan Rose 218772f87e [analyzer] Don't special-case ivars backing +0 properties.
Give up this checking in order to continue tracking that these values came from
direct ivar access, which will be important in the next commit.

Part of rdar://problem/20335433

llvm-svn: 233591
2015-03-30 20:17:47 +00:00
Eli Bendersky 5f4d76efd3 Record correct source range for defaulted/deleted members.
Fixes https://llvm.org/bugs/show_bug.cgi?id=20744

struct A {

A() = default;
};

Previously the source range of the declaration of A ended at the ')'. It should
include the '= default' part as well. The same for '= delete'.

Note: this will break one of the clang-tidy fixers, which is going to be
addessed in a follow-up patch.

Differential Revision: http://reviews.llvm.org/D8465

llvm-svn: 233028
2015-03-23 21:43:28 +00:00
Jordan Rose 03ad616143 [analyzer] RetainCountChecker: Don't assume +0 for ivars backing readonly properties.
Similarly, don't assume +0 if the property's setter is manually implemented.
In both cases, if the property's ownership is explicitly written, then we /do/
assume the ivar has the same ownership.

rdar://problem/20218183

llvm-svn: 232849
2015-03-20 21:12:27 +00:00
Ed Schouten e5bdc8516e Enable security checks for arc4random() on CloudABI as well.
CloudABI also supports the arc4random() function. We can enable compiler
warnings for rand(), random() and *rand48() on this system as well.

llvm-svn: 231914
2015-03-11 08:48:55 +00:00
Jordan Rose 58f8cc15c9 [analyzer] RetainCountChecker: CF properties are always manually retain-counted.
In theory we could assume a CF property is stored at +0 if there's not a custom
setter, but that's not really worth the complexity. What we do know is that a
CF property can't have ownership attributes, and so we shouldn't assume anything
about the ownership of the ivar.

rdar://problem/20076963

llvm-svn: 231553
2015-03-07 05:47:24 +00:00
Anton Yartsev 9907fc9053 [analyzer] Bug fix: do not report leaks for alloca()
llvm-svn: 231314
2015-03-04 23:18:21 +00:00
Gabor Horvath e40c71c10a [analyzer] Individual configuration options can be specified for checkers.
Reviewed by: Anna Zaks

Original patch by: Aleksei Sidorin

Differential Revision: http://reviews.llvm.org/D7905

llvm-svn: 231266
2015-03-04 17:59:34 +00:00
Reid Kleckner acbd23adf1 Remove shell requirements from tests that use 'cd'
Modules and Tooling tests in particular tend to want to change the cwd,
so we were missing test coverage in this area on Windows. It should now
be easier to write such portable tests.

llvm-svn: 231029
2015-03-02 22:42:58 +00:00
Jordan Rose 000bac5e17 [analyzer] RetainCountChecker: don't try to track ivars known to be nil.
We expect in general that any nil value has no retain count information
associated with it; violating this results in unexpected state unification
/later/ when we decide to throw the information away. Unexpectedly caching
out can lead to an assertion failure or crash.

rdar://problem/19862648

llvm-svn: 229934
2015-02-19 23:57:04 +00:00
Anton Yartsev 5b5c7cec08 [analyzer] Different handling of alloca().
+ separate bug report for "Free alloca()" error to be able to customize checkers responsible for this error.
+ Muted "Free alloca()" error for NewDelete checker that is not responsible for c-allocated memory, turned on for unix.MismatchedDeallocator checker.
+ RefState for alloca() - to be able to detect usage of zero-allocated memory by upcoming ZeroAllocDereference checker.
+ AF_Alloca family to handle alloca() consistently - keep proper family in RefState, handle 'alloca' by getCheckIfTracked() facility, etc.
+ extra tests.

llvm-svn: 229850
2015-02-19 13:36:20 +00:00
Pete Cooper 05df16d809 Fix REQUIRES lines on tests from r228735. Thanks Kristof for pointing out the missing commas
llvm-svn: 228870
2015-02-11 19:45:13 +00:00
Pete Cooper 7dc8af5306 Check for backtraces in tests which are verifying pretty stack traces from a crashing clang.
PrettyStackTrace now requires the ENABLE_BACKTRACES option.  We need to check for that here or these tests fail llvm-lit.

Reviewed by chandlerc

llvm-svn: 228735
2015-02-10 19:53:38 +00:00
Gabor Horvath c18a11397c [Static Analyzer] The name of the checker that reports a bug is added
to the plist output. This check_name field does not guaranteed to be the
same as the name of the checker in the future.

Reviewer: Anna Zaks

Differential Revision: http://reviews.llvm.org/D6841

llvm-svn: 228624
2015-02-09 22:52:26 +00:00
Anna Zaks f4c7ce8a37 [analyzer] Relax an assertion in VisitLvalArraySubscriptExpr
The analyzer thinks that ArraySubscriptExpr cannot be an r-value (ever).
However, it can be in some corner cases. Specifically, C forbids expressions
of unqualified void type from being l-values.

Note, the analyzer will keep modeling the subscript expr as an l-value. The
analyzer should be treating void* as a char array
(https://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Pointer-Arith.html).

llvm-svn: 228249
2015-02-05 01:02:59 +00:00
Anna Zaks 33f0632640 [analyzer] Do not crash in the KeychainAPI checker on user defined 'free()'.
llvm-svn: 228248
2015-02-05 01:02:56 +00:00
Anna Zaks 486a0ff4b7 [analyzer] Look for allocation site in the parent frames as well as the current one.
Instead of handling edge cases (mostly involving blocks), where we have difficulty finding
an allocation statement, allow the allocation site to be in a parent node.

Previously we assumed that the allocation site can always be found in the same frame
as allocation, but there are scenarios in which an element is leaked in a child
frame but is allocated in the parent.

llvm-svn: 228247
2015-02-05 01:02:53 +00:00