UnixAPIChecker.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. //= UnixAPIChecker.h - Checks preconditions for various Unix APIs --*- C++ -*-//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This defines UnixAPIChecker, which is an assortment of checks on calls
  11. // to various, widely used UNIX/Posix functions.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "InternalChecks.h"
  15. #include "clang/Basic/TargetInfo.h"
  16. #include "clang/StaticAnalyzer/BugReporter/BugType.h"
  17. #include "clang/StaticAnalyzer/PathSensitive/CheckerVisitor.h"
  18. #include "llvm/ADT/Optional.h"
  19. #include "llvm/ADT/StringSwitch.h"
  20. #include <fcntl.h>
  21. using namespace clang;
  22. using namespace ento;
  23. using llvm::Optional;
  24. namespace {
  25. class UnixAPIChecker : public CheckerVisitor<UnixAPIChecker> {
  26. enum SubChecks {
  27. OpenFn = 0,
  28. PthreadOnceFn = 1,
  29. MallocZero = 2,
  30. NumChecks
  31. };
  32. BugType *BTypes[NumChecks];
  33. public:
  34. Optional<uint64_t> Val_O_CREAT;
  35. public:
  36. UnixAPIChecker() { memset(BTypes, 0, sizeof(*BTypes) * NumChecks); }
  37. static void *getTag() { static unsigned tag = 0; return &tag; }
  38. void PreVisitCallExpr(CheckerContext &C, const CallExpr *CE);
  39. };
  40. } //end anonymous namespace
  41. void ento::RegisterUnixAPIChecker(ExprEngine &Eng) {
  42. Eng.registerCheck(new UnixAPIChecker());
  43. }
  44. //===----------------------------------------------------------------------===//
  45. // Utility functions.
  46. //===----------------------------------------------------------------------===//
  47. static inline void LazyInitialize(BugType *&BT, const char *name) {
  48. if (BT)
  49. return;
  50. BT = new BugType(name, "Unix API");
  51. }
  52. //===----------------------------------------------------------------------===//
  53. // "open" (man 2 open)
  54. //===----------------------------------------------------------------------===//
  55. static void CheckOpen(CheckerContext &C, UnixAPIChecker &UC,
  56. const CallExpr *CE, BugType *&BT) {
  57. // The definition of O_CREAT is platform specific. We need a better way
  58. // of querying this information from the checking environment.
  59. if (!UC.Val_O_CREAT.hasValue()) {
  60. if (C.getASTContext().Target.getTriple().getVendor() == llvm::Triple::Apple)
  61. UC.Val_O_CREAT = 0x0200;
  62. else {
  63. // FIXME: We need a more general way of getting the O_CREAT value.
  64. // We could possibly grovel through the preprocessor state, but
  65. // that would require passing the Preprocessor object to the ExprEngine.
  66. return;
  67. }
  68. }
  69. LazyInitialize(BT, "Improper use of 'open'");
  70. // Look at the 'oflags' argument for the O_CREAT flag.
  71. const GRState *state = C.getState();
  72. if (CE->getNumArgs() < 2) {
  73. // The frontend should issue a warning for this case, so this is a sanity
  74. // check.
  75. return;
  76. }
  77. // Now check if oflags has O_CREAT set.
  78. const Expr *oflagsEx = CE->getArg(1);
  79. const SVal V = state->getSVal(oflagsEx);
  80. if (!isa<NonLoc>(V)) {
  81. // The case where 'V' can be a location can only be due to a bad header,
  82. // so in this case bail out.
  83. return;
  84. }
  85. NonLoc oflags = cast<NonLoc>(V);
  86. NonLoc ocreateFlag =
  87. cast<NonLoc>(C.getSValBuilder().makeIntVal(UC.Val_O_CREAT.getValue(),
  88. oflagsEx->getType()));
  89. SVal maskedFlagsUC = C.getSValBuilder().evalBinOpNN(state, BO_And,
  90. oflags, ocreateFlag,
  91. oflagsEx->getType());
  92. if (maskedFlagsUC.isUnknownOrUndef())
  93. return;
  94. DefinedSVal maskedFlags = cast<DefinedSVal>(maskedFlagsUC);
  95. // Check if maskedFlags is non-zero.
  96. const GRState *trueState, *falseState;
  97. llvm::tie(trueState, falseState) = state->assume(maskedFlags);
  98. // Only emit an error if the value of 'maskedFlags' is properly
  99. // constrained;
  100. if (!(trueState && !falseState))
  101. return;
  102. if (CE->getNumArgs() < 3) {
  103. ExplodedNode *N = C.generateSink(trueState);
  104. if (!N)
  105. return;
  106. EnhancedBugReport *report =
  107. new EnhancedBugReport(*BT,
  108. "Call to 'open' requires a third argument when "
  109. "the 'O_CREAT' flag is set", N);
  110. report->addRange(oflagsEx->getSourceRange());
  111. C.EmitReport(report);
  112. }
  113. }
  114. //===----------------------------------------------------------------------===//
  115. // pthread_once
  116. //===----------------------------------------------------------------------===//
  117. static void CheckPthreadOnce(CheckerContext &C, UnixAPIChecker &,
  118. const CallExpr *CE, BugType *&BT) {
  119. // This is similar to 'CheckDispatchOnce' in the MacOSXAPIChecker.
  120. // They can possibly be refactored.
  121. LazyInitialize(BT, "Improper use of 'pthread_once'");
  122. if (CE->getNumArgs() < 1)
  123. return;
  124. // Check if the first argument is stack allocated. If so, issue a warning
  125. // because that's likely to be bad news.
  126. const GRState *state = C.getState();
  127. const MemRegion *R = state->getSVal(CE->getArg(0)).getAsRegion();
  128. if (!R || !isa<StackSpaceRegion>(R->getMemorySpace()))
  129. return;
  130. ExplodedNode *N = C.generateSink(state);
  131. if (!N)
  132. return;
  133. llvm::SmallString<256> S;
  134. llvm::raw_svector_ostream os(S);
  135. os << "Call to 'pthread_once' uses";
  136. if (const VarRegion *VR = dyn_cast<VarRegion>(R))
  137. os << " the local variable '" << VR->getDecl()->getName() << '\'';
  138. else
  139. os << " stack allocated memory";
  140. os << " for the \"control\" value. Using such transient memory for "
  141. "the control value is potentially dangerous.";
  142. if (isa<VarRegion>(R) && isa<StackLocalsSpaceRegion>(R->getMemorySpace()))
  143. os << " Perhaps you intended to declare the variable as 'static'?";
  144. EnhancedBugReport *report = new EnhancedBugReport(*BT, os.str(), N);
  145. report->addRange(CE->getArg(0)->getSourceRange());
  146. C.EmitReport(report);
  147. }
  148. //===----------------------------------------------------------------------===//
  149. // "malloc" with allocation size 0
  150. //===----------------------------------------------------------------------===//
  151. // FIXME: Eventually this should be rolled into the MallocChecker, but this
  152. // check is more basic and is valuable for widespread use.
  153. static void CheckMallocZero(CheckerContext &C, UnixAPIChecker &UC,
  154. const CallExpr *CE, BugType *&BT) {
  155. // Sanity check that malloc takes one argument.
  156. if (CE->getNumArgs() != 1)
  157. return;
  158. // Check if the allocation size is 0.
  159. const GRState *state = C.getState();
  160. SVal argVal = state->getSVal(CE->getArg(0));
  161. if (argVal.isUnknownOrUndef())
  162. return;
  163. const GRState *trueState, *falseState;
  164. llvm::tie(trueState, falseState) = state->assume(cast<DefinedSVal>(argVal));
  165. // Is the value perfectly constrained to zero?
  166. if (falseState && !trueState) {
  167. ExplodedNode *N = C.generateSink(falseState);
  168. if (!N)
  169. return;
  170. // FIXME: Add reference to CERT advisory, and/or C99 standard in bug
  171. // output.
  172. LazyInitialize(BT, "Undefined allocation of 0 bytes");
  173. EnhancedBugReport *report =
  174. new EnhancedBugReport(*BT, "Call to 'malloc' has an allocation size"
  175. " of 0 bytes", N);
  176. report->addRange(CE->getArg(0)->getSourceRange());
  177. report->addVisitorCreator(bugreporter::registerTrackNullOrUndefValue,
  178. CE->getArg(0));
  179. C.EmitReport(report);
  180. return;
  181. }
  182. // Assume the the value is non-zero going forward.
  183. assert(trueState);
  184. if (trueState != state) {
  185. C.addTransition(trueState);
  186. }
  187. }
  188. //===----------------------------------------------------------------------===//
  189. // Central dispatch function.
  190. //===----------------------------------------------------------------------===//
  191. typedef void (*SubChecker)(CheckerContext &C, UnixAPIChecker &UC,
  192. const CallExpr *CE, BugType *&BT);
  193. namespace {
  194. class SubCheck {
  195. SubChecker SC;
  196. UnixAPIChecker *UC;
  197. BugType **BT;
  198. public:
  199. SubCheck(SubChecker sc, UnixAPIChecker *uc, BugType *& bt) : SC(sc), UC(uc),
  200. BT(&bt) {}
  201. SubCheck() : SC(NULL), UC(NULL), BT(NULL) {}
  202. void run(CheckerContext &C, const CallExpr *CE) const {
  203. if (SC)
  204. SC(C, *UC, CE, *BT);
  205. }
  206. };
  207. } // end anonymous namespace
  208. void UnixAPIChecker::PreVisitCallExpr(CheckerContext &C, const CallExpr *CE) {
  209. // Get the callee. All the functions we care about are C functions
  210. // with simple identifiers.
  211. const GRState *state = C.getState();
  212. const Expr *Callee = CE->getCallee();
  213. const FunctionTextRegion *Fn =
  214. dyn_cast_or_null<FunctionTextRegion>(state->getSVal(Callee).getAsRegion());
  215. if (!Fn)
  216. return;
  217. const IdentifierInfo *FI = Fn->getDecl()->getIdentifier();
  218. if (!FI)
  219. return;
  220. const SubCheck &SC =
  221. llvm::StringSwitch<SubCheck>(FI->getName())
  222. .Case("open",
  223. SubCheck(CheckOpen, this, BTypes[OpenFn]))
  224. .Case("pthread_once",
  225. SubCheck(CheckPthreadOnce, this, BTypes[PthreadOnceFn]))
  226. .Case("malloc",
  227. SubCheck(CheckMallocZero, this, BTypes[MallocZero]))
  228. .Default(SubCheck());
  229. SC.run(C, CE);
  230. }