UnixAPIChecker.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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 "ClangSACheckers.h"
  15. #include "clang/StaticAnalyzer/Core/Checker.h"
  16. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  17. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  18. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  19. #include "clang/Basic/TargetInfo.h"
  20. #include "llvm/ADT/Optional.h"
  21. #include "llvm/ADT/STLExtras.h"
  22. #include "llvm/ADT/StringSwitch.h"
  23. #include <fcntl.h>
  24. using namespace clang;
  25. using namespace ento;
  26. using llvm::Optional;
  27. namespace {
  28. class UnixAPIChecker : public Checker< check::PreStmt<CallExpr> > {
  29. mutable llvm::OwningPtr<BugType> BT_open, BT_pthreadOnce, BT_mallocZero;
  30. mutable Optional<uint64_t> Val_O_CREAT;
  31. public:
  32. void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
  33. void CheckOpen(CheckerContext &C, const CallExpr *CE) const;
  34. void CheckPthreadOnce(CheckerContext &C, const CallExpr *CE) const;
  35. void CheckCallocZero(CheckerContext &C, const CallExpr *CE) const;
  36. void CheckMallocZero(CheckerContext &C, const CallExpr *CE) const;
  37. void CheckReallocZero(CheckerContext &C, const CallExpr *CE) const;
  38. void CheckAllocaZero(CheckerContext &C, const CallExpr *CE) const;
  39. void CheckVallocZero(CheckerContext &C, const CallExpr *CE) const;
  40. typedef void (UnixAPIChecker::*SubChecker)(CheckerContext &,
  41. const CallExpr *) const;
  42. private:
  43. bool ReportZeroByteAllocation(CheckerContext &C,
  44. ProgramStateRef falseState,
  45. const Expr *arg,
  46. const char *fn_name) const;
  47. void BasicAllocationCheck(CheckerContext &C,
  48. const CallExpr *CE,
  49. const unsigned numArgs,
  50. const unsigned sizeArg,
  51. const char *fn) const;
  52. };
  53. } //end anonymous namespace
  54. //===----------------------------------------------------------------------===//
  55. // Utility functions.
  56. //===----------------------------------------------------------------------===//
  57. static inline void LazyInitialize(llvm::OwningPtr<BugType> &BT,
  58. const char *name) {
  59. if (BT)
  60. return;
  61. BT.reset(new BugType(name, "Unix API"));
  62. }
  63. //===----------------------------------------------------------------------===//
  64. // "open" (man 2 open)
  65. //===----------------------------------------------------------------------===//
  66. void UnixAPIChecker::CheckOpen(CheckerContext &C, const CallExpr *CE) const {
  67. // The definition of O_CREAT is platform specific. We need a better way
  68. // of querying this information from the checking environment.
  69. if (!Val_O_CREAT.hasValue()) {
  70. if (C.getASTContext().getTargetInfo().getTriple().getVendor()
  71. == llvm::Triple::Apple)
  72. Val_O_CREAT = 0x0200;
  73. else {
  74. // FIXME: We need a more general way of getting the O_CREAT value.
  75. // We could possibly grovel through the preprocessor state, but
  76. // that would require passing the Preprocessor object to the ExprEngine.
  77. return;
  78. }
  79. }
  80. // Look at the 'oflags' argument for the O_CREAT flag.
  81. ProgramStateRef state = C.getState();
  82. if (CE->getNumArgs() < 2) {
  83. // The frontend should issue a warning for this case, so this is a sanity
  84. // check.
  85. return;
  86. }
  87. // Now check if oflags has O_CREAT set.
  88. const Expr *oflagsEx = CE->getArg(1);
  89. const SVal V = state->getSVal(oflagsEx, C.getLocationContext());
  90. if (!isa<NonLoc>(V)) {
  91. // The case where 'V' can be a location can only be due to a bad header,
  92. // so in this case bail out.
  93. return;
  94. }
  95. NonLoc oflags = cast<NonLoc>(V);
  96. NonLoc ocreateFlag =
  97. cast<NonLoc>(C.getSValBuilder().makeIntVal(Val_O_CREAT.getValue(),
  98. oflagsEx->getType()));
  99. SVal maskedFlagsUC = C.getSValBuilder().evalBinOpNN(state, BO_And,
  100. oflags, ocreateFlag,
  101. oflagsEx->getType());
  102. if (maskedFlagsUC.isUnknownOrUndef())
  103. return;
  104. DefinedSVal maskedFlags = cast<DefinedSVal>(maskedFlagsUC);
  105. // Check if maskedFlags is non-zero.
  106. ProgramStateRef trueState, falseState;
  107. llvm::tie(trueState, falseState) = state->assume(maskedFlags);
  108. // Only emit an error if the value of 'maskedFlags' is properly
  109. // constrained;
  110. if (!(trueState && !falseState))
  111. return;
  112. if (CE->getNumArgs() < 3) {
  113. ExplodedNode *N = C.generateSink(trueState);
  114. if (!N)
  115. return;
  116. LazyInitialize(BT_open, "Improper use of 'open'");
  117. BugReport *report =
  118. new BugReport(*BT_open,
  119. "Call to 'open' requires a third argument when "
  120. "the 'O_CREAT' flag is set", N);
  121. report->addRange(oflagsEx->getSourceRange());
  122. C.EmitReport(report);
  123. }
  124. }
  125. //===----------------------------------------------------------------------===//
  126. // pthread_once
  127. //===----------------------------------------------------------------------===//
  128. void UnixAPIChecker::CheckPthreadOnce(CheckerContext &C,
  129. const CallExpr *CE) const {
  130. // This is similar to 'CheckDispatchOnce' in the MacOSXAPIChecker.
  131. // They can possibly be refactored.
  132. if (CE->getNumArgs() < 1)
  133. return;
  134. // Check if the first argument is stack allocated. If so, issue a warning
  135. // because that's likely to be bad news.
  136. ProgramStateRef state = C.getState();
  137. const MemRegion *R =
  138. state->getSVal(CE->getArg(0), C.getLocationContext()).getAsRegion();
  139. if (!R || !isa<StackSpaceRegion>(R->getMemorySpace()))
  140. return;
  141. ExplodedNode *N = C.generateSink(state);
  142. if (!N)
  143. return;
  144. llvm::SmallString<256> S;
  145. llvm::raw_svector_ostream os(S);
  146. os << "Call to 'pthread_once' uses";
  147. if (const VarRegion *VR = dyn_cast<VarRegion>(R))
  148. os << " the local variable '" << VR->getDecl()->getName() << '\'';
  149. else
  150. os << " stack allocated memory";
  151. os << " for the \"control\" value. Using such transient memory for "
  152. "the control value is potentially dangerous.";
  153. if (isa<VarRegion>(R) && isa<StackLocalsSpaceRegion>(R->getMemorySpace()))
  154. os << " Perhaps you intended to declare the variable as 'static'?";
  155. LazyInitialize(BT_pthreadOnce, "Improper use of 'pthread_once'");
  156. BugReport *report = new BugReport(*BT_pthreadOnce, os.str(), N);
  157. report->addRange(CE->getArg(0)->getSourceRange());
  158. C.EmitReport(report);
  159. }
  160. //===----------------------------------------------------------------------===//
  161. // "calloc", "malloc", "realloc", "alloca" and "valloc" with allocation size 0
  162. //===----------------------------------------------------------------------===//
  163. // FIXME: Eventually these should be rolled into the MallocChecker, but right now
  164. // they're more basic and valuable for widespread use.
  165. // Returns true if we try to do a zero byte allocation, false otherwise.
  166. // Fills in trueState and falseState.
  167. static bool IsZeroByteAllocation(ProgramStateRef state,
  168. const SVal argVal,
  169. ProgramStateRef *trueState,
  170. ProgramStateRef *falseState) {
  171. llvm::tie(*trueState, *falseState) =
  172. state->assume(cast<DefinedSVal>(argVal));
  173. return (*falseState && !*trueState);
  174. }
  175. // Generates an error report, indicating that the function whose name is given
  176. // will perform a zero byte allocation.
  177. // Returns false if an error occured, true otherwise.
  178. bool UnixAPIChecker::ReportZeroByteAllocation(CheckerContext &C,
  179. ProgramStateRef falseState,
  180. const Expr *arg,
  181. const char *fn_name) const {
  182. ExplodedNode *N = C.generateSink(falseState);
  183. if (!N)
  184. return false;
  185. LazyInitialize(BT_mallocZero,
  186. "Undefined allocation of 0 bytes (CERT MEM04-C; CWE-131)");
  187. llvm::SmallString<256> S;
  188. llvm::raw_svector_ostream os(S);
  189. os << "Call to '" << fn_name << "' has an allocation size of 0 bytes";
  190. BugReport *report = new BugReport(*BT_mallocZero, os.str(), N);
  191. report->addRange(arg->getSourceRange());
  192. report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, arg));
  193. C.EmitReport(report);
  194. return true;
  195. }
  196. // Does a basic check for 0-sized allocations suitable for most of the below
  197. // functions (modulo "calloc")
  198. void UnixAPIChecker::BasicAllocationCheck(CheckerContext &C,
  199. const CallExpr *CE,
  200. const unsigned numArgs,
  201. const unsigned sizeArg,
  202. const char *fn) const {
  203. // Sanity check for the correct number of arguments
  204. if (CE->getNumArgs() != numArgs)
  205. return;
  206. // Check if the allocation size is 0.
  207. ProgramStateRef state = C.getState();
  208. ProgramStateRef trueState = NULL, falseState = NULL;
  209. const Expr *arg = CE->getArg(sizeArg);
  210. SVal argVal = state->getSVal(arg, C.getLocationContext());
  211. if (argVal.isUnknownOrUndef())
  212. return;
  213. // Is the value perfectly constrained to zero?
  214. if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
  215. (void) ReportZeroByteAllocation(C, falseState, arg, fn);
  216. return;
  217. }
  218. // Assume the the value is non-zero going forward.
  219. assert(trueState);
  220. if (trueState != state)
  221. C.addTransition(trueState);
  222. }
  223. void UnixAPIChecker::CheckCallocZero(CheckerContext &C,
  224. const CallExpr *CE) const {
  225. unsigned int nArgs = CE->getNumArgs();
  226. if (nArgs != 2)
  227. return;
  228. ProgramStateRef state = C.getState();
  229. ProgramStateRef trueState = NULL, falseState = NULL;
  230. unsigned int i;
  231. for (i = 0; i < nArgs; i++) {
  232. const Expr *arg = CE->getArg(i);
  233. SVal argVal = state->getSVal(arg, C.getLocationContext());
  234. if (argVal.isUnknownOrUndef()) {
  235. if (i == 0)
  236. continue;
  237. else
  238. return;
  239. }
  240. if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
  241. if (ReportZeroByteAllocation(C, falseState, arg, "calloc"))
  242. return;
  243. else if (i == 0)
  244. continue;
  245. else
  246. return;
  247. }
  248. }
  249. // Assume the the value is non-zero going forward.
  250. assert(trueState);
  251. if (trueState != state)
  252. C.addTransition(trueState);
  253. }
  254. void UnixAPIChecker::CheckMallocZero(CheckerContext &C,
  255. const CallExpr *CE) const {
  256. BasicAllocationCheck(C, CE, 1, 0, "malloc");
  257. }
  258. void UnixAPIChecker::CheckReallocZero(CheckerContext &C,
  259. const CallExpr *CE) const {
  260. BasicAllocationCheck(C, CE, 2, 1, "realloc");
  261. }
  262. void UnixAPIChecker::CheckAllocaZero(CheckerContext &C,
  263. const CallExpr *CE) const {
  264. BasicAllocationCheck(C, CE, 1, 0, "alloca");
  265. }
  266. void UnixAPIChecker::CheckVallocZero(CheckerContext &C,
  267. const CallExpr *CE) const {
  268. BasicAllocationCheck(C, CE, 1, 0, "valloc");
  269. }
  270. //===----------------------------------------------------------------------===//
  271. // Central dispatch function.
  272. //===----------------------------------------------------------------------===//
  273. void UnixAPIChecker::checkPreStmt(const CallExpr *CE,
  274. CheckerContext &C) const {
  275. StringRef FName = C.getCalleeName(CE);
  276. if (FName.empty())
  277. return;
  278. SubChecker SC =
  279. llvm::StringSwitch<SubChecker>(FName)
  280. .Case("open", &UnixAPIChecker::CheckOpen)
  281. .Case("pthread_once", &UnixAPIChecker::CheckPthreadOnce)
  282. .Case("calloc", &UnixAPIChecker::CheckCallocZero)
  283. .Case("malloc", &UnixAPIChecker::CheckMallocZero)
  284. .Case("realloc", &UnixAPIChecker::CheckReallocZero)
  285. .Cases("alloca", "__builtin_alloca", &UnixAPIChecker::CheckAllocaZero)
  286. .Case("valloc", &UnixAPIChecker::CheckVallocZero)
  287. .Default(NULL);
  288. if (SC)
  289. (this->*SC)(C, CE);
  290. }
  291. //===----------------------------------------------------------------------===//
  292. // Registration.
  293. //===----------------------------------------------------------------------===//
  294. void ento::registerUnixAPIChecker(CheckerManager &mgr) {
  295. mgr.registerChecker<UnixAPIChecker>();
  296. }