Commit Graph

1940 Commits

Author SHA1 Message Date
Jordan Rose 3b4c3ea2fb [analyzer] Use SymExprs to represent '<loc> - <loc>' and '<loc> == <loc>'.
We just treat this as opaque symbols, but even that allows us to handle
simple cases where the same condition is tested twice. This is very common
in the STL, which means that any project using the STL gets spurious errors.

Part of <rdar://problem/13239003>.

llvm-svn: 177800
2013-03-23 01:21:05 +00:00
Anna Zaks 130df4b0a4 [analyzer] Warn when a nil key or value are passed to NSMutableDictionary and ensure it works with subscripting.
llvm-svn: 177789
2013-03-23 00:39:21 +00:00
Ted Kremenek 21c29e5713 Add test case for PR 12921.
llvm-svn: 177767
2013-03-22 21:30:22 +00:00
Jordan Rose 08821c84da [analyzer] Fix test to actually test what was intended.
llvm-svn: 177763
2013-03-22 21:15:26 +00:00
Jordan Rose 28c68a2d07 [analyzer] Don't invalidate globals when there's no call involved.
This fixes some mistaken condition logic in RegionStore that caused
global variables to be invalidated when /any/ region was invalidated,
rather than only as part of opaque function calls. This was only
being used by CStringChecker, and so users will now see that strcpy()
and friends do not invalidate global variables.

Also, add a test case we don't handle properly: explicitly-assigned
global variables aren't being invalidated by opaque calls. This is
being tracked by <rdar://problem/13464044>.

llvm-svn: 177572
2013-03-20 20:36:01 +00:00
Jordan Rose 5d22fcb257 [analyzer] Track malloc'd memory into struct fields.
Due to improper modelling of copy constructors (specifically, their
const reference arguments), we were producing spurious leak warnings
for allocated memory stored in structs. In order to silence this, we
decided to consider storing into a struct to be the same as escaping.
However, the previous commit has fixed this issue and we can now properly
distinguish leaked memory that happens to be in a struct from a buffer
that escapes within a struct wrapper.

Originally applied in r161511, reverted in r174468.
<rdar://problem/12945937>

llvm-svn: 177571
2013-03-20 20:35:57 +00:00
Jordan Rose 5413aaa791 [analyzer] Invalidate regions indirectly accessible through const pointers.
In this case, the value of 'x' may be changed after the call to indirectAccess:

  struct Wrapper {
    int *ptr;
  };

  void indirectAccess(const Wrapper &w);

  void test() {
    int x = 42;
    Wrapper w = { x };

    clang_analyzer_eval(x == 42); // TRUE
    indirectAccess(w);
    clang_analyzer_eval(x == 42); // UNKNOWN
  }

This is important for modelling return-by-value objects in C++, to show
that the contents of the struct are escaping in the return copy-constructor.

<rdar://problem/13239826>

llvm-svn: 177570
2013-03-20 20:35:53 +00:00
Jordan Rose 25132d5156 [analyzer] Add an integer version of the Circle tests in uninit-vals.m.
A floating-point version is nice for testing unknown values, but it's
good to be able to check all parts of the structure as well.

Test change only, no functionality change.

llvm-svn: 177455
2013-03-19 23:01:57 +00:00
Anna Zaks 3f4fad92fe [analyzer] Do not believe lazy binding when symbolic region types do not match
This fixes a crash when analyzing LLVM that was exposed by r177220 (modeling of
trivial copy/move assignment operators).

When we look up a lazy binding for “Builder”, we see the direct binding of Loc at offset 0.
Previously, we believed the binding, which led to a crash. Now, we do not believe it as
the types do not match.

llvm-svn: 177453
2013-03-19 22:38:09 +00:00
Jordan Rose 15a185f1e0 [analyzer] Add a test case for diagnostic suppression on a graph with cycles.
(see previous commit)

llvm-svn: 177449
2013-03-19 22:10:44 +00:00
Anna Zaks 6457ad2335 [analyzer] Warn when a ‘nil’ object is added to NSArray or NSMutableArray.
llvm-svn: 177318
2013-03-18 20:46:56 +00:00
Jordan Rose 3d7b7f5268 [analyzer] Model trivial copy/move assignment operators with a bind as well.
r175234 allowed the analyzer to model trivial copy/move constructors as
an aggregate bind. This commit extends that to trivial assignment
operators as well. Like the last commit, one of the motivating factors here
is not warning when the right-hand object is partially-initialized, which
can have legitimate uses.

<rdar://problem/13405162>

llvm-svn: 177220
2013-03-16 02:14:06 +00:00
Anna Zaks bda130f02a [analyzer] Use isLiveRegion to determine when SymbolRegionValue is dead.
Fixes a FIXME, improves dead symbol collection, suppresses a false positive,
which resulted from reusing the same symbol twice for simulation of 2 calls to the same function.

Fixing this lead to 2 possible false negatives in CString checker. Since the checker is still alpha and
the solution will not require revert of this commit, move the tests to a FIXME section.

llvm-svn: 177206
2013-03-15 23:34:29 +00:00
Anna Zaks e0f1a0f0d8 [analyzer] BugReporterVisitors: handle the case where a ternary operator is wrapped in a cast.
llvm-svn: 177205
2013-03-15 23:34:25 +00:00
Jordan Rose ecaa7d2c3d [analyzer] Look through ExprWhenCleanups when trying to track a NULL.
Silences a few false positives in LLVM.

llvm-svn: 177186
2013-03-15 21:41:46 +00:00
Anna Zaks 913b0d0078 [analyzer] Teach trackNullOrUndef to look through ternary operators
Allows the suppression visitors trigger more often.

llvm-svn: 177137
2013-03-15 01:15:12 +00:00
Anna Zaks 2672a4cc0c [analyzer] Change the way in which IDC Visitor decides to kick in and make sure it attaches in the given edge case
In the test case below, the value V is not constrained to 0 in ErrorNode but it is in node N.
So we used to fail to register the Suppression visitor.

We also need to change the way we determine that the Visitor should kick in because the node N belongs to
the ExplodedGraph and might not be on the BugReporter path that the visitor sees. Instead of trying to match the node,
turn on the visitor when we see the last node in which the symbol is ‘0’.

llvm-svn: 177121
2013-03-14 22:31:56 +00:00
Jordan Rose 529e239aee [analyzer] Fix scan-build's -stats mode.
We were failing to match the output line, which led to us collecting no
stats at all, which led to a divide-by-zero error.

Fixes PR15510.

llvm-svn: 177084
2013-03-14 17:18:30 +00:00
Anna Zaks e9989bd4df [analyzer] BugReporter - more precise tracking of C++ references
When BugReporter tracks C++ references involved in a null pointer violation, we
want to differentiate between a null reference and a reference to a null pointer. In the
first case, we want to track the region for the reference location; in the second, we want
to track the null pointer.

In addition, the core creates CXXTempObjectRegion to represent the location of the
C++ reference, so teach FindLastStoreBRVisitor about it.

This helps null pointer suppression to kick in.

(Patch by Anna and Jordan.)

llvm-svn: 176969
2013-03-13 20:20:14 +00:00
Ted Kremenek 2fb5f09e15 [analyzer] Handle Objc Fast enumeration for "loop is executed 0 times".
Fixes <rdar://problem/12322528>

llvm-svn: 176965
2013-03-13 20:03:31 +00:00
Jan Wen Voung 183ced44fe Partly revert "Move clang tests that depend on llvm/ADT/Statistic.h to a subdir".
This reverts commit 176730, and uses "REQUIRES: asserts" instead.

llvm-svn: 176815
2013-03-11 17:48:03 +00:00
Anna Zaks 5497d1a55c [analyzer] Make Suppress IDC checker aware that it might not start from the same node it was registered at
The visitor used to assume that the value it’s tracking is null in the first node it examines. This is not true.
If we are registering the Suppress Inlined Defensive checks visitor while traversing in another visitor
(such as FindlastStoreVisitor). When we restart with the IDC visitor, the invariance of the visitor does
not hold since the symbol we are tracking no longer exists at that point.

I had to pass the ErrorNode when creating the IDC visitor, because, in some cases, node N is
neither the error node nor will be visible along the path (we had not finalized the path at that point
and are dealing with ExplodedGraph.)

We should revisit the other visitors which might not be aware that they might get nodes, which are
later in path than the trigger point.

This suppresses a number of inline defensive checks in JavaScriptCore.

llvm-svn: 176756
2013-03-09 03:23:19 +00:00
Anna Zaks ef89339986 [analyzer] Rename AttrNonNullChecker -> NonNullParamChecker
llvm-svn: 176755
2013-03-09 03:23:14 +00:00
Anna Zaks cdbca7ae77 [analyzer] Add test case for reference to null pointer param check
This tests that we track the original Expr if getDerefExpr fails.

llvm-svn: 176754
2013-03-09 03:23:10 +00:00
Jordan Rose 613f3c0022 [analyzer] Be more consistent about Objective-C methods that free memory.
Previously, MallocChecker's pointer escape check and its post-call state
update for Objective-C method calls had a fair amount duplicated logic
and not-entirely-consistent checks. This commit restructures all this to
be more consistent and possibly allow us to be more aggressive in warning
about double-frees.

New policy (applies to system header methods only):
(1) If this is a method we know about, model it as taking/holding ownership
    of the passed-in buffer.
  (1a) ...unless there's a "freeWhenDone:" parameter with a zero (NO) value.
(2) If there's a "freeWhenDone:" parameter (but it's not a method we know
    about), treat the buffer as escaping if the value is non-zero (YES) and
    non-escaping if it's zero (NO).
(3) If the first selector piece ends with "NoCopy" (but it's not a method we
    know about and there's no "freeWhenDone:" parameter), treat the buffer
    as escaping.

The reason that (2) and (3) don't explicitly model the ownership transfer is
because we can't be sure that they will actually free the memory using free(),
and we wouldn't want to emit a spurious "mismatched allocator" warning
(coming in Anton's upcoming patch). In the future, we may have an idea of a
"generic deallocation", i.e. we assume that the deallocator is correct but
still continue tracking the region so that we can warn about double-frees.

Patch by Anton Yartsev, with modifications from me.

llvm-svn: 176744
2013-03-09 00:59:10 +00:00
Jordan Rose bce0583627 [analyzer] Look for lvalue nodes when tracking a null pointer.
r176010 introduced the notion of "interesting" lvalue expressions, whose
nodes are guaranteed never to be reclaimed by the ExplodedGraph. This was
used in bugreporter::trackNullOrUndefValue to find the region that contains
the null or undef value being tracked.

However, the /rvalue/ nodes (i.e. the loads from these lvalues that produce
a null or undef value) /are/ still being reclaimed, and if we couldn't
find the node for the rvalue, we just give up. This patch changes that so
that we look for the node for either the rvalue or the lvalue -- preferring
the former, since it lets us fall back to value-only tracking in cases
where we can't get a region, but allowing the latter as well.

<rdar://problem/13342842>

llvm-svn: 176737
2013-03-08 23:30:56 +00:00
Jan Wen Voung 058927b8d4 Move clang tests that depend on llvm/ADT/Statistic.h to a subdir.
The subdirectory has a lit.local.cfg that marks the tests unsupported
if llvm was built without Asserts.  There will be a patch in LLVM
that disables statistics gathering when built without Asserts so
that full Release builds can be faster.  Statistics can also
be enabled by building with -DLLVM_ENABLE_STATS.

llvm-svn: 176730
2013-03-08 22:42:02 +00:00
Anna Zaks 9e0da9e070 [analyzer] Warn on passing a reference to null pointer as an argument in a call
Warn about null pointer dereference earlier when a reference to a null pointer is
passed in a call. The idea is that even though the standard might allow this, reporting
the issue earlier is better for diagnostics (the error is reported closer to the place where
the pointer was set to NULL). This also simplifies analyzer’s diagnostic logic, which has
to track “where the null came from”. As a consequence, some of our null pointer
warning suppression mechanisms started triggering more often.

TODO: Change the name of the file and class to reflect the new check.
llvm-svn: 176612
2013-03-07 03:02:36 +00:00
Jordan Rose b41977f852 [analyzer] Check for returning null references in ReturnUndefChecker.
Officially in the C++ standard, a null reference cannot exist. However,
it's still very easy to create one:

int &getNullRef() {
  int *p = 0;
  return *p;
}

We already check that binds to reference regions don't create null references.
This patch checks that we don't create null references by returning, either.

<rdar://problem/13364378>

llvm-svn: 176601
2013-03-07 01:23:25 +00:00
Anna Zaks 23c85ed52b [analyzer] Pass the correct Expr to the bug reporter visitors when dealing with CompoundLiteralExpr
This allows us to trigger the IDC visitor in the added test case.

llvm-svn: 176577
2013-03-06 20:26:02 +00:00
Anna Zaks 6fe2fc633a [analyzer] IDC: Add config option; perform the idc check on first “null node” rather than last “non-null”.
The second modification does not lead to any visible result, but, theoretically, is what we should
have been looking at to begin with since we are checking if the node was assumed to be null in
an inlined function.

llvm-svn: 176576
2013-03-06 20:25:59 +00:00
Jordan Rose 85707b28e8 [analyzer] Don't let cf_audited_transfer override CFRetain semantics.
We weren't treating a cf_audited_transfer CFRetain as returning +1 because
its name doesn't contain "Create" or "Copy". Oops! Fortunately, the
standard definitions of these functions are not marked audited.

<rdar://problem/13339601>

llvm-svn: 176463
2013-03-04 23:21:32 +00:00
Anna Zaks 8d7c8a4dd6 [analyzer] Simple inline defensive checks suppression
Inlining brought a few "null pointer use" false positives, which occur because
the callee defensively checks if a pointer is NULL, whereas the caller knows
that the pointer cannot be NULL in the context of the given call.

This is a first attempt to silence these warnings by tracking the symbolic value
along the execution path in the BugReporter. The new visitor finds the node
in which the symbol was first constrained to NULL. If the node belongs to
a function on the active stack, the warning is reported, otherwise, it is
suppressed.

There are several areas for follow up work, for example:
 - How do we differentiate the cases where the first check is followed by
another one, which does happen on the active stack?

Also, this only silences a fraction of null pointer use warnings. For example, it
does not do anything for the cases where NULL was assigned inside a callee.

llvm-svn: 176402
2013-03-02 03:20:52 +00:00
Jordan Rose e185d73101 [analyzer] Special-case bitfields when finding sub-region bindings.
Previously we were assuming that we'd never ask for the sub-region bindings
of a bitfield, since a bitfield cannot have subregions. However,
unification of code paths has made that assumption invalid. While we could
take advantage of this by just checking for the single possible binding,
it's probably better to do the right thing, so that if/when we someday
support unions we'll do the right thing there, too.

This fixes a handful of false positives in analyzing LLVM.

<rdar://problem/13325522>

llvm-svn: 176388
2013-03-01 23:03:17 +00:00
Jordan Rose 801916baf1 [analyzer] Suppress paths involving a reference whose rvalue is null.
Most map types have an operator[] that inserts a new element if the key
isn't found, then returns a reference to the value slot so that you can
assign into it. However, if the value type is a pointer, it will be
initialized to null. This is usually no problem.

However, if the user /knows/ the map contains a value for a particular key,
they may just use it immediately:

   // From ClangSACheckersEmitter.cpp
   recordGroupMap[group]->Checkers

In this case the analyzer reports a null dereference on the path where the
key is not in the map, even though the user knows that path is impossible
here. They could silence the warning by adding an assertion, but that means
splitting up the expression and introducing a local variable. (Note that
the analyzer has no way of knowing that recordGroupMap[group] will return
the same reference if called twice in a row!)

We already have logic that says a null dereference has a high chance of
being a false positive if the null came from an inlined function. This
patch simply extends that to references whose rvalues are null as well,
silencing several false positives in LLVM.

<rdar://problem/13239854>

llvm-svn: 176371
2013-03-01 19:45:10 +00:00
Jordan Rose 2c377feacb [analyzer] Fix test for previous commit.
llvm-svn: 176202
2013-02-27 18:57:20 +00:00
Jordan Rose f7f32d5202 [analyzer] Teach FindLastStoreBRVisitor to understand stores of the same value.
Consider this case:

  int *p = 0;
  p = getPointerThatMayBeNull();
  *p = 1;

If we inline 'getPointerThatMayBeNull', we might know that the value of 'p'
is NULL, and thus emit a null pointer dereference report. However, we
usually want to suppress such warnings as error paths, and we do so by using
FindLastStoreBRVisitor to see where the NULL came from. In this case, though,
because 'p' was NULL both before and after the assignment, the visitor
would decide that the "last store" was the initialization, not the
re-assignment.

This commit changes FindLastStoreBRVisitor to consider all PostStore nodes
that assign to this region. This still won't catches changes made directly
by checkers if they re-assign the same value, but it does handle the common
case in user-written code and will trigger ReturnVisitor's suppression
machinery as expected.

<rdar://problem/13299738>

llvm-svn: 176201
2013-02-27 18:49:57 +00:00
Jordan Rose 4587b28758 [analyzer] Turn on C++ constructor inlining by default.
This enables constructor inlining for types with non-trivial destructors.
The plan is to enable destructor inlining within the next month, but that
needs further verification.

<rdar://problem/12295329>

llvm-svn: 176200
2013-02-27 18:49:43 +00:00
Jordan Rose 4a7bf49bd4 [analyzer] If a struct has a partial lazy binding, its fields aren't Undef.
This is essentially the same problem as r174031: a lazy binding for the first
field of a struct may stomp on an existing default binding for the
entire struct. Because of the way RegionStore is set up, we can't help
but lose the top-level binding, but then we need to make sure that accessing
one of the other fields doesn't come back as Undefined.

In this case, RegionStore is now correctly detecting that the lazy binding
we have isn't the right type, but then failing to follow through on the
implications of that: we don't know anything about the other fields in the
aggregate. This fix adds a test when searching for other kinds of default
values to see if there's a lazy binding we rejected, and if so returns
a symbolic value instead of Undefined.

The long-term fix for this is probably a new Store model; see
<rdar://problem/12701038>.

Fixes <rdar://problem/13292559>.

llvm-svn: 176144
2013-02-27 00:05:29 +00:00
Ted Kremenek 37c777ecc0 [analyzer] Use 'MemRegion::printPretty()' instead of assuming the region is a VarRegion.
Fixes PR15358 and <rdar://problem/13295437>.

Along the way, shorten path diagnostics that say "Variable 'x'" to just
be "'x'".  By the context, it is obvious that we have a variable,
and so this just consumes text space.

llvm-svn: 176115
2013-02-26 19:44:38 +00:00
Jordan Rose 861a174018 [analyzer] Don't look through casts when creating pointer temporaries.
Normally, we need to look through derived-to-base casts when creating
temporary object regions (added in r175854). However, if the temporary
is a pointer (rather than a struct/class instance), we need to /preserve/
the base casts that have been applied.

This also ensures that we really do create a new temporary region when
we need to: MaterializeTemporaryExpr and lvalue CXXDefaultArgExprs.

Fixes PR15342, although the test case doesn't include the crash because
I couldn't isolate it.

llvm-svn: 176069
2013-02-26 01:21:27 +00:00
Jordan Rose c948709cda [analyzer] StackAddrEscapeChecker: strip qualifiers from temporary types.
With the new support for trivial copy constructors, we are not always
consistent about whether a CXXTempObjectRegion gets reused or created
from scratch, which affects whether qualifiers are preserved. However,
we probably don't care anyway.

This also switches to using the current PrintingPolicy for the type,
which means C++ types don't get a spurious 'struct' prefix anymore.

llvm-svn: 176068
2013-02-26 01:21:21 +00:00
Anna Zaks ba34272321 [analyzer] Restrict ObjC type inference to methods that have related result type.
This addresses a case when we inline a wrong method due to incorrect
dynamic type inference. Specifically, when user code contains a method from init
family, which creates an instance of another class.

Use hasRelatedResultType() to find out if our inference rules should be triggered.

llvm-svn: 176054
2013-02-25 22:10:34 +00:00
Jordan Rose 77cdb53cdf [analyzer] Handle reference parameters with default values.
r175026 added support for default values, but didn't take reference
parameters into account, which expect the default argument to be an
lvalue. Use createTemporaryRegionIfNeeded if we can evaluate the default
expr as an rvalue but the expected result is an lvalue.

Fixes the most recent report of PR12915. The original report predates
default argument support, so that can't be it.

llvm-svn: 176042
2013-02-25 19:45:34 +00:00
Jordan Rose f9e9a9f41b [analyzer] Base regions may be invalid when layered on symbolic regions.
While RegionStore checks to make sure casts on TypedValueRegions are valid,
it does not do the same for SymbolicRegions, which do not have perfect type
info anyway. Additionally, MemRegion::getAsOffset does not take a
ProgramState, so it can't use dynamic type info to determine a better type
for the regions. (This could also be dangerous if the type of a super-region
changes!)

Account for this by checking that a base object region is valid on top of a
symbolic region, and falling back to "symbolic offset" mode if not.

Fixes PR15345.

llvm-svn: 176034
2013-02-25 18:36:15 +00:00
Ted Kremenek 9625048278 [analyzer] tracking stores/constraints now works for ObjC ivars or struct fields.
This required more changes than I originally expected:

- ObjCIvarRegion implements "canPrintPretty" et al
- DereferenceChecker indicates the null pointer source is an ivar
- bugreporter::trackNullOrUndefValue() uses an alternate algorithm
  to compute the location region to track by scouring the ExplodedGraph.
  This allows us to get the actual MemRegion for variables, ivars,
  fields, etc.  We only hand construct a VarRegion for C++ references.
- ExplodedGraph no longer drops nodes for expressions that are marked
  'lvalue'.  This is to facilitate the logic in the previous bullet.
  This may lead to a slight increase in size in the ExplodedGraph,
  which I have not measured, but it is likely not to be a big deal.

I have validated each of the changed plist output.

Fixes <rdar://problem/12114812>

llvm-svn: 175988
2013-02-24 07:21:01 +00:00
Jordan Rose 893d73b7e9 [analyzer] Don't canonicalize the RecordDecl used in CXXBaseObjectRegion.
This Decl shouldn't be the canonical Decl; it should be the Decl used by
the CXXBaseSpecifier in the subclass. Unfortunately, that means continuing
to throw getCanonicalDecl() on all comparisons.

This fixes MemRegion::getAsOffset's use of ASTRecordLayout when redeclarations
are involved.

llvm-svn: 175913
2013-02-22 19:33:13 +00:00
Ted Kremenek efb41d23a6 [analyzer] Implement "Loop executed 0 times" diagnostic correctly.
Fixes <rdar://problem/13236549>

llvm-svn: 175863
2013-02-22 05:45:33 +00:00
Anna Zaks 04e7ff43a1 [analyzer] Place all inlining policy checks into one palce
Previously, we had the decisions about inlining spread out
over multiple functions.

In addition to the refactor, this commit ensures
that we will always inline BodyFarm functions as long as the Decl
is available. This fixes false positives due to those functions
not being inlined when no or minimal inlining is enabled such (as
shallow mode).

llvm-svn: 175857
2013-02-22 02:59:24 +00:00
Jordan Rose 5772f82d1e [analyzer] Make sure a materialized temporary matches its bindings.
This is a follow-up to r175830, which made sure a temporary object region
created for, say, a struct rvalue matched up with the initial bindings
being stored into it. This does the same for the case in which the AST
actually tells us that we need to create a temporary via a
MaterializeObjectExpr. I've unified the two code paths and moved a static
helper function onto ExprEngine.

This also caused a bit of test churn, causing us to go back to describing
temporary regions without a 'const' qualifier. This seems acceptable; it's
our behavior from a few months ago.

<rdar://problem/13265460> (part 2)

llvm-svn: 175854
2013-02-22 01:51:15 +00:00