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/ADT/StringExtras.h"
25 #include "llvm/Support/raw_ostream.h"
27 using namespace clang;
33 DefaultBool Check_CallAndMessageUnInitRefArg;
34 DefaultBool Check_CallAndMessageChecker;
36 CheckName CheckName_CallAndMessageUnInitRefArg;
37 CheckName CheckName_CallAndMessageChecker;
40 class CallAndMessageChecker
41 : public Checker< check::PreStmt<CallExpr>,
42 check::PreStmt<CXXDeleteExpr>,
43 check::PreObjCMessage,
44 check::ObjCMessageNil,
46 mutable std::unique_ptr<BugType> BT_call_null;
47 mutable std::unique_ptr<BugType> BT_call_undef;
48 mutable std::unique_ptr<BugType> BT_cxx_call_null;
49 mutable std::unique_ptr<BugType> BT_cxx_call_undef;
50 mutable std::unique_ptr<BugType> BT_call_arg;
51 mutable std::unique_ptr<BugType> BT_cxx_delete_undef;
52 mutable std::unique_ptr<BugType> BT_msg_undef;
53 mutable std::unique_ptr<BugType> BT_objc_prop_undef;
54 mutable std::unique_ptr<BugType> BT_objc_subscript_undef;
55 mutable std::unique_ptr<BugType> BT_msg_arg;
56 mutable std::unique_ptr<BugType> BT_msg_ret;
57 mutable std::unique_ptr<BugType> BT_call_few_args;
62 void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
63 void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
64 void checkPreObjCMessage(const ObjCMethodCall &msg, CheckerContext &C) const;
66 /// Fill in the return value that results from messaging nil based on the
67 /// return type and architecture and diagnose if the return value will be
69 void checkObjCMessageNil(const ObjCMethodCall &msg, CheckerContext &C) const;
71 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
74 bool PreVisitProcessArg(CheckerContext &C, SVal V, SourceRange ArgRange,
75 const Expr *ArgEx, int ArgumentNumber,
76 bool CheckUninitFields, const CallEvent &Call,
77 std::unique_ptr<BugType> &BT,
78 const ParmVarDecl *ParamDecl) const;
80 static void emitBadCall(BugType *BT, CheckerContext &C, const Expr *BadE);
81 void emitNilReceiverBug(CheckerContext &C, const ObjCMethodCall &msg,
82 ExplodedNode *N) const;
84 void HandleNilReceiver(CheckerContext &C,
85 ProgramStateRef state,
86 const ObjCMethodCall &msg) const;
88 void LazyInit_BT(const char *desc, std::unique_ptr<BugType> &BT) const {
90 BT.reset(new BuiltinBug(this, desc));
92 bool uninitRefOrPointer(CheckerContext &C, const SVal &V,
93 SourceRange ArgRange, const Expr *ArgEx,
94 std::unique_ptr<BugType> &BT,
95 const ParmVarDecl *ParamDecl, const char *BD,
96 int ArgumentNumber) const;
98 } // end anonymous namespace
100 void CallAndMessageChecker::emitBadCall(BugType *BT, CheckerContext &C,
102 ExplodedNode *N = C.generateErrorNode();
106 auto R = llvm::make_unique<BugReport>(*BT, BT->getName(), N);
108 R->addRange(BadE->getSourceRange());
109 if (BadE->isGLValue())
110 BadE = bugreporter::getDerefExpr(BadE);
111 bugreporter::trackNullOrUndefValue(N, BadE, *R);
113 C.emitReport(std::move(R));
116 static void describeUninitializedArgumentInCall(const CallEvent &Call,
118 llvm::raw_svector_ostream &Os) {
119 switch (Call.getKind()) {
120 case CE_ObjCMessage: {
121 const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
122 switch (Msg.getMessageKind()) {
124 Os << (ArgumentNumber + 1) << llvm::getOrdinalSuffix(ArgumentNumber + 1)
125 << " argument in message expression is an uninitialized value";
127 case OCM_PropertyAccess:
128 assert(Msg.isSetter() && "Getters have no args");
129 Os << "Argument for property setter is an uninitialized value";
132 if (Msg.isSetter() && (ArgumentNumber == 0))
133 Os << "Argument for subscript setter is an uninitialized value";
135 Os << "Subscript index is an uninitialized value";
138 llvm_unreachable("Unknown message kind.");
141 Os << (ArgumentNumber + 1) << llvm::getOrdinalSuffix(ArgumentNumber + 1)
142 << " block call argument is an uninitialized value";
145 Os << (ArgumentNumber + 1) << llvm::getOrdinalSuffix(ArgumentNumber + 1)
146 << " function call argument is an uninitialized value";
151 bool CallAndMessageChecker::uninitRefOrPointer(
152 CheckerContext &C, const SVal &V, SourceRange ArgRange, const Expr *ArgEx,
153 std::unique_ptr<BugType> &BT, const ParmVarDecl *ParamDecl, const char *BD,
154 int ArgumentNumber) const {
155 if (!Filter.Check_CallAndMessageUnInitRefArg)
158 // No parameter declaration available, i.e. variadic function argument.
162 // If parameter is declared as pointer to const in function declaration,
163 // then check if corresponding argument in function call is
164 // pointing to undefined symbol value (uninitialized memory).
165 SmallString<200> Buf;
166 llvm::raw_svector_ostream Os(Buf);
168 if (ParamDecl->getType()->isPointerType()) {
169 Os << (ArgumentNumber + 1) << llvm::getOrdinalSuffix(ArgumentNumber + 1)
170 << " function call argument is a pointer to uninitialized value";
171 } else if (ParamDecl->getType()->isReferenceType()) {
172 Os << (ArgumentNumber + 1) << llvm::getOrdinalSuffix(ArgumentNumber + 1)
173 << " function call argument is an uninitialized value";
177 if(!ParamDecl->getType()->getPointeeType().isConstQualified())
180 if (const MemRegion *SValMemRegion = V.getAsRegion()) {
181 const ProgramStateRef State = C.getState();
182 const SVal PSV = State->getSVal(SValMemRegion);
184 if (ExplodedNode *N = C.generateErrorNode()) {
186 auto R = llvm::make_unique<BugReport>(*BT, Os.str(), N);
187 R->addRange(ArgRange);
189 bugreporter::trackNullOrUndefValue(N, ArgEx, *R);
191 C.emitReport(std::move(R));
199 bool CallAndMessageChecker::PreVisitProcessArg(CheckerContext &C,
201 SourceRange ArgRange,
204 bool CheckUninitFields,
205 const CallEvent &Call,
206 std::unique_ptr<BugType> &BT,
207 const ParmVarDecl *ParamDecl
209 const char *BD = "Uninitialized argument value";
211 if (uninitRefOrPointer(C, V, ArgRange, ArgEx, BT, ParamDecl, BD,
216 if (ExplodedNode *N = C.generateErrorNode()) {
218 // Generate a report for this bug.
219 SmallString<200> Buf;
220 llvm::raw_svector_ostream Os(Buf);
221 describeUninitializedArgumentInCall(Call, ArgumentNumber, Os);
222 auto R = llvm::make_unique<BugReport>(*BT, Os.str(), N);
224 R->addRange(ArgRange);
226 bugreporter::trackNullOrUndefValue(N, ArgEx, *R);
227 C.emitReport(std::move(R));
232 if (!CheckUninitFields)
235 if (Optional<nonloc::LazyCompoundVal> LV =
236 V.getAs<nonloc::LazyCompoundVal>()) {
238 class FindUninitializedField {
240 SmallVector<const FieldDecl *, 10> FieldChain;
242 StoreManager &StoreMgr;
243 MemRegionManager &MrMgr;
246 FindUninitializedField(StoreManager &storeMgr,
247 MemRegionManager &mrMgr, Store s)
248 : StoreMgr(storeMgr), MrMgr(mrMgr), store(s) {}
250 bool Find(const TypedValueRegion *R) {
251 QualType T = R->getValueType();
252 if (const RecordType *RT = T->getAsStructureType()) {
253 const RecordDecl *RD = RT->getDecl()->getDefinition();
254 assert(RD && "Referred record has no definition");
255 for (const auto *I : RD->fields()) {
256 const FieldRegion *FR = MrMgr.getFieldRegion(I, R);
257 FieldChain.push_back(I);
259 if (T->getAsStructureType()) {
264 const SVal &V = StoreMgr.getBinding(store, loc::MemRegionVal(FR));
268 FieldChain.pop_back();
276 const LazyCompoundValData *D = LV->getCVData();
277 FindUninitializedField F(C.getState()->getStateManager().getStoreManager(),
278 C.getSValBuilder().getRegionManager(),
281 if (F.Find(D->getRegion())) {
282 if (ExplodedNode *N = C.generateErrorNode()) {
284 SmallString<512> Str;
285 llvm::raw_svector_ostream os(Str);
286 os << "Passed-by-value struct argument contains uninitialized data";
288 if (F.FieldChain.size() == 1)
289 os << " (e.g., field: '" << *F.FieldChain[0] << "')";
291 os << " (e.g., via the field chain: '";
293 for (SmallVectorImpl<const FieldDecl *>::iterator
294 DI = F.FieldChain.begin(), DE = F.FieldChain.end(); DI!=DE;++DI){
304 // Generate a report for this bug.
305 auto R = llvm::make_unique<BugReport>(*BT, os.str(), N);
306 R->addRange(ArgRange);
308 // FIXME: enhance track back for uninitialized value for arbitrary
310 C.emitReport(std::move(R));
319 void CallAndMessageChecker::checkPreStmt(const CallExpr *CE,
320 CheckerContext &C) const{
322 const Expr *Callee = CE->getCallee()->IgnoreParens();
323 ProgramStateRef State = C.getState();
324 const LocationContext *LCtx = C.getLocationContext();
325 SVal L = State->getSVal(Callee, LCtx);
329 BT_call_undef.reset(new BuiltinBug(
330 this, "Called function pointer is an uninitialized pointer value"));
331 emitBadCall(BT_call_undef.get(), C, Callee);
335 ProgramStateRef StNonNull, StNull;
336 std::tie(StNonNull, StNull) = State->assume(L.castAs<DefinedOrUnknownSVal>());
338 if (StNull && !StNonNull) {
340 BT_call_null.reset(new BuiltinBug(
341 this, "Called function pointer is null (null dereference)"));
342 emitBadCall(BT_call_null.get(), C, Callee);
346 C.addTransition(StNonNull);
349 void CallAndMessageChecker::checkPreStmt(const CXXDeleteExpr *DE,
350 CheckerContext &C) const {
352 SVal Arg = C.getSVal(DE->getArgument());
355 ExplodedNode *N = C.generateErrorNode();
358 if (!BT_cxx_delete_undef)
359 BT_cxx_delete_undef.reset(
360 new BuiltinBug(this, "Uninitialized argument value"));
361 if (DE->isArrayFormAsWritten())
362 Desc = "Argument to 'delete[]' is uninitialized";
364 Desc = "Argument to 'delete' is uninitialized";
365 BugType *BT = BT_cxx_delete_undef.get();
366 auto R = llvm::make_unique<BugReport>(*BT, Desc, N);
367 bugreporter::trackNullOrUndefValue(N, DE, *R);
368 C.emitReport(std::move(R));
373 void CallAndMessageChecker::checkPreCall(const CallEvent &Call,
374 CheckerContext &C) const {
375 ProgramStateRef State = C.getState();
377 // If this is a call to a C++ method, check if the callee is null or
379 if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
380 SVal V = CC->getCXXThisVal();
382 if (!BT_cxx_call_undef)
383 BT_cxx_call_undef.reset(
384 new BuiltinBug(this, "Called C++ object pointer is uninitialized"));
385 emitBadCall(BT_cxx_call_undef.get(), C, CC->getCXXThisExpr());
389 ProgramStateRef StNonNull, StNull;
390 std::tie(StNonNull, StNull) =
391 State->assume(V.castAs<DefinedOrUnknownSVal>());
393 if (StNull && !StNonNull) {
394 if (!BT_cxx_call_null)
395 BT_cxx_call_null.reset(
396 new BuiltinBug(this, "Called C++ object pointer is null"));
397 emitBadCall(BT_cxx_call_null.get(), C, CC->getCXXThisExpr());
404 const Decl *D = Call.getDecl();
405 if (D && (isa<FunctionDecl>(D) || isa<BlockDecl>(D))) {
406 // If we have a function or block declaration, we can make sure we pass
407 // enough parameters.
408 unsigned Params = Call.parameters().size();
409 if (Call.getNumArgs() < Params) {
410 ExplodedNode *N = C.generateErrorNode();
414 LazyInit_BT("Function call with too few arguments", BT_call_few_args);
416 SmallString<512> Str;
417 llvm::raw_svector_ostream os(Str);
418 if (isa<FunctionDecl>(D)) {
421 assert(isa<BlockDecl>(D));
424 os << "taking " << Params << " argument"
425 << (Params == 1 ? "" : "s") << " is called with fewer ("
426 << Call.getNumArgs() << ")";
429 llvm::make_unique<BugReport>(*BT_call_few_args, os.str(), N));
433 // Don't check for uninitialized field values in arguments if the
434 // caller has a body that is available and we have the chance to inline it.
435 // This is a hack, but is a reasonable compromise betweens sometimes warning
436 // and sometimes not depending on if we decide to inline a function.
437 const bool checkUninitFields =
438 !(C.getAnalysisManager().shouldInlineCall() && (D && D->getBody()));
440 std::unique_ptr<BugType> *BT;
441 if (isa<ObjCMethodCall>(Call))
446 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
447 for (unsigned i = 0, e = Call.getNumArgs(); i != e; ++i) {
448 const ParmVarDecl *ParamDecl = nullptr;
449 if(FD && i < FD->getNumParams())
450 ParamDecl = FD->getParamDecl(i);
451 if (PreVisitProcessArg(C, Call.getArgSVal(i), Call.getArgSourceRange(i),
452 Call.getArgExpr(i), i,
453 checkUninitFields, Call, *BT, ParamDecl))
457 // If we make it here, record our assumptions about the callee.
458 C.addTransition(State);
461 void CallAndMessageChecker::checkPreObjCMessage(const ObjCMethodCall &msg,
462 CheckerContext &C) const {
463 SVal recVal = msg.getReceiverSVal();
464 if (recVal.isUndef()) {
465 if (ExplodedNode *N = C.generateErrorNode()) {
466 BugType *BT = nullptr;
467 switch (msg.getMessageKind()) {
470 BT_msg_undef.reset(new BuiltinBug(this,
471 "Receiver in message expression "
472 "is an uninitialized value"));
473 BT = BT_msg_undef.get();
475 case OCM_PropertyAccess:
476 if (!BT_objc_prop_undef)
477 BT_objc_prop_undef.reset(new BuiltinBug(
478 this, "Property access on an uninitialized object pointer"));
479 BT = BT_objc_prop_undef.get();
482 if (!BT_objc_subscript_undef)
483 BT_objc_subscript_undef.reset(new BuiltinBug(
484 this, "Subscript access on an uninitialized object pointer"));
485 BT = BT_objc_subscript_undef.get();
488 assert(BT && "Unknown message kind.");
490 auto R = llvm::make_unique<BugReport>(*BT, BT->getName(), N);
491 const ObjCMessageExpr *ME = msg.getOriginExpr();
492 R->addRange(ME->getReceiverRange());
494 // FIXME: getTrackNullOrUndefValueVisitor can't handle "super" yet.
495 if (const Expr *ReceiverE = ME->getInstanceReceiver())
496 bugreporter::trackNullOrUndefValue(N, ReceiverE, *R);
497 C.emitReport(std::move(R));
503 void CallAndMessageChecker::checkObjCMessageNil(const ObjCMethodCall &msg,
504 CheckerContext &C) const {
505 HandleNilReceiver(C, C.getState(), msg);
508 void CallAndMessageChecker::emitNilReceiverBug(CheckerContext &C,
509 const ObjCMethodCall &msg,
510 ExplodedNode *N) const {
514 new BuiltinBug(this, "Receiver in message expression is 'nil'"));
516 const ObjCMessageExpr *ME = msg.getOriginExpr();
518 QualType ResTy = msg.getResultType();
520 SmallString<200> buf;
521 llvm::raw_svector_ostream os(buf);
522 os << "The receiver of message '";
523 ME->getSelector().print(os);
525 if (ResTy->isReferenceType()) {
526 os << ", which results in forming a null reference";
528 os << " and returns a value of type '";
529 msg.getResultType().print(os, C.getLangOpts());
530 os << "' that will be garbage";
533 auto report = llvm::make_unique<BugReport>(*BT_msg_ret, os.str(), N);
534 report->addRange(ME->getReceiverRange());
535 // FIXME: This won't track "self" in messages to super.
536 if (const Expr *receiver = ME->getInstanceReceiver()) {
537 bugreporter::trackNullOrUndefValue(N, receiver, *report);
539 C.emitReport(std::move(report));
542 static bool supportsNilWithFloatRet(const llvm::Triple &triple) {
543 return (triple.getVendor() == llvm::Triple::Apple &&
544 (triple.isiOS() || triple.isWatchOS() ||
545 !triple.isMacOSXVersionLT(10,5)));
548 void CallAndMessageChecker::HandleNilReceiver(CheckerContext &C,
549 ProgramStateRef state,
550 const ObjCMethodCall &Msg) const {
551 ASTContext &Ctx = C.getASTContext();
552 static CheckerProgramPointTag Tag(this, "NilReceiver");
554 // Check the return type of the message expression. A message to nil will
555 // return different values depending on the return type and the architecture.
556 QualType RetTy = Msg.getResultType();
557 CanQualType CanRetTy = Ctx.getCanonicalType(RetTy);
558 const LocationContext *LCtx = C.getLocationContext();
560 if (CanRetTy->isStructureOrClassType()) {
561 // Structure returns are safe since the compiler zeroes them out.
562 SVal V = C.getSValBuilder().makeZeroVal(RetTy);
563 C.addTransition(state->BindExpr(Msg.getOriginExpr(), LCtx, V), &Tag);
567 // Other cases: check if sizeof(return type) > sizeof(void*)
568 if (CanRetTy != Ctx.VoidTy && C.getLocationContext()->getParentMap()
569 .isConsumedExpr(Msg.getOriginExpr())) {
570 // Compute: sizeof(void *) and sizeof(return type)
571 const uint64_t voidPtrSize = Ctx.getTypeSize(Ctx.VoidPtrTy);
572 const uint64_t returnTypeSize = Ctx.getTypeSize(CanRetTy);
574 if (CanRetTy.getTypePtr()->isReferenceType()||
575 (voidPtrSize < returnTypeSize &&
576 !(supportsNilWithFloatRet(Ctx.getTargetInfo().getTriple()) &&
577 (Ctx.FloatTy == CanRetTy ||
578 Ctx.DoubleTy == CanRetTy ||
579 Ctx.LongDoubleTy == CanRetTy ||
580 Ctx.LongLongTy == CanRetTy ||
581 Ctx.UnsignedLongLongTy == CanRetTy)))) {
582 if (ExplodedNode *N = C.generateErrorNode(state, &Tag))
583 emitNilReceiverBug(C, Msg, N);
587 // Handle the safe cases where the return value is 0 if the
590 // FIXME: For now take the conservative approach that we only
591 // return null values if we *know* that the receiver is nil.
592 // This is because we can have surprises like:
594 // ... = [[NSScreens screens] objectAtIndex:0];
596 // What can happen is that [... screens] could return nil, but
597 // it most likely isn't nil. We should assume the semantics
598 // of this case unless we have *a lot* more knowledge.
600 SVal V = C.getSValBuilder().makeZeroVal(RetTy);
601 C.addTransition(state->BindExpr(Msg.getOriginExpr(), LCtx, V), &Tag);
605 C.addTransition(state);
608 #define REGISTER_CHECKER(name) \
609 void ento::register##name(CheckerManager &mgr) { \
610 CallAndMessageChecker *Checker = \
611 mgr.registerChecker<CallAndMessageChecker>(); \
612 Checker->Filter.Check_##name = true; \
613 Checker->Filter.CheckName_##name = mgr.getCurrentCheckName(); \
616 REGISTER_CHECKER(CallAndMessageUnInitRefArg)
617 REGISTER_CHECKER(CallAndMessageChecker)