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 "ClangSACheckers.h"
16 #include "clang/AST/ParentMap.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
19 #include "clang/StaticAnalyzer/Core/Checker.h"
20 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/Support/raw_ostream.h"
26 using namespace clang;
30 class CallAndMessageChecker
31 : public Checker< check::PreStmt<CallExpr>, check::PreObjCMessage,
33 mutable OwningPtr<BugType> BT_call_null;
34 mutable OwningPtr<BugType> BT_call_undef;
35 mutable OwningPtr<BugType> BT_cxx_call_null;
36 mutable OwningPtr<BugType> BT_cxx_call_undef;
37 mutable OwningPtr<BugType> BT_call_arg;
38 mutable OwningPtr<BugType> BT_msg_undef;
39 mutable OwningPtr<BugType> BT_objc_prop_undef;
40 mutable OwningPtr<BugType> BT_objc_subscript_undef;
41 mutable OwningPtr<BugType> BT_msg_arg;
42 mutable OwningPtr<BugType> BT_msg_ret;
45 void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
46 void checkPreObjCMessage(const ObjCMethodCall &msg, CheckerContext &C) const;
47 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
50 static bool PreVisitProcessArg(CheckerContext &C, SVal V,
51 SourceRange argRange, const Expr *argEx,
52 bool IsFirstArgument, bool checkUninitFields,
53 const CallEvent &Call, OwningPtr<BugType> &BT);
55 static void emitBadCall(BugType *BT, CheckerContext &C, const Expr *BadE);
56 void emitNilReceiverBug(CheckerContext &C, const ObjCMethodCall &msg,
57 ExplodedNode *N) const;
59 void HandleNilReceiver(CheckerContext &C,
60 ProgramStateRef state,
61 const ObjCMethodCall &msg) const;
63 static void LazyInit_BT(const char *desc, OwningPtr<BugType> &BT) {
65 BT.reset(new BuiltinBug(desc));
68 } // end anonymous namespace
70 void CallAndMessageChecker::emitBadCall(BugType *BT, CheckerContext &C,
72 ExplodedNode *N = C.generateSink();
76 BugReport *R = new BugReport(*BT, BT->getName(), N);
78 R->addRange(BadE->getSourceRange());
79 if (BadE->isGLValue())
80 BadE = bugreporter::getDerefExpr(BadE);
81 bugreporter::trackNullOrUndefValue(N, BadE, *R);
86 static StringRef describeUninitializedArgumentInCall(const CallEvent &Call,
87 bool IsFirstArgument) {
88 switch (Call.getKind()) {
89 case CE_ObjCMessage: {
90 const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
91 switch (Msg.getMessageKind()) {
93 return "Argument in message expression is an uninitialized value";
94 case OCM_PropertyAccess:
95 assert(Msg.isSetter() && "Getters have no args");
96 return "Argument for property setter is an uninitialized value";
98 if (Msg.isSetter() && IsFirstArgument)
99 return "Argument for subscript setter is an uninitialized value";
100 return "Subscript index is an uninitialized value";
102 llvm_unreachable("Unknown message kind.");
105 return "Block call argument is an uninitialized value";
107 return "Function call argument is an uninitialized value";
111 bool CallAndMessageChecker::PreVisitProcessArg(CheckerContext &C,
112 SVal V, SourceRange argRange,
114 bool IsFirstArgument,
115 bool checkUninitFields,
116 const CallEvent &Call,
117 OwningPtr<BugType> &BT) {
119 if (ExplodedNode *N = C.generateSink()) {
120 LazyInit_BT("Uninitialized argument value", BT);
122 // Generate a report for this bug.
123 StringRef Desc = describeUninitializedArgumentInCall(Call,
125 BugReport *R = new BugReport(*BT, Desc, N);
126 R->addRange(argRange);
128 bugreporter::trackNullOrUndefValue(N, argEx, *R);
134 if (!checkUninitFields)
137 if (Optional<nonloc::LazyCompoundVal> LV =
138 V.getAs<nonloc::LazyCompoundVal>()) {
140 class FindUninitializedField {
142 SmallVector<const FieldDecl *, 10> FieldChain;
144 StoreManager &StoreMgr;
145 MemRegionManager &MrMgr;
148 FindUninitializedField(StoreManager &storeMgr,
149 MemRegionManager &mrMgr, Store s)
150 : StoreMgr(storeMgr), MrMgr(mrMgr), store(s) {}
152 bool Find(const TypedValueRegion *R) {
153 QualType T = R->getValueType();
154 if (const RecordType *RT = T->getAsStructureType()) {
155 const RecordDecl *RD = RT->getDecl()->getDefinition();
156 assert(RD && "Referred record has no definition");
157 for (RecordDecl::field_iterator I =
158 RD->field_begin(), E = RD->field_end(); I!=E; ++I) {
159 const FieldRegion *FR = MrMgr.getFieldRegion(*I, R);
160 FieldChain.push_back(*I);
162 if (T->getAsStructureType()) {
167 const SVal &V = StoreMgr.getBinding(store, loc::MemRegionVal(FR));
171 FieldChain.pop_back();
179 const LazyCompoundValData *D = LV->getCVData();
180 FindUninitializedField F(C.getState()->getStateManager().getStoreManager(),
181 C.getSValBuilder().getRegionManager(),
184 if (F.Find(D->getRegion())) {
185 if (ExplodedNode *N = C.generateSink()) {
186 LazyInit_BT("Uninitialized argument value", BT);
187 SmallString<512> Str;
188 llvm::raw_svector_ostream os(Str);
189 os << "Passed-by-value struct argument contains uninitialized data";
191 if (F.FieldChain.size() == 1)
192 os << " (e.g., field: '" << *F.FieldChain[0] << "')";
194 os << " (e.g., via the field chain: '";
196 for (SmallVectorImpl<const FieldDecl *>::iterator
197 DI = F.FieldChain.begin(), DE = F.FieldChain.end(); DI!=DE;++DI){
207 // Generate a report for this bug.
208 BugReport *R = new BugReport(*BT, os.str(), N);
209 R->addRange(argRange);
211 // FIXME: enhance track back for uninitialized value for arbitrary
222 void CallAndMessageChecker::checkPreStmt(const CallExpr *CE,
223 CheckerContext &C) const{
225 const Expr *Callee = CE->getCallee()->IgnoreParens();
226 ProgramStateRef State = C.getState();
227 const LocationContext *LCtx = C.getLocationContext();
228 SVal L = State->getSVal(Callee, LCtx);
232 BT_call_undef.reset(new BuiltinBug("Called function pointer is an "
233 "uninitalized pointer value"));
234 emitBadCall(BT_call_undef.get(), C, Callee);
238 ProgramStateRef StNonNull, StNull;
239 llvm::tie(StNonNull, StNull) =
240 State->assume(L.castAs<DefinedOrUnknownSVal>());
242 if (StNull && !StNonNull) {
245 new BuiltinBug("Called function pointer is null (null dereference)"));
246 emitBadCall(BT_call_null.get(), C, Callee);
249 C.addTransition(StNonNull);
252 void CallAndMessageChecker::checkPreCall(const CallEvent &Call,
253 CheckerContext &C) const {
254 ProgramStateRef State = C.getState();
256 // If this is a call to a C++ method, check if the callee is null or
258 if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
259 SVal V = CC->getCXXThisVal();
261 if (!BT_cxx_call_undef)
262 BT_cxx_call_undef.reset(new BuiltinBug("Called C++ object pointer is "
264 emitBadCall(BT_cxx_call_undef.get(), C, CC->getCXXThisExpr());
268 ProgramStateRef StNonNull, StNull;
269 llvm::tie(StNonNull, StNull) =
270 State->assume(V.castAs<DefinedOrUnknownSVal>());
272 if (StNull && !StNonNull) {
273 if (!BT_cxx_call_null)
274 BT_cxx_call_null.reset(new BuiltinBug("Called C++ object pointer "
276 emitBadCall(BT_cxx_call_null.get(), C, CC->getCXXThisExpr());
283 // Don't check for uninitialized field values in arguments if the
284 // caller has a body that is available and we have the chance to inline it.
285 // This is a hack, but is a reasonable compromise betweens sometimes warning
286 // and sometimes not depending on if we decide to inline a function.
287 const Decl *D = Call.getDecl();
288 const bool checkUninitFields =
289 !(C.getAnalysisManager().shouldInlineCall() && (D && D->getBody()));
291 OwningPtr<BugType> *BT;
292 if (isa<ObjCMethodCall>(Call))
297 for (unsigned i = 0, e = Call.getNumArgs(); i != e; ++i)
298 if (PreVisitProcessArg(C, Call.getArgSVal(i), Call.getArgSourceRange(i),
299 Call.getArgExpr(i), /*IsFirstArgument=*/i == 0,
300 checkUninitFields, Call, *BT))
303 // If we make it here, record our assumptions about the callee.
304 C.addTransition(State);
307 void CallAndMessageChecker::checkPreObjCMessage(const ObjCMethodCall &msg,
308 CheckerContext &C) const {
309 SVal recVal = msg.getReceiverSVal();
310 if (recVal.isUndef()) {
311 if (ExplodedNode *N = C.generateSink()) {
313 switch (msg.getMessageKind()) {
316 BT_msg_undef.reset(new BuiltinBug("Receiver in message expression "
317 "is an uninitialized value"));
318 BT = BT_msg_undef.get();
320 case OCM_PropertyAccess:
321 if (!BT_objc_prop_undef)
322 BT_objc_prop_undef.reset(new BuiltinBug("Property access on an "
323 "uninitialized object "
325 BT = BT_objc_prop_undef.get();
328 if (!BT_objc_subscript_undef)
329 BT_objc_subscript_undef.reset(new BuiltinBug("Subscript access on an "
330 "uninitialized object "
332 BT = BT_objc_subscript_undef.get();
335 assert(BT && "Unknown message kind.");
337 BugReport *R = new BugReport(*BT, BT->getName(), N);
338 const ObjCMessageExpr *ME = msg.getOriginExpr();
339 R->addRange(ME->getReceiverRange());
341 // FIXME: getTrackNullOrUndefValueVisitor can't handle "super" yet.
342 if (const Expr *ReceiverE = ME->getInstanceReceiver())
343 bugreporter::trackNullOrUndefValue(N, ReceiverE, *R);
348 // Bifurcate the state into nil and non-nil ones.
349 DefinedOrUnknownSVal receiverVal = recVal.castAs<DefinedOrUnknownSVal>();
351 ProgramStateRef state = C.getState();
352 ProgramStateRef notNilState, nilState;
353 llvm::tie(notNilState, nilState) = state->assume(receiverVal);
355 // Handle receiver must be nil.
356 if (nilState && !notNilState) {
357 HandleNilReceiver(C, state, msg);
363 void CallAndMessageChecker::emitNilReceiverBug(CheckerContext &C,
364 const ObjCMethodCall &msg,
365 ExplodedNode *N) const {
369 new BuiltinBug("Receiver in message expression is 'nil'"));
371 const ObjCMessageExpr *ME = msg.getOriginExpr();
373 QualType ResTy = msg.getResultType();
375 SmallString<200> buf;
376 llvm::raw_svector_ostream os(buf);
377 os << "The receiver of message '" << ME->getSelector().getAsString()
379 if (ResTy->isReferenceType()) {
380 os << ", which results in forming a null reference";
382 os << " and returns a value of type '";
383 msg.getResultType().print(os, C.getLangOpts());
384 os << "' that will be garbage";
387 BugReport *report = new BugReport(*BT_msg_ret, os.str(), N);
388 report->addRange(ME->getReceiverRange());
389 // FIXME: This won't track "self" in messages to super.
390 if (const Expr *receiver = ME->getInstanceReceiver()) {
391 bugreporter::trackNullOrUndefValue(N, receiver, *report);
393 C.emitReport(report);
396 static bool supportsNilWithFloatRet(const llvm::Triple &triple) {
397 return (triple.getVendor() == llvm::Triple::Apple &&
398 (triple.getOS() == llvm::Triple::IOS ||
399 !triple.isMacOSXVersionLT(10,5)));
402 void CallAndMessageChecker::HandleNilReceiver(CheckerContext &C,
403 ProgramStateRef state,
404 const ObjCMethodCall &Msg) const {
405 ASTContext &Ctx = C.getASTContext();
406 static SimpleProgramPointTag Tag("CallAndMessageChecker : NilReceiver");
408 // Check the return type of the message expression. A message to nil will
409 // return different values depending on the return type and the architecture.
410 QualType RetTy = Msg.getResultType();
411 CanQualType CanRetTy = Ctx.getCanonicalType(RetTy);
412 const LocationContext *LCtx = C.getLocationContext();
414 if (CanRetTy->isStructureOrClassType()) {
415 // Structure returns are safe since the compiler zeroes them out.
416 SVal V = C.getSValBuilder().makeZeroVal(RetTy);
417 C.addTransition(state->BindExpr(Msg.getOriginExpr(), LCtx, V), &Tag);
421 // Other cases: check if sizeof(return type) > sizeof(void*)
422 if (CanRetTy != Ctx.VoidTy && C.getLocationContext()->getParentMap()
423 .isConsumedExpr(Msg.getOriginExpr())) {
424 // Compute: sizeof(void *) and sizeof(return type)
425 const uint64_t voidPtrSize = Ctx.getTypeSize(Ctx.VoidPtrTy);
426 const uint64_t returnTypeSize = Ctx.getTypeSize(CanRetTy);
428 if (CanRetTy.getTypePtr()->isReferenceType()||
429 (voidPtrSize < returnTypeSize &&
430 !(supportsNilWithFloatRet(Ctx.getTargetInfo().getTriple()) &&
431 (Ctx.FloatTy == CanRetTy ||
432 Ctx.DoubleTy == CanRetTy ||
433 Ctx.LongDoubleTy == CanRetTy ||
434 Ctx.LongLongTy == CanRetTy ||
435 Ctx.UnsignedLongLongTy == CanRetTy)))) {
436 if (ExplodedNode *N = C.generateSink(state, 0 , &Tag))
437 emitNilReceiverBug(C, Msg, N);
441 // Handle the safe cases where the return value is 0 if the
444 // FIXME: For now take the conservative approach that we only
445 // return null values if we *know* that the receiver is nil.
446 // This is because we can have surprises like:
448 // ... = [[NSScreens screens] objectAtIndex:0];
450 // What can happen is that [... screens] could return nil, but
451 // it most likely isn't nil. We should assume the semantics
452 // of this case unless we have *a lot* more knowledge.
454 SVal V = C.getSValBuilder().makeZeroVal(RetTy);
455 C.addTransition(state->BindExpr(Msg.getOriginExpr(), LCtx, V), &Tag);
459 C.addTransition(state);
462 void ento::registerCallAndMessageChecker(CheckerManager &mgr) {
463 mgr.registerChecker<CallAndMessageChecker>();