UnixAPIChecker.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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/StringExtras.h"
  24. #include "llvm/ADT/StringSwitch.h"
  25. #include "llvm/Support/raw_ostream.h"
  26. #include <fcntl.h>
  27. using namespace clang;
  28. using namespace ento;
  29. enum class OpenVariant {
  30. /// The standard open() call:
  31. /// int open(const char *path, int oflag, ...);
  32. Open,
  33. /// The variant taking a directory file descriptor and a relative path:
  34. /// int openat(int fd, const char *path, int oflag, ...);
  35. OpenAt
  36. };
  37. namespace {
  38. class UnixAPIChecker : public Checker< check::PreStmt<CallExpr> > {
  39. mutable std::unique_ptr<BugType> BT_open, BT_pthreadOnce, BT_mallocZero;
  40. mutable Optional<uint64_t> Val_O_CREAT;
  41. public:
  42. DefaultBool CheckMisuse, CheckPortability;
  43. void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
  44. void CheckOpen(CheckerContext &C, const CallExpr *CE) const;
  45. void CheckOpenAt(CheckerContext &C, const CallExpr *CE) const;
  46. void CheckPthreadOnce(CheckerContext &C, const CallExpr *CE) const;
  47. void CheckCallocZero(CheckerContext &C, const CallExpr *CE) const;
  48. void CheckMallocZero(CheckerContext &C, const CallExpr *CE) const;
  49. void CheckReallocZero(CheckerContext &C, const CallExpr *CE) const;
  50. void CheckReallocfZero(CheckerContext &C, const CallExpr *CE) const;
  51. void CheckAllocaZero(CheckerContext &C, const CallExpr *CE) const;
  52. void CheckAllocaWithAlignZero(CheckerContext &C, const CallExpr *CE) const;
  53. void CheckVallocZero(CheckerContext &C, const CallExpr *CE) const;
  54. typedef void (UnixAPIChecker::*SubChecker)(CheckerContext &,
  55. const CallExpr *) const;
  56. private:
  57. void CheckOpenVariant(CheckerContext &C,
  58. const CallExpr *CE, OpenVariant Variant) const;
  59. bool ReportZeroByteAllocation(CheckerContext &C,
  60. ProgramStateRef falseState,
  61. const Expr *arg,
  62. const char *fn_name) const;
  63. void BasicAllocationCheck(CheckerContext &C,
  64. const CallExpr *CE,
  65. const unsigned numArgs,
  66. const unsigned sizeArg,
  67. const char *fn) const;
  68. void LazyInitialize(std::unique_ptr<BugType> &BT, const char *name) const {
  69. if (BT)
  70. return;
  71. BT.reset(new BugType(this, name, categories::UnixAPI));
  72. }
  73. void ReportOpenBug(CheckerContext &C,
  74. ProgramStateRef State,
  75. const char *Msg,
  76. SourceRange SR) const;
  77. };
  78. } //end anonymous namespace
  79. //===----------------------------------------------------------------------===//
  80. // "open" (man 2 open)
  81. //===----------------------------------------------------------------------===//
  82. void UnixAPIChecker::ReportOpenBug(CheckerContext &C,
  83. ProgramStateRef State,
  84. const char *Msg,
  85. SourceRange SR) const {
  86. ExplodedNode *N = C.generateErrorNode(State);
  87. if (!N)
  88. return;
  89. LazyInitialize(BT_open, "Improper use of 'open'");
  90. auto Report = llvm::make_unique<BugReport>(*BT_open, Msg, N);
  91. Report->addRange(SR);
  92. C.emitReport(std::move(Report));
  93. }
  94. void UnixAPIChecker::CheckOpen(CheckerContext &C, const CallExpr *CE) const {
  95. CheckOpenVariant(C, CE, OpenVariant::Open);
  96. }
  97. void UnixAPIChecker::CheckOpenAt(CheckerContext &C, const CallExpr *CE) const {
  98. CheckOpenVariant(C, CE, OpenVariant::OpenAt);
  99. }
  100. void UnixAPIChecker::CheckOpenVariant(CheckerContext &C,
  101. const CallExpr *CE,
  102. OpenVariant Variant) const {
  103. // The index of the argument taking the flags open flags (O_RDONLY,
  104. // O_WRONLY, O_CREAT, etc.),
  105. unsigned int FlagsArgIndex;
  106. const char *VariantName;
  107. switch (Variant) {
  108. case OpenVariant::Open:
  109. FlagsArgIndex = 1;
  110. VariantName = "open";
  111. break;
  112. case OpenVariant::OpenAt:
  113. FlagsArgIndex = 2;
  114. VariantName = "openat";
  115. break;
  116. };
  117. // All calls should at least provide arguments up to the 'flags' parameter.
  118. unsigned int MinArgCount = FlagsArgIndex + 1;
  119. // If the flags has O_CREAT set then open/openat() require an additional
  120. // argument specifying the file mode (permission bits) for the created file.
  121. unsigned int CreateModeArgIndex = FlagsArgIndex + 1;
  122. // The create mode argument should be the last argument.
  123. unsigned int MaxArgCount = CreateModeArgIndex + 1;
  124. ProgramStateRef state = C.getState();
  125. if (CE->getNumArgs() < MinArgCount) {
  126. // The frontend should issue a warning for this case, so this is a sanity
  127. // check.
  128. return;
  129. } else if (CE->getNumArgs() == MaxArgCount) {
  130. const Expr *Arg = CE->getArg(CreateModeArgIndex);
  131. QualType QT = Arg->getType();
  132. if (!QT->isIntegerType()) {
  133. SmallString<256> SBuf;
  134. llvm::raw_svector_ostream OS(SBuf);
  135. OS << "The " << CreateModeArgIndex + 1
  136. << llvm::getOrdinalSuffix(CreateModeArgIndex + 1)
  137. << " argument to '" << VariantName << "' is not an integer";
  138. ReportOpenBug(C, state,
  139. SBuf.c_str(),
  140. Arg->getSourceRange());
  141. return;
  142. }
  143. } else if (CE->getNumArgs() > MaxArgCount) {
  144. SmallString<256> SBuf;
  145. llvm::raw_svector_ostream OS(SBuf);
  146. OS << "Call to '" << VariantName << "' with more than " << MaxArgCount
  147. << " arguments";
  148. ReportOpenBug(C, state,
  149. SBuf.c_str(),
  150. CE->getArg(MaxArgCount)->getSourceRange());
  151. return;
  152. }
  153. // The definition of O_CREAT is platform specific. We need a better way
  154. // of querying this information from the checking environment.
  155. if (!Val_O_CREAT.hasValue()) {
  156. if (C.getASTContext().getTargetInfo().getTriple().getVendor()
  157. == llvm::Triple::Apple)
  158. Val_O_CREAT = 0x0200;
  159. else {
  160. // FIXME: We need a more general way of getting the O_CREAT value.
  161. // We could possibly grovel through the preprocessor state, but
  162. // that would require passing the Preprocessor object to the ExprEngine.
  163. // See also: MallocChecker.cpp / M_ZERO.
  164. return;
  165. }
  166. }
  167. // Now check if oflags has O_CREAT set.
  168. const Expr *oflagsEx = CE->getArg(FlagsArgIndex);
  169. const SVal V = C.getSVal(oflagsEx);
  170. if (!V.getAs<NonLoc>()) {
  171. // The case where 'V' can be a location can only be due to a bad header,
  172. // so in this case bail out.
  173. return;
  174. }
  175. NonLoc oflags = V.castAs<NonLoc>();
  176. NonLoc ocreateFlag = C.getSValBuilder()
  177. .makeIntVal(Val_O_CREAT.getValue(), oflagsEx->getType()).castAs<NonLoc>();
  178. SVal maskedFlagsUC = C.getSValBuilder().evalBinOpNN(state, BO_And,
  179. oflags, ocreateFlag,
  180. oflagsEx->getType());
  181. if (maskedFlagsUC.isUnknownOrUndef())
  182. return;
  183. DefinedSVal maskedFlags = maskedFlagsUC.castAs<DefinedSVal>();
  184. // Check if maskedFlags is non-zero.
  185. ProgramStateRef trueState, falseState;
  186. std::tie(trueState, falseState) = state->assume(maskedFlags);
  187. // Only emit an error if the value of 'maskedFlags' is properly
  188. // constrained;
  189. if (!(trueState && !falseState))
  190. return;
  191. if (CE->getNumArgs() < MaxArgCount) {
  192. SmallString<256> SBuf;
  193. llvm::raw_svector_ostream OS(SBuf);
  194. OS << "Call to '" << VariantName << "' requires a "
  195. << CreateModeArgIndex + 1
  196. << llvm::getOrdinalSuffix(CreateModeArgIndex + 1)
  197. << " argument when the 'O_CREAT' flag is set";
  198. ReportOpenBug(C, trueState,
  199. SBuf.c_str(),
  200. oflagsEx->getSourceRange());
  201. }
  202. }
  203. //===----------------------------------------------------------------------===//
  204. // pthread_once
  205. //===----------------------------------------------------------------------===//
  206. void UnixAPIChecker::CheckPthreadOnce(CheckerContext &C,
  207. const CallExpr *CE) const {
  208. // This is similar to 'CheckDispatchOnce' in the MacOSXAPIChecker.
  209. // They can possibly be refactored.
  210. if (CE->getNumArgs() < 1)
  211. return;
  212. // Check if the first argument is stack allocated. If so, issue a warning
  213. // because that's likely to be bad news.
  214. ProgramStateRef state = C.getState();
  215. const MemRegion *R = C.getSVal(CE->getArg(0)).getAsRegion();
  216. if (!R || !isa<StackSpaceRegion>(R->getMemorySpace()))
  217. return;
  218. ExplodedNode *N = C.generateErrorNode(state);
  219. if (!N)
  220. return;
  221. SmallString<256> S;
  222. llvm::raw_svector_ostream os(S);
  223. os << "Call to 'pthread_once' uses";
  224. if (const VarRegion *VR = dyn_cast<VarRegion>(R))
  225. os << " the local variable '" << VR->getDecl()->getName() << '\'';
  226. else
  227. os << " stack allocated memory";
  228. os << " for the \"control\" value. Using such transient memory for "
  229. "the control value is potentially dangerous.";
  230. if (isa<VarRegion>(R) && isa<StackLocalsSpaceRegion>(R->getMemorySpace()))
  231. os << " Perhaps you intended to declare the variable as 'static'?";
  232. LazyInitialize(BT_pthreadOnce, "Improper use of 'pthread_once'");
  233. auto report = llvm::make_unique<BugReport>(*BT_pthreadOnce, os.str(), N);
  234. report->addRange(CE->getArg(0)->getSourceRange());
  235. C.emitReport(std::move(report));
  236. }
  237. //===----------------------------------------------------------------------===//
  238. // "calloc", "malloc", "realloc", "reallocf", "alloca" and "valloc"
  239. // with allocation size 0
  240. //===----------------------------------------------------------------------===//
  241. // FIXME: Eventually these should be rolled into the MallocChecker, but right now
  242. // they're more basic and valuable for widespread use.
  243. // Returns true if we try to do a zero byte allocation, false otherwise.
  244. // Fills in trueState and falseState.
  245. static bool IsZeroByteAllocation(ProgramStateRef state,
  246. const SVal argVal,
  247. ProgramStateRef *trueState,
  248. ProgramStateRef *falseState) {
  249. std::tie(*trueState, *falseState) =
  250. state->assume(argVal.castAs<DefinedSVal>());
  251. return (*falseState && !*trueState);
  252. }
  253. // Generates an error report, indicating that the function whose name is given
  254. // will perform a zero byte allocation.
  255. // Returns false if an error occurred, true otherwise.
  256. bool UnixAPIChecker::ReportZeroByteAllocation(CheckerContext &C,
  257. ProgramStateRef falseState,
  258. const Expr *arg,
  259. const char *fn_name) const {
  260. ExplodedNode *N = C.generateErrorNode(falseState);
  261. if (!N)
  262. return false;
  263. LazyInitialize(BT_mallocZero,
  264. "Undefined allocation of 0 bytes (CERT MEM04-C; CWE-131)");
  265. SmallString<256> S;
  266. llvm::raw_svector_ostream os(S);
  267. os << "Call to '" << fn_name << "' has an allocation size of 0 bytes";
  268. auto report = llvm::make_unique<BugReport>(*BT_mallocZero, os.str(), N);
  269. report->addRange(arg->getSourceRange());
  270. bugreporter::trackNullOrUndefValue(N, arg, *report);
  271. C.emitReport(std::move(report));
  272. return true;
  273. }
  274. // Does a basic check for 0-sized allocations suitable for most of the below
  275. // functions (modulo "calloc")
  276. void UnixAPIChecker::BasicAllocationCheck(CheckerContext &C,
  277. const CallExpr *CE,
  278. const unsigned numArgs,
  279. const unsigned sizeArg,
  280. const char *fn) const {
  281. // Sanity check for the correct number of arguments
  282. if (CE->getNumArgs() != numArgs)
  283. return;
  284. // Check if the allocation size is 0.
  285. ProgramStateRef state = C.getState();
  286. ProgramStateRef trueState = nullptr, falseState = nullptr;
  287. const Expr *arg = CE->getArg(sizeArg);
  288. SVal argVal = C.getSVal(arg);
  289. if (argVal.isUnknownOrUndef())
  290. return;
  291. // Is the value perfectly constrained to zero?
  292. if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
  293. (void) ReportZeroByteAllocation(C, falseState, arg, fn);
  294. return;
  295. }
  296. // Assume the value is non-zero going forward.
  297. assert(trueState);
  298. if (trueState != state)
  299. C.addTransition(trueState);
  300. }
  301. void UnixAPIChecker::CheckCallocZero(CheckerContext &C,
  302. const CallExpr *CE) const {
  303. unsigned int nArgs = CE->getNumArgs();
  304. if (nArgs != 2)
  305. return;
  306. ProgramStateRef state = C.getState();
  307. ProgramStateRef trueState = nullptr, falseState = nullptr;
  308. unsigned int i;
  309. for (i = 0; i < nArgs; i++) {
  310. const Expr *arg = CE->getArg(i);
  311. SVal argVal = C.getSVal(arg);
  312. if (argVal.isUnknownOrUndef()) {
  313. if (i == 0)
  314. continue;
  315. else
  316. return;
  317. }
  318. if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
  319. if (ReportZeroByteAllocation(C, falseState, arg, "calloc"))
  320. return;
  321. else if (i == 0)
  322. continue;
  323. else
  324. return;
  325. }
  326. }
  327. // Assume the value is non-zero going forward.
  328. assert(trueState);
  329. if (trueState != state)
  330. C.addTransition(trueState);
  331. }
  332. void UnixAPIChecker::CheckMallocZero(CheckerContext &C,
  333. const CallExpr *CE) const {
  334. BasicAllocationCheck(C, CE, 1, 0, "malloc");
  335. }
  336. void UnixAPIChecker::CheckReallocZero(CheckerContext &C,
  337. const CallExpr *CE) const {
  338. BasicAllocationCheck(C, CE, 2, 1, "realloc");
  339. }
  340. void UnixAPIChecker::CheckReallocfZero(CheckerContext &C,
  341. const CallExpr *CE) const {
  342. BasicAllocationCheck(C, CE, 2, 1, "reallocf");
  343. }
  344. void UnixAPIChecker::CheckAllocaZero(CheckerContext &C,
  345. const CallExpr *CE) const {
  346. BasicAllocationCheck(C, CE, 1, 0, "alloca");
  347. }
  348. void UnixAPIChecker::CheckAllocaWithAlignZero(CheckerContext &C,
  349. const CallExpr *CE) const {
  350. BasicAllocationCheck(C, CE, 2, 0, "__builtin_alloca_with_align");
  351. }
  352. void UnixAPIChecker::CheckVallocZero(CheckerContext &C,
  353. const CallExpr *CE) const {
  354. BasicAllocationCheck(C, CE, 1, 0, "valloc");
  355. }
  356. //===----------------------------------------------------------------------===//
  357. // Central dispatch function.
  358. //===----------------------------------------------------------------------===//
  359. void UnixAPIChecker::checkPreStmt(const CallExpr *CE,
  360. CheckerContext &C) const {
  361. const FunctionDecl *FD = C.getCalleeDecl(CE);
  362. if (!FD || FD->getKind() != Decl::Function)
  363. return;
  364. // Don't treat functions in namespaces with the same name a Unix function
  365. // as a call to the Unix function.
  366. const DeclContext *NamespaceCtx = FD->getEnclosingNamespaceContext();
  367. if (NamespaceCtx && isa<NamespaceDecl>(NamespaceCtx))
  368. return;
  369. StringRef FName = C.getCalleeName(FD);
  370. if (FName.empty())
  371. return;
  372. if (CheckMisuse) {
  373. if (SubChecker SC =
  374. llvm::StringSwitch<SubChecker>(FName)
  375. .Case("open", &UnixAPIChecker::CheckOpen)
  376. .Case("openat", &UnixAPIChecker::CheckOpenAt)
  377. .Case("pthread_once", &UnixAPIChecker::CheckPthreadOnce)
  378. .Default(nullptr)) {
  379. (this->*SC)(C, CE);
  380. }
  381. }
  382. if (CheckPortability) {
  383. if (SubChecker SC =
  384. llvm::StringSwitch<SubChecker>(FName)
  385. .Case("calloc", &UnixAPIChecker::CheckCallocZero)
  386. .Case("malloc", &UnixAPIChecker::CheckMallocZero)
  387. .Case("realloc", &UnixAPIChecker::CheckReallocZero)
  388. .Case("reallocf", &UnixAPIChecker::CheckReallocfZero)
  389. .Cases("alloca", "__builtin_alloca",
  390. &UnixAPIChecker::CheckAllocaZero)
  391. .Case("__builtin_alloca_with_align",
  392. &UnixAPIChecker::CheckAllocaWithAlignZero)
  393. .Case("valloc", &UnixAPIChecker::CheckVallocZero)
  394. .Default(nullptr)) {
  395. (this->*SC)(C, CE);
  396. }
  397. }
  398. }
  399. //===----------------------------------------------------------------------===//
  400. // Registration.
  401. //===----------------------------------------------------------------------===//
  402. #define REGISTER_CHECKER(Name) \
  403. void ento::registerUnixAPI##Name##Checker(CheckerManager &mgr) { \
  404. mgr.registerChecker<UnixAPIChecker>()->Check##Name = true; \
  405. }
  406. REGISTER_CHECKER(Misuse)
  407. REGISTER_CHECKER(Portability)