CallAndMessageChecker.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  1. //===--- CallAndMessageChecker.cpp ------------------------------*- C++ -*--==//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This defines CallAndMessageChecker, a builtin checker that checks for various
  10. // errors of call and objc message expressions.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/AST/ExprCXX.h"
  14. #include "clang/AST/ParentMap.h"
  15. #include "clang/Basic/TargetInfo.h"
  16. #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
  17. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  18. #include "clang/StaticAnalyzer/Core/Checker.h"
  19. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  20. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  21. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  22. #include "llvm/ADT/SmallString.h"
  23. #include "llvm/ADT/StringExtras.h"
  24. #include "llvm/Support/Casting.h"
  25. #include "llvm/Support/raw_ostream.h"
  26. using namespace clang;
  27. using namespace ento;
  28. namespace {
  29. class CallAndMessageChecker
  30. : public Checker<check::PreObjCMessage, check::ObjCMessageNil,
  31. check::PreCall> {
  32. mutable std::unique_ptr<BugType> BT_call_null;
  33. mutable std::unique_ptr<BugType> BT_call_undef;
  34. mutable std::unique_ptr<BugType> BT_cxx_call_null;
  35. mutable std::unique_ptr<BugType> BT_cxx_call_undef;
  36. mutable std::unique_ptr<BugType> BT_call_arg;
  37. mutable std::unique_ptr<BugType> BT_cxx_delete_undef;
  38. mutable std::unique_ptr<BugType> BT_msg_undef;
  39. mutable std::unique_ptr<BugType> BT_objc_prop_undef;
  40. mutable std::unique_ptr<BugType> BT_objc_subscript_undef;
  41. mutable std::unique_ptr<BugType> BT_msg_arg;
  42. mutable std::unique_ptr<BugType> BT_msg_ret;
  43. mutable std::unique_ptr<BugType> BT_call_few_args;
  44. public:
  45. // These correspond with the checker options. Looking at other checkers such
  46. // as MallocChecker and CStringChecker, this is similar as to how they pull
  47. // off having a modeling class, but emitting diagnostics under a smaller
  48. // checker's name that can be safely disabled without disturbing the
  49. // underlaying modeling engine.
  50. // The reason behind having *checker options* rather then actual *checkers*
  51. // here is that CallAndMessage is among the oldest checkers out there, and can
  52. // be responsible for the majority of the reports on any given project. This
  53. // is obviously not ideal, but changing checker name has the consequence of
  54. // changing the issue hashes associated with the reports, and databases
  55. // relying on this (CodeChecker, for instance) would suffer greatly.
  56. // If we ever end up making changes to the issue hash generation algorithm, or
  57. // the warning messages here, we should totally jump on the opportunity to
  58. // convert these to actual checkers.
  59. enum CheckKind {
  60. CK_FunctionPointer,
  61. CK_ParameterCount,
  62. CK_CXXThisMethodCall,
  63. CK_CXXDeallocationArg,
  64. CK_ArgInitializedness,
  65. CK_ArgPointeeInitializedness,
  66. CK_NilReceiver,
  67. CK_UndefReceiver,
  68. CK_NumCheckKinds
  69. };
  70. DefaultBool ChecksEnabled[CK_NumCheckKinds];
  71. // The original core.CallAndMessage checker name. This should rather be an
  72. // array, as seen in MallocChecker and CStringChecker.
  73. CheckerNameRef OriginalName;
  74. void checkPreObjCMessage(const ObjCMethodCall &msg, CheckerContext &C) const;
  75. /// Fill in the return value that results from messaging nil based on the
  76. /// return type and architecture and diagnose if the return value will be
  77. /// garbage.
  78. void checkObjCMessageNil(const ObjCMethodCall &msg, CheckerContext &C) const;
  79. void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
  80. ProgramStateRef checkFunctionPointerCall(const CallExpr *CE,
  81. CheckerContext &C,
  82. ProgramStateRef State) const;
  83. ProgramStateRef checkCXXMethodCall(const CXXInstanceCall *CC,
  84. CheckerContext &C,
  85. ProgramStateRef State) const;
  86. ProgramStateRef checkParameterCount(const CallEvent &Call, CheckerContext &C,
  87. ProgramStateRef State) const;
  88. ProgramStateRef checkCXXDeallocation(const CXXDeallocatorCall *DC,
  89. CheckerContext &C,
  90. ProgramStateRef State) const;
  91. ProgramStateRef checkArgInitializedness(const CallEvent &Call,
  92. CheckerContext &C,
  93. ProgramStateRef State) const;
  94. private:
  95. bool PreVisitProcessArg(CheckerContext &C, SVal V, SourceRange ArgRange,
  96. const Expr *ArgEx, int ArgumentNumber,
  97. bool CheckUninitFields, const CallEvent &Call,
  98. std::unique_ptr<BugType> &BT,
  99. const ParmVarDecl *ParamDecl) const;
  100. static void emitBadCall(BugType *BT, CheckerContext &C, const Expr *BadE);
  101. void emitNilReceiverBug(CheckerContext &C, const ObjCMethodCall &msg,
  102. ExplodedNode *N) const;
  103. void HandleNilReceiver(CheckerContext &C,
  104. ProgramStateRef state,
  105. const ObjCMethodCall &msg) const;
  106. void LazyInit_BT(const char *desc, std::unique_ptr<BugType> &BT) const {
  107. if (!BT)
  108. BT.reset(new BuiltinBug(OriginalName, desc));
  109. }
  110. bool uninitRefOrPointer(CheckerContext &C, const SVal &V,
  111. SourceRange ArgRange, const Expr *ArgEx,
  112. std::unique_ptr<BugType> &BT,
  113. const ParmVarDecl *ParamDecl, const char *BD,
  114. int ArgumentNumber) const;
  115. };
  116. } // end anonymous namespace
  117. void CallAndMessageChecker::emitBadCall(BugType *BT, CheckerContext &C,
  118. const Expr *BadE) {
  119. ExplodedNode *N = C.generateErrorNode();
  120. if (!N)
  121. return;
  122. auto R = std::make_unique<PathSensitiveBugReport>(*BT, BT->getDescription(), N);
  123. if (BadE) {
  124. R->addRange(BadE->getSourceRange());
  125. if (BadE->isGLValue())
  126. BadE = bugreporter::getDerefExpr(BadE);
  127. bugreporter::trackExpressionValue(N, BadE, *R);
  128. }
  129. C.emitReport(std::move(R));
  130. }
  131. static void describeUninitializedArgumentInCall(const CallEvent &Call,
  132. int ArgumentNumber,
  133. llvm::raw_svector_ostream &Os) {
  134. switch (Call.getKind()) {
  135. case CE_ObjCMessage: {
  136. const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
  137. switch (Msg.getMessageKind()) {
  138. case OCM_Message:
  139. Os << (ArgumentNumber + 1) << llvm::getOrdinalSuffix(ArgumentNumber + 1)
  140. << " argument in message expression is an uninitialized value";
  141. return;
  142. case OCM_PropertyAccess:
  143. assert(Msg.isSetter() && "Getters have no args");
  144. Os << "Argument for property setter is an uninitialized value";
  145. return;
  146. case OCM_Subscript:
  147. if (Msg.isSetter() && (ArgumentNumber == 0))
  148. Os << "Argument for subscript setter is an uninitialized value";
  149. else
  150. Os << "Subscript index is an uninitialized value";
  151. return;
  152. }
  153. llvm_unreachable("Unknown message kind.");
  154. }
  155. case CE_Block:
  156. Os << (ArgumentNumber + 1) << llvm::getOrdinalSuffix(ArgumentNumber + 1)
  157. << " block call argument is an uninitialized value";
  158. return;
  159. default:
  160. Os << (ArgumentNumber + 1) << llvm::getOrdinalSuffix(ArgumentNumber + 1)
  161. << " function call argument is an uninitialized value";
  162. return;
  163. }
  164. }
  165. bool CallAndMessageChecker::uninitRefOrPointer(
  166. CheckerContext &C, const SVal &V, SourceRange ArgRange, const Expr *ArgEx,
  167. std::unique_ptr<BugType> &BT, const ParmVarDecl *ParamDecl, const char *BD,
  168. int ArgumentNumber) const {
  169. // The pointee being uninitialized is a sign of code smell, not a bug, no need
  170. // to sink here.
  171. if (!ChecksEnabled[CK_ArgPointeeInitializedness])
  172. return false;
  173. // No parameter declaration available, i.e. variadic function argument.
  174. if(!ParamDecl)
  175. return false;
  176. // If parameter is declared as pointer to const in function declaration,
  177. // then check if corresponding argument in function call is
  178. // pointing to undefined symbol value (uninitialized memory).
  179. SmallString<200> Buf;
  180. llvm::raw_svector_ostream Os(Buf);
  181. if (ParamDecl->getType()->isPointerType()) {
  182. Os << (ArgumentNumber + 1) << llvm::getOrdinalSuffix(ArgumentNumber + 1)
  183. << " function call argument is a pointer to uninitialized value";
  184. } else if (ParamDecl->getType()->isReferenceType()) {
  185. Os << (ArgumentNumber + 1) << llvm::getOrdinalSuffix(ArgumentNumber + 1)
  186. << " function call argument is an uninitialized value";
  187. } else
  188. return false;
  189. if(!ParamDecl->getType()->getPointeeType().isConstQualified())
  190. return false;
  191. if (const MemRegion *SValMemRegion = V.getAsRegion()) {
  192. const ProgramStateRef State = C.getState();
  193. const SVal PSV = State->getSVal(SValMemRegion, C.getASTContext().CharTy);
  194. if (PSV.isUndef()) {
  195. if (ExplodedNode *N = C.generateErrorNode()) {
  196. LazyInit_BT(BD, BT);
  197. auto R = std::make_unique<PathSensitiveBugReport>(*BT, Os.str(), N);
  198. R->addRange(ArgRange);
  199. if (ArgEx)
  200. bugreporter::trackExpressionValue(N, ArgEx, *R);
  201. C.emitReport(std::move(R));
  202. }
  203. return true;
  204. }
  205. }
  206. return false;
  207. }
  208. namespace {
  209. class FindUninitializedField {
  210. public:
  211. SmallVector<const FieldDecl *, 10> FieldChain;
  212. private:
  213. StoreManager &StoreMgr;
  214. MemRegionManager &MrMgr;
  215. Store store;
  216. public:
  217. FindUninitializedField(StoreManager &storeMgr, MemRegionManager &mrMgr,
  218. Store s)
  219. : StoreMgr(storeMgr), MrMgr(mrMgr), store(s) {}
  220. bool Find(const TypedValueRegion *R) {
  221. QualType T = R->getValueType();
  222. if (const RecordType *RT = T->getAsStructureType()) {
  223. const RecordDecl *RD = RT->getDecl()->getDefinition();
  224. assert(RD && "Referred record has no definition");
  225. for (const auto *I : RD->fields()) {
  226. const FieldRegion *FR = MrMgr.getFieldRegion(I, R);
  227. FieldChain.push_back(I);
  228. T = I->getType();
  229. if (T->getAsStructureType()) {
  230. if (Find(FR))
  231. return true;
  232. } else {
  233. const SVal &V = StoreMgr.getBinding(store, loc::MemRegionVal(FR));
  234. if (V.isUndef())
  235. return true;
  236. }
  237. FieldChain.pop_back();
  238. }
  239. }
  240. return false;
  241. }
  242. };
  243. } // namespace
  244. bool CallAndMessageChecker::PreVisitProcessArg(CheckerContext &C,
  245. SVal V,
  246. SourceRange ArgRange,
  247. const Expr *ArgEx,
  248. int ArgumentNumber,
  249. bool CheckUninitFields,
  250. const CallEvent &Call,
  251. std::unique_ptr<BugType> &BT,
  252. const ParmVarDecl *ParamDecl
  253. ) const {
  254. const char *BD = "Uninitialized argument value";
  255. if (uninitRefOrPointer(C, V, ArgRange, ArgEx, BT, ParamDecl, BD,
  256. ArgumentNumber))
  257. return true;
  258. if (V.isUndef()) {
  259. if (!ChecksEnabled[CK_ArgInitializedness]) {
  260. C.addSink();
  261. return true;
  262. }
  263. if (ExplodedNode *N = C.generateErrorNode()) {
  264. LazyInit_BT(BD, BT);
  265. // Generate a report for this bug.
  266. SmallString<200> Buf;
  267. llvm::raw_svector_ostream Os(Buf);
  268. describeUninitializedArgumentInCall(Call, ArgumentNumber, Os);
  269. auto R = std::make_unique<PathSensitiveBugReport>(*BT, Os.str(), N);
  270. R->addRange(ArgRange);
  271. if (ArgEx)
  272. bugreporter::trackExpressionValue(N, ArgEx, *R);
  273. C.emitReport(std::move(R));
  274. }
  275. return true;
  276. }
  277. if (!CheckUninitFields)
  278. return false;
  279. if (auto LV = V.getAs<nonloc::LazyCompoundVal>()) {
  280. const LazyCompoundValData *D = LV->getCVData();
  281. FindUninitializedField F(C.getState()->getStateManager().getStoreManager(),
  282. C.getSValBuilder().getRegionManager(),
  283. D->getStore());
  284. if (F.Find(D->getRegion())) {
  285. if (!ChecksEnabled[CK_ArgInitializedness]) {
  286. C.addSink();
  287. return true;
  288. }
  289. if (ExplodedNode *N = C.generateErrorNode()) {
  290. LazyInit_BT(BD, BT);
  291. SmallString<512> Str;
  292. llvm::raw_svector_ostream os(Str);
  293. os << "Passed-by-value struct argument contains uninitialized data";
  294. if (F.FieldChain.size() == 1)
  295. os << " (e.g., field: '" << *F.FieldChain[0] << "')";
  296. else {
  297. os << " (e.g., via the field chain: '";
  298. bool first = true;
  299. for (SmallVectorImpl<const FieldDecl *>::iterator
  300. DI = F.FieldChain.begin(), DE = F.FieldChain.end(); DI!=DE;++DI){
  301. if (first)
  302. first = false;
  303. else
  304. os << '.';
  305. os << **DI;
  306. }
  307. os << "')";
  308. }
  309. // Generate a report for this bug.
  310. auto R = std::make_unique<PathSensitiveBugReport>(*BT, os.str(), N);
  311. R->addRange(ArgRange);
  312. if (ArgEx)
  313. bugreporter::trackExpressionValue(N, ArgEx, *R);
  314. // FIXME: enhance track back for uninitialized value for arbitrary
  315. // memregions
  316. C.emitReport(std::move(R));
  317. }
  318. return true;
  319. }
  320. }
  321. return false;
  322. }
  323. ProgramStateRef CallAndMessageChecker::checkFunctionPointerCall(
  324. const CallExpr *CE, CheckerContext &C, ProgramStateRef State) const {
  325. const Expr *Callee = CE->getCallee()->IgnoreParens();
  326. const LocationContext *LCtx = C.getLocationContext();
  327. SVal L = State->getSVal(Callee, LCtx);
  328. if (L.isUndef()) {
  329. if (!ChecksEnabled[CK_FunctionPointer]) {
  330. C.addSink(State);
  331. return nullptr;
  332. }
  333. if (!BT_call_undef)
  334. BT_call_undef.reset(new BuiltinBug(
  335. OriginalName,
  336. "Called function pointer is an uninitialized pointer value"));
  337. emitBadCall(BT_call_undef.get(), C, Callee);
  338. return nullptr;
  339. }
  340. ProgramStateRef StNonNull, StNull;
  341. std::tie(StNonNull, StNull) = State->assume(L.castAs<DefinedOrUnknownSVal>());
  342. if (StNull && !StNonNull) {
  343. if (!ChecksEnabled[CK_FunctionPointer]) {
  344. C.addSink(StNull);
  345. return nullptr;
  346. }
  347. if (!BT_call_null)
  348. BT_call_null.reset(new BuiltinBug(
  349. OriginalName, "Called function pointer is null (null dereference)"));
  350. emitBadCall(BT_call_null.get(), C, Callee);
  351. return nullptr;
  352. }
  353. return StNonNull;
  354. }
  355. ProgramStateRef CallAndMessageChecker::checkParameterCount(
  356. const CallEvent &Call, CheckerContext &C, ProgramStateRef State) const {
  357. // If we have a function or block declaration, we can make sure we pass
  358. // enough parameters.
  359. unsigned Params = Call.parameters().size();
  360. if (Call.getNumArgs() >= Params)
  361. return State;
  362. if (!ChecksEnabled[CK_ParameterCount]) {
  363. C.addSink(State);
  364. return nullptr;
  365. }
  366. ExplodedNode *N = C.generateErrorNode();
  367. if (!N)
  368. return nullptr;
  369. LazyInit_BT("Function call with too few arguments", BT_call_few_args);
  370. SmallString<512> Str;
  371. llvm::raw_svector_ostream os(Str);
  372. if (isa<AnyFunctionCall>(Call)) {
  373. os << "Function ";
  374. } else {
  375. assert(isa<BlockCall>(Call));
  376. os << "Block ";
  377. }
  378. os << "taking " << Params << " argument" << (Params == 1 ? "" : "s")
  379. << " is called with fewer (" << Call.getNumArgs() << ")";
  380. C.emitReport(
  381. std::make_unique<PathSensitiveBugReport>(*BT_call_few_args, os.str(), N));
  382. return nullptr;
  383. }
  384. ProgramStateRef CallAndMessageChecker::checkCXXMethodCall(
  385. const CXXInstanceCall *CC, CheckerContext &C, ProgramStateRef State) const {
  386. SVal V = CC->getCXXThisVal();
  387. if (V.isUndef()) {
  388. if (!ChecksEnabled[CK_CXXThisMethodCall]) {
  389. C.addSink(State);
  390. return nullptr;
  391. }
  392. if (!BT_cxx_call_undef)
  393. BT_cxx_call_undef.reset(new BuiltinBug(
  394. OriginalName, "Called C++ object pointer is uninitialized"));
  395. emitBadCall(BT_cxx_call_undef.get(), C, CC->getCXXThisExpr());
  396. return nullptr;
  397. }
  398. ProgramStateRef StNonNull, StNull;
  399. std::tie(StNonNull, StNull) = State->assume(V.castAs<DefinedOrUnknownSVal>());
  400. if (StNull && !StNonNull) {
  401. if (!ChecksEnabled[CK_CXXThisMethodCall]) {
  402. C.addSink(StNull);
  403. return nullptr;
  404. }
  405. if (!BT_cxx_call_null)
  406. BT_cxx_call_null.reset(
  407. new BuiltinBug(OriginalName, "Called C++ object pointer is null"));
  408. emitBadCall(BT_cxx_call_null.get(), C, CC->getCXXThisExpr());
  409. return nullptr;
  410. }
  411. return StNonNull;
  412. }
  413. ProgramStateRef
  414. CallAndMessageChecker::checkCXXDeallocation(const CXXDeallocatorCall *DC,
  415. CheckerContext &C,
  416. ProgramStateRef State) const {
  417. const CXXDeleteExpr *DE = DC->getOriginExpr();
  418. assert(DE);
  419. SVal Arg = C.getSVal(DE->getArgument());
  420. if (!Arg.isUndef())
  421. return State;
  422. if (!ChecksEnabled[CK_CXXDeallocationArg]) {
  423. C.addSink(State);
  424. return nullptr;
  425. }
  426. StringRef Desc;
  427. ExplodedNode *N = C.generateErrorNode();
  428. if (!N)
  429. return nullptr;
  430. if (!BT_cxx_delete_undef)
  431. BT_cxx_delete_undef.reset(
  432. new BuiltinBug(OriginalName, "Uninitialized argument value"));
  433. if (DE->isArrayFormAsWritten())
  434. Desc = "Argument to 'delete[]' is uninitialized";
  435. else
  436. Desc = "Argument to 'delete' is uninitialized";
  437. BugType *BT = BT_cxx_delete_undef.get();
  438. auto R = std::make_unique<PathSensitiveBugReport>(*BT, Desc, N);
  439. bugreporter::trackExpressionValue(N, DE, *R);
  440. C.emitReport(std::move(R));
  441. return nullptr;
  442. }
  443. ProgramStateRef CallAndMessageChecker::checkArgInitializedness(
  444. const CallEvent &Call, CheckerContext &C, ProgramStateRef State) const {
  445. const Decl *D = Call.getDecl();
  446. // Don't check for uninitialized field values in arguments if the
  447. // caller has a body that is available and we have the chance to inline it.
  448. // This is a hack, but is a reasonable compromise betweens sometimes warning
  449. // and sometimes not depending on if we decide to inline a function.
  450. const bool checkUninitFields =
  451. !(C.getAnalysisManager().shouldInlineCall() && (D && D->getBody()));
  452. std::unique_ptr<BugType> *BT;
  453. if (isa<ObjCMethodCall>(Call))
  454. BT = &BT_msg_arg;
  455. else
  456. BT = &BT_call_arg;
  457. const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
  458. for (unsigned i = 0, e = Call.getNumArgs(); i != e; ++i) {
  459. const ParmVarDecl *ParamDecl = nullptr;
  460. if (FD && i < FD->getNumParams())
  461. ParamDecl = FD->getParamDecl(i);
  462. if (PreVisitProcessArg(C, Call.getArgSVal(i), Call.getArgSourceRange(i),
  463. Call.getArgExpr(i), i, checkUninitFields, Call, *BT,
  464. ParamDecl))
  465. return nullptr;
  466. }
  467. return State;
  468. }
  469. void CallAndMessageChecker::checkPreCall(const CallEvent &Call,
  470. CheckerContext &C) const {
  471. ProgramStateRef State = C.getState();
  472. if (const CallExpr *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr()))
  473. State = checkFunctionPointerCall(CE, C, State);
  474. if (!State)
  475. return;
  476. if (Call.getDecl())
  477. State = checkParameterCount(Call, C, State);
  478. if (!State)
  479. return;
  480. if (const auto *CC = dyn_cast<CXXInstanceCall>(&Call))
  481. State = checkCXXMethodCall(CC, C, State);
  482. if (!State)
  483. return;
  484. if (const auto *DC = dyn_cast<CXXDeallocatorCall>(&Call))
  485. State = checkCXXDeallocation(DC, C, State);
  486. if (!State)
  487. return;
  488. State = checkArgInitializedness(Call, C, State);
  489. // If we make it here, record our assumptions about the callee.
  490. C.addTransition(State);
  491. }
  492. void CallAndMessageChecker::checkPreObjCMessage(const ObjCMethodCall &msg,
  493. CheckerContext &C) const {
  494. SVal recVal = msg.getReceiverSVal();
  495. if (recVal.isUndef()) {
  496. if (!ChecksEnabled[CK_UndefReceiver]) {
  497. C.addSink();
  498. return;
  499. }
  500. if (ExplodedNode *N = C.generateErrorNode()) {
  501. BugType *BT = nullptr;
  502. switch (msg.getMessageKind()) {
  503. case OCM_Message:
  504. if (!BT_msg_undef)
  505. BT_msg_undef.reset(new BuiltinBug(OriginalName,
  506. "Receiver in message expression "
  507. "is an uninitialized value"));
  508. BT = BT_msg_undef.get();
  509. break;
  510. case OCM_PropertyAccess:
  511. if (!BT_objc_prop_undef)
  512. BT_objc_prop_undef.reset(new BuiltinBug(
  513. OriginalName,
  514. "Property access on an uninitialized object pointer"));
  515. BT = BT_objc_prop_undef.get();
  516. break;
  517. case OCM_Subscript:
  518. if (!BT_objc_subscript_undef)
  519. BT_objc_subscript_undef.reset(new BuiltinBug(
  520. OriginalName,
  521. "Subscript access on an uninitialized object pointer"));
  522. BT = BT_objc_subscript_undef.get();
  523. break;
  524. }
  525. assert(BT && "Unknown message kind.");
  526. auto R = std::make_unique<PathSensitiveBugReport>(*BT, BT->getDescription(), N);
  527. const ObjCMessageExpr *ME = msg.getOriginExpr();
  528. R->addRange(ME->getReceiverRange());
  529. // FIXME: getTrackNullOrUndefValueVisitor can't handle "super" yet.
  530. if (const Expr *ReceiverE = ME->getInstanceReceiver())
  531. bugreporter::trackExpressionValue(N, ReceiverE, *R);
  532. C.emitReport(std::move(R));
  533. }
  534. return;
  535. }
  536. }
  537. void CallAndMessageChecker::checkObjCMessageNil(const ObjCMethodCall &msg,
  538. CheckerContext &C) const {
  539. HandleNilReceiver(C, C.getState(), msg);
  540. }
  541. void CallAndMessageChecker::emitNilReceiverBug(CheckerContext &C,
  542. const ObjCMethodCall &msg,
  543. ExplodedNode *N) const {
  544. if (!ChecksEnabled[CK_NilReceiver]) {
  545. C.addSink();
  546. return;
  547. }
  548. if (!BT_msg_ret)
  549. BT_msg_ret.reset(new BuiltinBug(OriginalName,
  550. "Receiver in message expression is 'nil'"));
  551. const ObjCMessageExpr *ME = msg.getOriginExpr();
  552. QualType ResTy = msg.getResultType();
  553. SmallString<200> buf;
  554. llvm::raw_svector_ostream os(buf);
  555. os << "The receiver of message '";
  556. ME->getSelector().print(os);
  557. os << "' is nil";
  558. if (ResTy->isReferenceType()) {
  559. os << ", which results in forming a null reference";
  560. } else {
  561. os << " and returns a value of type '";
  562. msg.getResultType().print(os, C.getLangOpts());
  563. os << "' that will be garbage";
  564. }
  565. auto report =
  566. std::make_unique<PathSensitiveBugReport>(*BT_msg_ret, os.str(), N);
  567. report->addRange(ME->getReceiverRange());
  568. // FIXME: This won't track "self" in messages to super.
  569. if (const Expr *receiver = ME->getInstanceReceiver()) {
  570. bugreporter::trackExpressionValue(N, receiver, *report);
  571. }
  572. C.emitReport(std::move(report));
  573. }
  574. static bool supportsNilWithFloatRet(const llvm::Triple &triple) {
  575. return (triple.getVendor() == llvm::Triple::Apple &&
  576. (triple.isiOS() || triple.isWatchOS() ||
  577. !triple.isMacOSXVersionLT(10,5)));
  578. }
  579. void CallAndMessageChecker::HandleNilReceiver(CheckerContext &C,
  580. ProgramStateRef state,
  581. const ObjCMethodCall &Msg) const {
  582. ASTContext &Ctx = C.getASTContext();
  583. static CheckerProgramPointTag Tag(this, "NilReceiver");
  584. // Check the return type of the message expression. A message to nil will
  585. // return different values depending on the return type and the architecture.
  586. QualType RetTy = Msg.getResultType();
  587. CanQualType CanRetTy = Ctx.getCanonicalType(RetTy);
  588. const LocationContext *LCtx = C.getLocationContext();
  589. if (CanRetTy->isStructureOrClassType()) {
  590. // Structure returns are safe since the compiler zeroes them out.
  591. SVal V = C.getSValBuilder().makeZeroVal(RetTy);
  592. C.addTransition(state->BindExpr(Msg.getOriginExpr(), LCtx, V), &Tag);
  593. return;
  594. }
  595. // Other cases: check if sizeof(return type) > sizeof(void*)
  596. if (CanRetTy != Ctx.VoidTy && C.getLocationContext()->getParentMap()
  597. .isConsumedExpr(Msg.getOriginExpr())) {
  598. // Compute: sizeof(void *) and sizeof(return type)
  599. const uint64_t voidPtrSize = Ctx.getTypeSize(Ctx.VoidPtrTy);
  600. const uint64_t returnTypeSize = Ctx.getTypeSize(CanRetTy);
  601. if (CanRetTy.getTypePtr()->isReferenceType()||
  602. (voidPtrSize < returnTypeSize &&
  603. !(supportsNilWithFloatRet(Ctx.getTargetInfo().getTriple()) &&
  604. (Ctx.FloatTy == CanRetTy ||
  605. Ctx.DoubleTy == CanRetTy ||
  606. Ctx.LongDoubleTy == CanRetTy ||
  607. Ctx.LongLongTy == CanRetTy ||
  608. Ctx.UnsignedLongLongTy == CanRetTy)))) {
  609. if (ExplodedNode *N = C.generateErrorNode(state, &Tag))
  610. emitNilReceiverBug(C, Msg, N);
  611. return;
  612. }
  613. // Handle the safe cases where the return value is 0 if the
  614. // receiver is nil.
  615. //
  616. // FIXME: For now take the conservative approach that we only
  617. // return null values if we *know* that the receiver is nil.
  618. // This is because we can have surprises like:
  619. //
  620. // ... = [[NSScreens screens] objectAtIndex:0];
  621. //
  622. // What can happen is that [... screens] could return nil, but
  623. // it most likely isn't nil. We should assume the semantics
  624. // of this case unless we have *a lot* more knowledge.
  625. //
  626. SVal V = C.getSValBuilder().makeZeroVal(RetTy);
  627. C.addTransition(state->BindExpr(Msg.getOriginExpr(), LCtx, V), &Tag);
  628. return;
  629. }
  630. C.addTransition(state);
  631. }
  632. void ento::registerCallAndMessageModeling(CheckerManager &mgr) {
  633. mgr.registerChecker<CallAndMessageChecker>();
  634. }
  635. bool ento::shouldRegisterCallAndMessageModeling(const CheckerManager &mgr) {
  636. return true;
  637. }
  638. void ento::registerCallAndMessageChecker(CheckerManager &mgr) {
  639. CallAndMessageChecker *checker = mgr.getChecker<CallAndMessageChecker>();
  640. checker->OriginalName = mgr.getCurrentCheckerName();
  641. #define QUERY_CHECKER_OPTION(OPTION) \
  642. checker->ChecksEnabled[CallAndMessageChecker::CK_##OPTION] = \
  643. mgr.getAnalyzerOptions().getCheckerBooleanOption( \
  644. mgr.getCurrentCheckerName(), #OPTION);
  645. QUERY_CHECKER_OPTION(FunctionPointer)
  646. QUERY_CHECKER_OPTION(ParameterCount)
  647. QUERY_CHECKER_OPTION(CXXThisMethodCall)
  648. QUERY_CHECKER_OPTION(CXXDeallocationArg)
  649. QUERY_CHECKER_OPTION(ArgInitializedness)
  650. QUERY_CHECKER_OPTION(ArgPointeeInitializedness)
  651. QUERY_CHECKER_OPTION(NilReceiver)
  652. QUERY_CHECKER_OPTION(UndefReceiver)
  653. }
  654. bool ento::shouldRegisterCallAndMessageChecker(const CheckerManager &mgr) {
  655. return true;
  656. }