NonNullParamChecker.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. //===--- NonNullParamChecker.cpp - Undefined arguments checker -*- 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 NonNullParamChecker, which checks for arguments expected not to
  10. // be null due to:
  11. // - the corresponding parameters being declared to have nonnull attribute
  12. // - the corresponding parameters being references; since the call would form
  13. // a reference to a null pointer
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #include "clang/AST/Attr.h"
  17. #include "clang/Analysis/AnyCall.h"
  18. #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
  19. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  20. #include "clang/StaticAnalyzer/Core/Checker.h"
  21. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  22. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  23. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  24. #include "llvm/ADT/StringExtras.h"
  25. using namespace clang;
  26. using namespace ento;
  27. namespace {
  28. class NonNullParamChecker
  29. : public Checker<check::PreCall, check::BeginFunction,
  30. EventDispatcher<ImplicitNullDerefEvent>> {
  31. mutable std::unique_ptr<BugType> BTAttrNonNull;
  32. mutable std::unique_ptr<BugType> BTNullRefArg;
  33. public:
  34. void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
  35. void checkBeginFunction(CheckerContext &C) const;
  36. std::unique_ptr<PathSensitiveBugReport>
  37. genReportNullAttrNonNull(const ExplodedNode *ErrorN, const Expr *ArgE,
  38. unsigned IdxOfArg) const;
  39. std::unique_ptr<PathSensitiveBugReport>
  40. genReportReferenceToNullPointer(const ExplodedNode *ErrorN,
  41. const Expr *ArgE) const;
  42. };
  43. template <class CallType>
  44. void setBitsAccordingToFunctionAttributes(const CallType &Call,
  45. llvm::SmallBitVector &AttrNonNull) {
  46. const Decl *FD = Call.getDecl();
  47. for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
  48. if (!NonNull->args_size()) {
  49. // Lack of attribute parameters means that all of the parameters are
  50. // implicitly marked as non-null.
  51. AttrNonNull.set();
  52. break;
  53. }
  54. for (const ParamIdx &Idx : NonNull->args()) {
  55. // 'nonnull' attribute's parameters are 1-based and should be adjusted to
  56. // match actual AST parameter/argument indices.
  57. unsigned IdxAST = Idx.getASTIndex();
  58. if (IdxAST >= AttrNonNull.size())
  59. continue;
  60. AttrNonNull.set(IdxAST);
  61. }
  62. }
  63. }
  64. template <class CallType>
  65. void setBitsAccordingToParameterAttributes(const CallType &Call,
  66. llvm::SmallBitVector &AttrNonNull) {
  67. for (const ParmVarDecl *Parameter : Call.parameters()) {
  68. unsigned ParameterIndex = Parameter->getFunctionScopeIndex();
  69. if (ParameterIndex == AttrNonNull.size())
  70. break;
  71. if (Parameter->hasAttr<NonNullAttr>())
  72. AttrNonNull.set(ParameterIndex);
  73. }
  74. }
  75. template <class CallType>
  76. llvm::SmallBitVector getNonNullAttrsImpl(const CallType &Call,
  77. unsigned ExpectedSize) {
  78. llvm::SmallBitVector AttrNonNull(ExpectedSize);
  79. setBitsAccordingToFunctionAttributes(Call, AttrNonNull);
  80. setBitsAccordingToParameterAttributes(Call, AttrNonNull);
  81. return AttrNonNull;
  82. }
  83. /// \return Bitvector marking non-null attributes.
  84. llvm::SmallBitVector getNonNullAttrs(const CallEvent &Call) {
  85. return getNonNullAttrsImpl(Call, Call.getNumArgs());
  86. }
  87. /// \return Bitvector marking non-null attributes.
  88. llvm::SmallBitVector getNonNullAttrs(const AnyCall &Call) {
  89. return getNonNullAttrsImpl(Call, Call.param_size());
  90. }
  91. } // end anonymous namespace
  92. void NonNullParamChecker::checkPreCall(const CallEvent &Call,
  93. CheckerContext &C) const {
  94. if (!Call.getDecl())
  95. return;
  96. llvm::SmallBitVector AttrNonNull = getNonNullAttrs(Call);
  97. unsigned NumArgs = Call.getNumArgs();
  98. ProgramStateRef state = C.getState();
  99. ArrayRef<ParmVarDecl *> parms = Call.parameters();
  100. for (unsigned idx = 0; idx < NumArgs; ++idx) {
  101. // For vararg functions, a corresponding parameter decl may not exist.
  102. bool HasParam = idx < parms.size();
  103. // Check if the parameter is a reference. We want to report when reference
  104. // to a null pointer is passed as a parameter.
  105. bool HasRefTypeParam =
  106. HasParam ? parms[idx]->getType()->isReferenceType() : false;
  107. bool ExpectedToBeNonNull = AttrNonNull.test(idx);
  108. if (!ExpectedToBeNonNull && !HasRefTypeParam)
  109. continue;
  110. // If the value is unknown or undefined, we can't perform this check.
  111. const Expr *ArgE = Call.getArgExpr(idx);
  112. SVal V = Call.getArgSVal(idx);
  113. auto DV = V.getAs<DefinedSVal>();
  114. if (!DV)
  115. continue;
  116. assert(!HasRefTypeParam || DV->getAs<Loc>());
  117. // Process the case when the argument is not a location.
  118. if (ExpectedToBeNonNull && !DV->getAs<Loc>()) {
  119. // If the argument is a union type, we want to handle a potential
  120. // transparent_union GCC extension.
  121. if (!ArgE)
  122. continue;
  123. QualType T = ArgE->getType();
  124. const RecordType *UT = T->getAsUnionType();
  125. if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
  126. continue;
  127. auto CSV = DV->getAs<nonloc::CompoundVal>();
  128. // FIXME: Handle LazyCompoundVals?
  129. if (!CSV)
  130. continue;
  131. V = *(CSV->begin());
  132. DV = V.getAs<DefinedSVal>();
  133. assert(++CSV->begin() == CSV->end());
  134. // FIXME: Handle (some_union){ some_other_union_val }, which turns into
  135. // a LazyCompoundVal inside a CompoundVal.
  136. if (!V.getAs<Loc>())
  137. continue;
  138. // Retrieve the corresponding expression.
  139. if (const auto *CE = dyn_cast<CompoundLiteralExpr>(ArgE))
  140. if (const auto *IE = dyn_cast<InitListExpr>(CE->getInitializer()))
  141. ArgE = dyn_cast<Expr>(*(IE->begin()));
  142. }
  143. ConstraintManager &CM = C.getConstraintManager();
  144. ProgramStateRef stateNotNull, stateNull;
  145. std::tie(stateNotNull, stateNull) = CM.assumeDual(state, *DV);
  146. // Generate an error node. Check for a null node in case
  147. // we cache out.
  148. if (stateNull && !stateNotNull) {
  149. if (ExplodedNode *errorNode = C.generateErrorNode(stateNull)) {
  150. std::unique_ptr<BugReport> R;
  151. if (ExpectedToBeNonNull)
  152. R = genReportNullAttrNonNull(errorNode, ArgE, idx + 1);
  153. else if (HasRefTypeParam)
  154. R = genReportReferenceToNullPointer(errorNode, ArgE);
  155. // Highlight the range of the argument that was null.
  156. R->addRange(Call.getArgSourceRange(idx));
  157. // Emit the bug report.
  158. C.emitReport(std::move(R));
  159. }
  160. // Always return. Either we cached out or we just emitted an error.
  161. return;
  162. }
  163. if (stateNull) {
  164. if (ExplodedNode *N = C.generateSink(stateNull, C.getPredecessor())) {
  165. ImplicitNullDerefEvent event = {
  166. V, false, N, &C.getBugReporter(),
  167. /*IsDirectDereference=*/HasRefTypeParam};
  168. dispatchEvent(event);
  169. }
  170. }
  171. // If a pointer value passed the check we should assume that it is
  172. // indeed not null from this point forward.
  173. state = stateNotNull;
  174. }
  175. // If we reach here all of the arguments passed the nonnull check.
  176. // If 'state' has been updated generated a new node.
  177. C.addTransition(state);
  178. }
  179. /// We want to trust developer annotations and consider all 'nonnull' parameters
  180. /// as non-null indeed. Each marked parameter will get a corresponding
  181. /// constraint.
  182. ///
  183. /// This approach will not only help us to get rid of some false positives, but
  184. /// remove duplicates and shorten warning traces as well.
  185. ///
  186. /// \code
  187. /// void foo(int *x) [[gnu::nonnull]] {
  188. /// // . . .
  189. /// *x = 42; // we don't want to consider this as an error...
  190. /// // . . .
  191. /// }
  192. ///
  193. /// foo(nullptr); // ...and report here instead
  194. /// \endcode
  195. void NonNullParamChecker::checkBeginFunction(CheckerContext &Context) const {
  196. // Planned assumption makes sense only for top-level functions.
  197. // Inlined functions will get similar constraints as part of 'checkPreCall'.
  198. if (!Context.inTopFrame())
  199. return;
  200. const LocationContext *LocContext = Context.getLocationContext();
  201. const Decl *FD = LocContext->getDecl();
  202. // AnyCall helps us here to avoid checking for FunctionDecl and ObjCMethodDecl
  203. // separately and aggregates interfaces of these classes.
  204. auto AbstractCall = AnyCall::forDecl(FD);
  205. if (!AbstractCall)
  206. return;
  207. ProgramStateRef State = Context.getState();
  208. llvm::SmallBitVector ParameterNonNullMarks = getNonNullAttrs(*AbstractCall);
  209. for (const ParmVarDecl *Parameter : AbstractCall->parameters()) {
  210. // 1. Check parameter if it is annotated as non-null
  211. if (!ParameterNonNullMarks.test(Parameter->getFunctionScopeIndex()))
  212. continue;
  213. // 2. Check that parameter is a pointer.
  214. // Nonnull attribute can be applied to non-pointers (by default
  215. // __attribute__(nonnull) implies "all parameters").
  216. if (!Parameter->getType()->isPointerType())
  217. continue;
  218. Loc ParameterLoc = State->getLValue(Parameter, LocContext);
  219. // We never consider top-level function parameters undefined.
  220. auto StoredVal =
  221. State->getSVal(ParameterLoc).castAs<DefinedOrUnknownSVal>();
  222. // 3. Assume that it is indeed non-null
  223. if (ProgramStateRef NewState = State->assume(StoredVal, true)) {
  224. State = NewState;
  225. }
  226. }
  227. Context.addTransition(State);
  228. }
  229. std::unique_ptr<PathSensitiveBugReport>
  230. NonNullParamChecker::genReportNullAttrNonNull(const ExplodedNode *ErrorNode,
  231. const Expr *ArgE,
  232. unsigned IdxOfArg) const {
  233. // Lazily allocate the BugType object if it hasn't already been
  234. // created. Ownership is transferred to the BugReporter object once
  235. // the BugReport is passed to 'EmitWarning'.
  236. if (!BTAttrNonNull)
  237. BTAttrNonNull.reset(new BugType(
  238. this, "Argument with 'nonnull' attribute passed null", "API"));
  239. llvm::SmallString<256> SBuf;
  240. llvm::raw_svector_ostream OS(SBuf);
  241. OS << "Null pointer passed to "
  242. << IdxOfArg << llvm::getOrdinalSuffix(IdxOfArg)
  243. << " parameter expecting 'nonnull'";
  244. auto R =
  245. std::make_unique<PathSensitiveBugReport>(*BTAttrNonNull, SBuf, ErrorNode);
  246. if (ArgE)
  247. bugreporter::trackExpressionValue(ErrorNode, ArgE, *R);
  248. return R;
  249. }
  250. std::unique_ptr<PathSensitiveBugReport>
  251. NonNullParamChecker::genReportReferenceToNullPointer(
  252. const ExplodedNode *ErrorNode, const Expr *ArgE) const {
  253. if (!BTNullRefArg)
  254. BTNullRefArg.reset(new BuiltinBug(this, "Dereference of null pointer"));
  255. auto R = std::make_unique<PathSensitiveBugReport>(
  256. *BTNullRefArg, "Forming reference to null pointer", ErrorNode);
  257. if (ArgE) {
  258. const Expr *ArgEDeref = bugreporter::getDerefExpr(ArgE);
  259. if (!ArgEDeref)
  260. ArgEDeref = ArgE;
  261. bugreporter::trackExpressionValue(ErrorNode, ArgEDeref, *R);
  262. }
  263. return R;
  264. }
  265. void ento::registerNonNullParamChecker(CheckerManager &mgr) {
  266. mgr.registerChecker<NonNullParamChecker>();
  267. }
  268. bool ento::shouldRegisterNonNullParamChecker(const CheckerManager &mgr) {
  269. return true;
  270. }