PutenvWithAutoChecker.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. //== PutenvWithAutoChecker.cpp --------------------------------- -*- C++ -*--=//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines PutenvWithAutoChecker which finds calls of ``putenv``
  10. // function with automatic variable as the argument.
  11. // https://wiki.sei.cmu.edu/confluence/x/6NYxBQ
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "../AllocationState.h"
  15. #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.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/CallDescription.h"
  20. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  21. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  22. #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
  23. using namespace clang;
  24. using namespace ento;
  25. namespace {
  26. class PutenvWithAutoChecker : public Checker<check::PostCall> {
  27. private:
  28. BugType BT{this, "'putenv' function should not be called with auto variables",
  29. categories::SecurityError};
  30. const CallDescription Putenv{"putenv", 1};
  31. public:
  32. void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
  33. };
  34. } // namespace
  35. void PutenvWithAutoChecker::checkPostCall(const CallEvent &Call,
  36. CheckerContext &C) const {
  37. if (!Putenv.matches(Call))
  38. return;
  39. SVal ArgV = Call.getArgSVal(0);
  40. const Expr *ArgExpr = Call.getArgExpr(0);
  41. const MemSpaceRegion *MSR = ArgV.getAsRegion()->getMemorySpace();
  42. if (!isa<StackSpaceRegion>(MSR))
  43. return;
  44. StringRef ErrorMsg = "The 'putenv' function should not be called with "
  45. "arguments that have automatic storage";
  46. ExplodedNode *N = C.generateErrorNode();
  47. auto Report = std::make_unique<PathSensitiveBugReport>(BT, ErrorMsg, N);
  48. // Track the argument.
  49. bugreporter::trackExpressionValue(Report->getErrorNode(), ArgExpr, *Report);
  50. C.emitReport(std::move(Report));
  51. }
  52. void ento::registerPutenvWithAuto(CheckerManager &Mgr) {
  53. Mgr.registerChecker<PutenvWithAutoChecker>();
  54. }
  55. bool ento::shouldRegisterPutenvWithAuto(const CheckerManager &) { return true; }