StreamChecker.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. //===-- StreamChecker.cpp -----------------------------------------*- 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 file defines checkers that model and check stream handling functions.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "ClangSACheckers.h"
  14. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.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/PathSensitive/ProgramState.h"
  19. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
  20. #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
  21. #include "llvm/ADT/ImmutableMap.h"
  22. using namespace clang;
  23. using namespace ento;
  24. namespace {
  25. struct StreamState {
  26. enum Kind { Opened, Closed, OpenFailed, Escaped } K;
  27. const Stmt *S;
  28. StreamState(Kind k, const Stmt *s) : K(k), S(s) {}
  29. bool isOpened() const { return K == Opened; }
  30. bool isClosed() const { return K == Closed; }
  31. //bool isOpenFailed() const { return K == OpenFailed; }
  32. //bool isEscaped() const { return K == Escaped; }
  33. bool operator==(const StreamState &X) const {
  34. return K == X.K && S == X.S;
  35. }
  36. static StreamState getOpened(const Stmt *s) { return StreamState(Opened, s); }
  37. static StreamState getClosed(const Stmt *s) { return StreamState(Closed, s); }
  38. static StreamState getOpenFailed(const Stmt *s) {
  39. return StreamState(OpenFailed, s);
  40. }
  41. static StreamState getEscaped(const Stmt *s) {
  42. return StreamState(Escaped, s);
  43. }
  44. void Profile(llvm::FoldingSetNodeID &ID) const {
  45. ID.AddInteger(K);
  46. ID.AddPointer(S);
  47. }
  48. };
  49. class StreamChecker : public Checker<eval::Call,
  50. check::DeadSymbols > {
  51. mutable IdentifierInfo *II_fopen, *II_tmpfile, *II_fclose, *II_fread,
  52. *II_fwrite,
  53. *II_fseek, *II_ftell, *II_rewind, *II_fgetpos, *II_fsetpos,
  54. *II_clearerr, *II_feof, *II_ferror, *II_fileno;
  55. mutable std::unique_ptr<BuiltinBug> BT_nullfp, BT_illegalwhence,
  56. BT_doubleclose, BT_ResourceLeak;
  57. public:
  58. StreamChecker()
  59. : II_fopen(nullptr), II_tmpfile(nullptr), II_fclose(nullptr),
  60. II_fread(nullptr), II_fwrite(nullptr), II_fseek(nullptr),
  61. II_ftell(nullptr), II_rewind(nullptr), II_fgetpos(nullptr),
  62. II_fsetpos(nullptr), II_clearerr(nullptr), II_feof(nullptr),
  63. II_ferror(nullptr), II_fileno(nullptr) {}
  64. bool evalCall(const CallExpr *CE, CheckerContext &C) const;
  65. void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
  66. private:
  67. void Fopen(CheckerContext &C, const CallExpr *CE) const;
  68. void Tmpfile(CheckerContext &C, const CallExpr *CE) const;
  69. void Fclose(CheckerContext &C, const CallExpr *CE) const;
  70. void Fread(CheckerContext &C, const CallExpr *CE) const;
  71. void Fwrite(CheckerContext &C, const CallExpr *CE) const;
  72. void Fseek(CheckerContext &C, const CallExpr *CE) const;
  73. void Ftell(CheckerContext &C, const CallExpr *CE) const;
  74. void Rewind(CheckerContext &C, const CallExpr *CE) const;
  75. void Fgetpos(CheckerContext &C, const CallExpr *CE) const;
  76. void Fsetpos(CheckerContext &C, const CallExpr *CE) const;
  77. void Clearerr(CheckerContext &C, const CallExpr *CE) const;
  78. void Feof(CheckerContext &C, const CallExpr *CE) const;
  79. void Ferror(CheckerContext &C, const CallExpr *CE) const;
  80. void Fileno(CheckerContext &C, const CallExpr *CE) const;
  81. void OpenFileAux(CheckerContext &C, const CallExpr *CE) const;
  82. ProgramStateRef CheckNullStream(SVal SV, ProgramStateRef state,
  83. CheckerContext &C) const;
  84. ProgramStateRef CheckDoubleClose(const CallExpr *CE, ProgramStateRef state,
  85. CheckerContext &C) const;
  86. };
  87. } // end anonymous namespace
  88. REGISTER_MAP_WITH_PROGRAMSTATE(StreamMap, SymbolRef, StreamState)
  89. bool StreamChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
  90. const FunctionDecl *FD = C.getCalleeDecl(CE);
  91. if (!FD || FD->getKind() != Decl::Function)
  92. return false;
  93. ASTContext &Ctx = C.getASTContext();
  94. if (!II_fopen)
  95. II_fopen = &Ctx.Idents.get("fopen");
  96. if (!II_tmpfile)
  97. II_tmpfile = &Ctx.Idents.get("tmpfile");
  98. if (!II_fclose)
  99. II_fclose = &Ctx.Idents.get("fclose");
  100. if (!II_fread)
  101. II_fread = &Ctx.Idents.get("fread");
  102. if (!II_fwrite)
  103. II_fwrite = &Ctx.Idents.get("fwrite");
  104. if (!II_fseek)
  105. II_fseek = &Ctx.Idents.get("fseek");
  106. if (!II_ftell)
  107. II_ftell = &Ctx.Idents.get("ftell");
  108. if (!II_rewind)
  109. II_rewind = &Ctx.Idents.get("rewind");
  110. if (!II_fgetpos)
  111. II_fgetpos = &Ctx.Idents.get("fgetpos");
  112. if (!II_fsetpos)
  113. II_fsetpos = &Ctx.Idents.get("fsetpos");
  114. if (!II_clearerr)
  115. II_clearerr = &Ctx.Idents.get("clearerr");
  116. if (!II_feof)
  117. II_feof = &Ctx.Idents.get("feof");
  118. if (!II_ferror)
  119. II_ferror = &Ctx.Idents.get("ferror");
  120. if (!II_fileno)
  121. II_fileno = &Ctx.Idents.get("fileno");
  122. if (FD->getIdentifier() == II_fopen) {
  123. Fopen(C, CE);
  124. return true;
  125. }
  126. if (FD->getIdentifier() == II_tmpfile) {
  127. Tmpfile(C, CE);
  128. return true;
  129. }
  130. if (FD->getIdentifier() == II_fclose) {
  131. Fclose(C, CE);
  132. return true;
  133. }
  134. if (FD->getIdentifier() == II_fread) {
  135. Fread(C, CE);
  136. return true;
  137. }
  138. if (FD->getIdentifier() == II_fwrite) {
  139. Fwrite(C, CE);
  140. return true;
  141. }
  142. if (FD->getIdentifier() == II_fseek) {
  143. Fseek(C, CE);
  144. return true;
  145. }
  146. if (FD->getIdentifier() == II_ftell) {
  147. Ftell(C, CE);
  148. return true;
  149. }
  150. if (FD->getIdentifier() == II_rewind) {
  151. Rewind(C, CE);
  152. return true;
  153. }
  154. if (FD->getIdentifier() == II_fgetpos) {
  155. Fgetpos(C, CE);
  156. return true;
  157. }
  158. if (FD->getIdentifier() == II_fsetpos) {
  159. Fsetpos(C, CE);
  160. return true;
  161. }
  162. if (FD->getIdentifier() == II_clearerr) {
  163. Clearerr(C, CE);
  164. return true;
  165. }
  166. if (FD->getIdentifier() == II_feof) {
  167. Feof(C, CE);
  168. return true;
  169. }
  170. if (FD->getIdentifier() == II_ferror) {
  171. Ferror(C, CE);
  172. return true;
  173. }
  174. if (FD->getIdentifier() == II_fileno) {
  175. Fileno(C, CE);
  176. return true;
  177. }
  178. return false;
  179. }
  180. void StreamChecker::Fopen(CheckerContext &C, const CallExpr *CE) const {
  181. OpenFileAux(C, CE);
  182. }
  183. void StreamChecker::Tmpfile(CheckerContext &C, const CallExpr *CE) const {
  184. OpenFileAux(C, CE);
  185. }
  186. void StreamChecker::OpenFileAux(CheckerContext &C, const CallExpr *CE) const {
  187. ProgramStateRef state = C.getState();
  188. SValBuilder &svalBuilder = C.getSValBuilder();
  189. const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
  190. DefinedSVal RetVal = svalBuilder.conjureSymbolVal(nullptr, CE, LCtx,
  191. C.blockCount())
  192. .castAs<DefinedSVal>();
  193. state = state->BindExpr(CE, C.getLocationContext(), RetVal);
  194. ConstraintManager &CM = C.getConstraintManager();
  195. // Bifurcate the state into two: one with a valid FILE* pointer, the other
  196. // with a NULL.
  197. ProgramStateRef stateNotNull, stateNull;
  198. std::tie(stateNotNull, stateNull) = CM.assumeDual(state, RetVal);
  199. if (SymbolRef Sym = RetVal.getAsSymbol()) {
  200. // if RetVal is not NULL, set the symbol's state to Opened.
  201. stateNotNull =
  202. stateNotNull->set<StreamMap>(Sym,StreamState::getOpened(CE));
  203. stateNull =
  204. stateNull->set<StreamMap>(Sym, StreamState::getOpenFailed(CE));
  205. C.addTransition(stateNotNull);
  206. C.addTransition(stateNull);
  207. }
  208. }
  209. void StreamChecker::Fclose(CheckerContext &C, const CallExpr *CE) const {
  210. ProgramStateRef state = CheckDoubleClose(CE, C.getState(), C);
  211. if (state)
  212. C.addTransition(state);
  213. }
  214. void StreamChecker::Fread(CheckerContext &C, const CallExpr *CE) const {
  215. ProgramStateRef state = C.getState();
  216. if (!CheckNullStream(state->getSVal(CE->getArg(3), C.getLocationContext()),
  217. state, C))
  218. return;
  219. }
  220. void StreamChecker::Fwrite(CheckerContext &C, const CallExpr *CE) const {
  221. ProgramStateRef state = C.getState();
  222. if (!CheckNullStream(state->getSVal(CE->getArg(3), C.getLocationContext()),
  223. state, C))
  224. return;
  225. }
  226. void StreamChecker::Fseek(CheckerContext &C, const CallExpr *CE) const {
  227. ProgramStateRef state = C.getState();
  228. if (!(state = CheckNullStream(state->getSVal(CE->getArg(0),
  229. C.getLocationContext()), state, C)))
  230. return;
  231. // Check the legality of the 'whence' argument of 'fseek'.
  232. SVal Whence = state->getSVal(CE->getArg(2), C.getLocationContext());
  233. Optional<nonloc::ConcreteInt> CI = Whence.getAs<nonloc::ConcreteInt>();
  234. if (!CI)
  235. return;
  236. int64_t x = CI->getValue().getSExtValue();
  237. if (x >= 0 && x <= 2)
  238. return;
  239. if (ExplodedNode *N = C.addTransition(state)) {
  240. if (!BT_illegalwhence)
  241. BT_illegalwhence.reset(
  242. new BuiltinBug(this, "Illegal whence argument",
  243. "The whence argument to fseek() should be "
  244. "SEEK_SET, SEEK_END, or SEEK_CUR."));
  245. C.emitReport(llvm::make_unique<BugReport>(
  246. *BT_illegalwhence, BT_illegalwhence->getDescription(), N));
  247. }
  248. }
  249. void StreamChecker::Ftell(CheckerContext &C, const CallExpr *CE) const {
  250. ProgramStateRef state = C.getState();
  251. if (!CheckNullStream(state->getSVal(CE->getArg(0), C.getLocationContext()),
  252. state, C))
  253. return;
  254. }
  255. void StreamChecker::Rewind(CheckerContext &C, const CallExpr *CE) const {
  256. ProgramStateRef state = C.getState();
  257. if (!CheckNullStream(state->getSVal(CE->getArg(0), C.getLocationContext()),
  258. state, C))
  259. return;
  260. }
  261. void StreamChecker::Fgetpos(CheckerContext &C, const CallExpr *CE) const {
  262. ProgramStateRef state = C.getState();
  263. if (!CheckNullStream(state->getSVal(CE->getArg(0), C.getLocationContext()),
  264. state, C))
  265. return;
  266. }
  267. void StreamChecker::Fsetpos(CheckerContext &C, const CallExpr *CE) const {
  268. ProgramStateRef state = C.getState();
  269. if (!CheckNullStream(state->getSVal(CE->getArg(0), C.getLocationContext()),
  270. state, C))
  271. return;
  272. }
  273. void StreamChecker::Clearerr(CheckerContext &C, const CallExpr *CE) const {
  274. ProgramStateRef state = C.getState();
  275. if (!CheckNullStream(state->getSVal(CE->getArg(0), C.getLocationContext()),
  276. state, C))
  277. return;
  278. }
  279. void StreamChecker::Feof(CheckerContext &C, const CallExpr *CE) const {
  280. ProgramStateRef state = C.getState();
  281. if (!CheckNullStream(state->getSVal(CE->getArg(0), C.getLocationContext()),
  282. state, C))
  283. return;
  284. }
  285. void StreamChecker::Ferror(CheckerContext &C, const CallExpr *CE) const {
  286. ProgramStateRef state = C.getState();
  287. if (!CheckNullStream(state->getSVal(CE->getArg(0), C.getLocationContext()),
  288. state, C))
  289. return;
  290. }
  291. void StreamChecker::Fileno(CheckerContext &C, const CallExpr *CE) const {
  292. ProgramStateRef state = C.getState();
  293. if (!CheckNullStream(state->getSVal(CE->getArg(0), C.getLocationContext()),
  294. state, C))
  295. return;
  296. }
  297. ProgramStateRef StreamChecker::CheckNullStream(SVal SV, ProgramStateRef state,
  298. CheckerContext &C) const {
  299. Optional<DefinedSVal> DV = SV.getAs<DefinedSVal>();
  300. if (!DV)
  301. return nullptr;
  302. ConstraintManager &CM = C.getConstraintManager();
  303. ProgramStateRef stateNotNull, stateNull;
  304. std::tie(stateNotNull, stateNull) = CM.assumeDual(state, *DV);
  305. if (!stateNotNull && stateNull) {
  306. if (ExplodedNode *N = C.generateSink(stateNull)) {
  307. if (!BT_nullfp)
  308. BT_nullfp.reset(new BuiltinBug(this, "NULL stream pointer",
  309. "Stream pointer might be NULL."));
  310. C.emitReport(llvm::make_unique<BugReport>(
  311. *BT_nullfp, BT_nullfp->getDescription(), N));
  312. }
  313. return nullptr;
  314. }
  315. return stateNotNull;
  316. }
  317. ProgramStateRef StreamChecker::CheckDoubleClose(const CallExpr *CE,
  318. ProgramStateRef state,
  319. CheckerContext &C) const {
  320. SymbolRef Sym =
  321. state->getSVal(CE->getArg(0), C.getLocationContext()).getAsSymbol();
  322. if (!Sym)
  323. return state;
  324. const StreamState *SS = state->get<StreamMap>(Sym);
  325. // If the file stream is not tracked, return.
  326. if (!SS)
  327. return state;
  328. // Check: Double close a File Descriptor could cause undefined behaviour.
  329. // Conforming to man-pages
  330. if (SS->isClosed()) {
  331. ExplodedNode *N = C.generateSink();
  332. if (N) {
  333. if (!BT_doubleclose)
  334. BT_doubleclose.reset(new BuiltinBug(
  335. this, "Double fclose", "Try to close a file Descriptor already"
  336. " closed. Cause undefined behaviour."));
  337. C.emitReport(llvm::make_unique<BugReport>(
  338. *BT_doubleclose, BT_doubleclose->getDescription(), N));
  339. }
  340. return nullptr;
  341. }
  342. // Close the File Descriptor.
  343. return state->set<StreamMap>(Sym, StreamState::getClosed(CE));
  344. }
  345. void StreamChecker::checkDeadSymbols(SymbolReaper &SymReaper,
  346. CheckerContext &C) const {
  347. // TODO: Clean up the state.
  348. for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
  349. E = SymReaper.dead_end(); I != E; ++I) {
  350. SymbolRef Sym = *I;
  351. ProgramStateRef state = C.getState();
  352. const StreamState *SS = state->get<StreamMap>(Sym);
  353. if (!SS)
  354. continue;
  355. if (SS->isOpened()) {
  356. ExplodedNode *N = C.generateSink();
  357. if (N) {
  358. if (!BT_ResourceLeak)
  359. BT_ResourceLeak.reset(new BuiltinBug(
  360. this, "Resource Leak",
  361. "Opened File never closed. Potential Resource leak."));
  362. C.emitReport(llvm::make_unique<BugReport>(
  363. *BT_ResourceLeak, BT_ResourceLeak->getDescription(), N));
  364. }
  365. }
  366. }
  367. }
  368. void ento::registerStreamChecker(CheckerManager &mgr) {
  369. mgr.registerChecker<StreamChecker>();
  370. }