UnixAPIChecker.cpp 13 KB

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