1 //===--- CallAndMessageChecker.cpp ------------------------------*- C++ -*--==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This defines CallAndMessageChecker, a builtin checker that checks for various
11 // errors of call and objc message expressions.
13 //===----------------------------------------------------------------------===//
15 #include "GRExprEngineInternalChecks.h"
16 #include "clang/AST/ParentMap.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/Checker/BugReporter/BugType.h"
19 #include "clang/Checker/PathSensitive/CheckerVisitor.h"
21 using namespace clang
;
24 class CallAndMessageChecker
25 : public CheckerVisitor
<CallAndMessageChecker
> {
26 BugType
*BT_call_null
;
27 BugType
*BT_call_undef
;
29 BugType
*BT_msg_undef
;
33 CallAndMessageChecker() :
34 BT_call_null(0), BT_call_undef(0), BT_call_arg(0),
35 BT_msg_undef(0), BT_msg_arg(0), BT_msg_ret(0) {}
37 static void *getTag() {
42 void PreVisitCallExpr(CheckerContext
&C
, const CallExpr
*CE
);
43 void PreVisitObjCMessageExpr(CheckerContext
&C
, const ObjCMessageExpr
*ME
);
44 bool evalNilReceiver(CheckerContext
&C
, const ObjCMessageExpr
*ME
);
47 bool PreVisitProcessArg(CheckerContext
&C
, const Expr
*Ex
,
48 const char *BT_desc
, BugType
*&BT
);
50 void EmitBadCall(BugType
*BT
, CheckerContext
&C
, const CallExpr
*CE
);
51 void emitNilReceiverBug(CheckerContext
&C
, const ObjCMessageExpr
*ME
,
54 void HandleNilReceiver(CheckerContext
&C
, const GRState
*state
,
55 const ObjCMessageExpr
*ME
);
57 void LazyInit_BT(const char *desc
, BugType
*&BT
) {
59 BT
= new BuiltinBug(desc
);
62 } // end anonymous namespace
64 void clang::RegisterCallAndMessageChecker(GRExprEngine
&Eng
) {
65 Eng
.registerCheck(new CallAndMessageChecker());
68 void CallAndMessageChecker::EmitBadCall(BugType
*BT
, CheckerContext
&C
,
70 ExplodedNode
*N
= C
.generateSink();
74 EnhancedBugReport
*R
= new EnhancedBugReport(*BT
, BT
->getName(), N
);
75 R
->addVisitorCreator(bugreporter::registerTrackNullOrUndefValue
,
76 bugreporter::GetCalleeExpr(N
));
80 bool CallAndMessageChecker::PreVisitProcessArg(CheckerContext
&C
,
85 const SVal
&V
= C
.getState()->getSVal(Ex
);
88 if (ExplodedNode
*N
= C
.generateSink()) {
89 LazyInit_BT(BT_desc
, BT
);
91 // Generate a report for this bug.
92 EnhancedBugReport
*R
= new EnhancedBugReport(*BT
, BT
->getName(), N
);
93 R
->addRange(Ex
->getSourceRange());
94 R
->addVisitorCreator(bugreporter::registerTrackNullOrUndefValue
, Ex
);
100 if (const nonloc::LazyCompoundVal
*LV
=
101 dyn_cast
<nonloc::LazyCompoundVal
>(&V
)) {
103 class FindUninitializedField
{
105 llvm::SmallVector
<const FieldDecl
*, 10> FieldChain
;
108 StoreManager
&StoreMgr
;
109 MemRegionManager
&MrMgr
;
112 FindUninitializedField(ASTContext
&c
, StoreManager
&storeMgr
,
113 MemRegionManager
&mrMgr
, Store s
)
114 : C(c
), StoreMgr(storeMgr
), MrMgr(mrMgr
), store(s
) {}
116 bool Find(const TypedRegion
*R
) {
117 QualType T
= R
->getValueType();
118 if (const RecordType
*RT
= T
->getAsStructureType()) {
119 const RecordDecl
*RD
= RT
->getDecl()->getDefinition();
120 assert(RD
&& "Referred record has no definition");
121 for (RecordDecl::field_iterator I
=
122 RD
->field_begin(), E
= RD
->field_end(); I
!=E
; ++I
) {
123 const FieldRegion
*FR
= MrMgr
.getFieldRegion(*I
, R
);
124 FieldChain
.push_back(*I
);
126 if (T
->getAsStructureType()) {
131 const SVal
&V
= StoreMgr
.Retrieve(store
, loc::MemRegionVal(FR
));
135 FieldChain
.pop_back();
143 const LazyCompoundValData
*D
= LV
->getCVData();
144 FindUninitializedField
F(C
.getASTContext(),
145 C
.getState()->getStateManager().getStoreManager(),
146 C
.getSValBuilder().getRegionManager(),
149 if (F
.Find(D
->getRegion())) {
150 if (ExplodedNode
*N
= C
.generateSink()) {
151 LazyInit_BT(BT_desc
, BT
);
152 llvm::SmallString
<512> Str
;
153 llvm::raw_svector_ostream
os(Str
);
154 os
<< "Passed-by-value struct argument contains uninitialized data";
156 if (F
.FieldChain
.size() == 1)
157 os
<< " (e.g., field: '" << F
.FieldChain
[0] << "')";
159 os
<< " (e.g., via the field chain: '";
161 for (llvm::SmallVectorImpl
<const FieldDecl
*>::iterator
162 DI
= F
.FieldChain
.begin(), DE
= F
.FieldChain
.end(); DI
!=DE
;++DI
){
172 // Generate a report for this bug.
173 EnhancedBugReport
*R
= new EnhancedBugReport(*BT
, os
.str(), N
);
174 R
->addRange(Ex
->getSourceRange());
176 // FIXME: enhance track back for uninitialized value for arbitrary
187 void CallAndMessageChecker::PreVisitCallExpr(CheckerContext
&C
,
190 const Expr
*Callee
= CE
->getCallee()->IgnoreParens();
191 SVal L
= C
.getState()->getSVal(Callee
);
196 new BuiltinBug("Called function pointer is an uninitalized pointer value");
197 EmitBadCall(BT_call_undef
, C
, CE
);
201 if (isa
<loc::ConcreteInt
>(L
)) {
204 new BuiltinBug("Called function pointer is null (null dereference)");
205 EmitBadCall(BT_call_null
, C
, CE
);
208 for (CallExpr::const_arg_iterator I
= CE
->arg_begin(), E
= CE
->arg_end();
210 if (PreVisitProcessArg(C
, *I
,
211 "Function call argument is an uninitialized value",
216 void CallAndMessageChecker::PreVisitObjCMessageExpr(CheckerContext
&C
,
217 const ObjCMessageExpr
*ME
) {
219 const GRState
*state
= C
.getState();
221 // FIXME: Handle 'super'?
222 if (const Expr
*receiver
= ME
->getInstanceReceiver())
223 if (state
->getSVal(receiver
).isUndef()) {
224 if (ExplodedNode
*N
= C
.generateSink()) {
227 new BuiltinBug("Receiver in message expression is an uninitialized value");
228 EnhancedBugReport
*R
=
229 new EnhancedBugReport(*BT_msg_undef
, BT_msg_undef
->getName(), N
);
230 R
->addRange(receiver
->getSourceRange());
231 R
->addVisitorCreator(bugreporter::registerTrackNullOrUndefValue
,
238 // Check for any arguments that are uninitialized/undefined.
239 for (ObjCMessageExpr::const_arg_iterator I
= ME
->arg_begin(),
240 E
= ME
->arg_end(); I
!= E
; ++I
)
241 if (PreVisitProcessArg(C
, *I
,
242 "Argument in message expression "
243 "is an uninitialized value", BT_msg_arg
))
247 bool CallAndMessageChecker::evalNilReceiver(CheckerContext
&C
,
248 const ObjCMessageExpr
*ME
) {
249 HandleNilReceiver(C
, C
.getState(), ME
);
250 return true; // Nil receiver is not handled elsewhere.
253 void CallAndMessageChecker::emitNilReceiverBug(CheckerContext
&C
,
254 const ObjCMessageExpr
*ME
,
259 new BuiltinBug("Receiver in message expression is "
260 "'nil' and returns a garbage value");
262 llvm::SmallString
<200> buf
;
263 llvm::raw_svector_ostream
os(buf
);
264 os
<< "The receiver of message '" << ME
->getSelector().getAsString()
265 << "' is nil and returns a value of type '"
266 << ME
->getType().getAsString() << "' that will be garbage";
268 EnhancedBugReport
*report
= new EnhancedBugReport(*BT_msg_ret
, os
.str(), N
);
269 if (const Expr
*receiver
= ME
->getInstanceReceiver()) {
270 report
->addRange(receiver
->getSourceRange());
271 report
->addVisitorCreator(bugreporter::registerTrackNullOrUndefValue
,
274 C
.EmitReport(report
);
277 static bool supportsNilWithFloatRet(const llvm::Triple
&triple
) {
278 return triple
.getVendor() == llvm::Triple::Apple
&&
279 (triple
.getDarwinMajorNumber() >= 9 ||
280 triple
.getArch() == llvm::Triple::arm
||
281 triple
.getArch() == llvm::Triple::thumb
);
284 void CallAndMessageChecker::HandleNilReceiver(CheckerContext
&C
,
285 const GRState
*state
,
286 const ObjCMessageExpr
*ME
) {
288 // Check the return type of the message expression. A message to nil will
289 // return different values depending on the return type and the architecture.
290 QualType RetTy
= ME
->getType();
292 ASTContext
&Ctx
= C
.getASTContext();
293 CanQualType CanRetTy
= Ctx
.getCanonicalType(RetTy
);
295 if (CanRetTy
->isStructureOrClassType()) {
296 // FIXME: At some point we shouldn't rely on isConsumedExpr(), but instead
297 // have the "use of undefined value" be smarter about where the
298 // undefined value came from.
299 if (C
.getPredecessor()->getParentMap().isConsumedExpr(ME
)) {
300 if (ExplodedNode
* N
= C
.generateSink(state
))
301 emitNilReceiverBug(C
, ME
, N
);
305 // The result is not consumed by a surrounding expression. Just propagate
306 // the current state.
307 C
.addTransition(state
);
311 // Other cases: check if the return type is smaller than void*.
312 if (CanRetTy
!= Ctx
.VoidTy
&&
313 C
.getPredecessor()->getParentMap().isConsumedExpr(ME
)) {
314 // Compute: sizeof(void *) and sizeof(return type)
315 const uint64_t voidPtrSize
= Ctx
.getTypeSize(Ctx
.VoidPtrTy
);
316 const uint64_t returnTypeSize
= Ctx
.getTypeSize(CanRetTy
);
318 if (voidPtrSize
< returnTypeSize
&&
319 !(supportsNilWithFloatRet(Ctx
.Target
.getTriple()) &&
320 (Ctx
.FloatTy
== CanRetTy
||
321 Ctx
.DoubleTy
== CanRetTy
||
322 Ctx
.LongDoubleTy
== CanRetTy
||
323 Ctx
.LongLongTy
== CanRetTy
||
324 Ctx
.UnsignedLongLongTy
== CanRetTy
))) {
325 if (ExplodedNode
* N
= C
.generateSink(state
))
326 emitNilReceiverBug(C
, ME
, N
);
330 // Handle the safe cases where the return value is 0 if the
333 // FIXME: For now take the conservative approach that we only
334 // return null values if we *know* that the receiver is nil.
335 // This is because we can have surprises like:
337 // ... = [[NSScreens screens] objectAtIndex:0];
339 // What can happen is that [... screens] could return nil, but
340 // it most likely isn't nil. We should assume the semantics
341 // of this case unless we have *a lot* more knowledge.
343 SVal V
= C
.getSValBuilder().makeZeroVal(ME
->getType());
344 C
.generateNode(state
->BindExpr(ME
, V
));
348 C
.addTransition(state
);