UnixAPIChecker.cpp 13 KB

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