UnixAPIChecker.cpp 13 KB

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