Clang Project

clang_source_code/lib/StaticAnalyzer/Checkers/VforkChecker.cpp
1//===- VforkChecker.cpp -------- Vfork usage checks --------------*- 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 vfork checker which checks for dangerous uses of vfork.
10//  Vforked process shares memory (including stack) with parent so it's
11//  range of actions is significantly limited: can't write variables,
12//  can't call functions not in whitelist, etc. For more details, see
13//  http://man7.org/linux/man-pages/man2/vfork.2.html
14//
15//  This checker checks for prohibited constructs in vforked process.
16//  The state transition diagram:
17//  PARENT ---(vfork() == 0)--> CHILD
18//                                   |
19//                                   --(*p = ...)--> bug
20//                                   |
21//                                   --foo()--> bug
22//                                   |
23//                                   --return--> bug
24//
25//===----------------------------------------------------------------------===//
26
27#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
28#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
29#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
30#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
31#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
32#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
33#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
34#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
35#include "clang/StaticAnalyzer/Core/Checker.h"
36#include "clang/StaticAnalyzer/Core/CheckerManager.h"
37#include "clang/AST/ParentMap.h"
38
39using namespace clang;
40using namespace ento;
41
42namespace {
43
44class VforkChecker : public Checker<check::PreCall, check::PostCall,
45                                    check::Bind, check::PreStmt<ReturnStmt>> {
46  mutable std::unique_ptr<BuiltinBugBT;
47  mutable llvm::SmallSet<const IdentifierInfo *, 10VforkWhitelist;
48  mutable const IdentifierInfo *II_vfork;
49
50  static bool isChildProcess(const ProgramStateRef State);
51
52  bool isVforkCall(const Decl *DCheckerContext &Cconst;
53  bool isCallWhitelisted(const IdentifierInfo *IICheckerContext &Cconst;
54
55  void reportBug(const char *WhatCheckerContext &C,
56                 const char *Details = nullptrconst;
57
58public:
59  VforkChecker() : II_vfork(nullptr) {}
60
61  void checkPreCall(const CallEvent &CallCheckerContext &Cconst;
62  void checkPostCall(const CallEvent &CallCheckerContext &Cconst;
63  void checkBind(SVal LSVal Vconst Stmt *SCheckerContext &Cconst;
64  void checkPreStmt(const ReturnStmt *RSCheckerContext &Cconst;
65};
66
67// end anonymous namespace
68
69// This trait holds region of variable that is assigned with vfork's
70// return value (this is the only region child is allowed to write).
71// VFORK_RESULT_INVALID means that we are in parent process.
72// VFORK_RESULT_NONE means that vfork's return value hasn't been assigned.
73// Other values point to valid regions.
74REGISTER_TRAIT_WITH_PROGRAMSTATE(VforkResultRegion, const void *)
75#define VFORK_RESULT_INVALID 0
76#define VFORK_RESULT_NONE ((void *)(uintptr_t)1)
77
78bool VforkChecker::isChildProcess(const ProgramStateRef State) {
79  return State->get<VforkResultRegion>() != VFORK_RESULT_INVALID;
80}
81
82bool VforkChecker::isVforkCall(const Decl *DCheckerContext &Cconst {
83  auto FD = dyn_cast_or_null<FunctionDecl>(D);
84  if (!FD || !C.isCLibraryFunction(FD))
85    return false;
86
87  if (!II_vfork) {
88    ASTContext &AC = C.getASTContext();
89    II_vfork = &AC.Idents.get("vfork");
90  }
91
92  return FD->getIdentifier() == II_vfork;
93}
94
95// Returns true iff ok to call function after successful vfork.
96bool VforkChecker::isCallWhitelisted(const IdentifierInfo *II,
97                                 CheckerContext &Cconst {
98  if (VforkWhitelist.empty()) {
99    // According to manpage.
100    const char *ids[] = {
101      "_exit",
102      "_Exit",
103      "execl",
104      "execlp",
105      "execle",
106      "execv",
107      "execvp",
108      "execvpe",
109      nullptr
110    };
111
112    ASTContext &AC = C.getASTContext();
113    for (const char **id = ids; *id; ++id)
114      VforkWhitelist.insert(&AC.Idents.get(*id));
115  }
116
117  return VforkWhitelist.count(II);
118}
119
120void VforkChecker::reportBug(const char *WhatCheckerContext &C,
121                             const char *Detailsconst {
122  if (ExplodedNode *N = C.generateErrorNode(C.getState())) {
123    if (!BT)
124      BT.reset(new BuiltinBug(this,
125                              "Dangerous construct in a vforked process"));
126
127    SmallString<256buf;
128    llvm::raw_svector_ostream os(buf);
129
130    os << What << " is prohibited after a successful vfork";
131
132    if (Details)
133      os << "; " << Details;
134
135    auto Report = llvm::make_unique<BugReport>(*BT, os.str(), N);
136    // TODO: mark vfork call in BugReportVisitor
137    C.emitReport(std::move(Report));
138  }
139}
140
141// Detect calls to vfork and split execution appropriately.
142void VforkChecker::checkPostCall(const CallEvent &Call,
143                                 CheckerContext &Cconst {
144  // We can't call vfork in child so don't bother
145  // (corresponding warning has already been emitted in checkPreCall).
146  ProgramStateRef State = C.getState();
147  if (isChildProcess(State))
148    return;
149
150  if (!isVforkCall(Call.getDecl(), C))
151    return;
152
153  // Get return value of vfork.
154  SVal VforkRetVal = Call.getReturnValue();
155  Optional<DefinedOrUnknownSValDVal =
156    VforkRetVal.getAs<DefinedOrUnknownSVal>();
157  if (!DVal)
158    return;
159
160  // Get assigned variable.
161  const ParentMap &PM = C.getLocationContext()->getParentMap();
162  const Stmt *P = PM.getParentIgnoreParenCasts(Call.getOriginExpr());
163  const VarDecl *LhsDecl;
164  std::tie(LhsDeclstd::ignore) = parseAssignment(P);
165
166  // Get assigned memory region.
167  MemRegionManager &M = C.getStoreManager().getRegionManager();
168  const MemRegion *LhsDeclReg =
169    LhsDecl
170      ? M.getVarRegion(LhsDeclC.getLocationContext())
171      : (const MemRegion *)VFORK_RESULT_NONE;
172
173  // Parent branch gets nonzero return value (according to manpage).
174  ProgramStateRef ParentStateChildState;
175  std::tie(ParentState, ChildState) = C.getState()->assume(*DVal);
176  C.addTransition(ParentState);
177  ChildState = ChildState->set<VforkResultRegion>(LhsDeclReg);
178  C.addTransition(ChildState);
179}
180
181// Prohibit calls to non-whitelist functions in child process.
182void VforkChecker::checkPreCall(const CallEvent &Call,
183                                CheckerContext &Cconst {
184  ProgramStateRef State = C.getState();
185  if (isChildProcess(State)
186      && !isCallWhitelisted(Call.getCalleeIdentifier(), C))
187    reportBug("This function call"C);
188}
189
190// Prohibit writes in child process (except for vfork's lhs).
191void VforkChecker::checkBind(SVal LSVal Vconst Stmt *S,
192                             CheckerContext &Cconst {
193  ProgramStateRef State = C.getState();
194  if (!isChildProcess(State))
195    return;
196
197  const MemRegion *VforkLhs =
198    static_cast<const MemRegion *>(State->get<VforkResultRegion>());
199  const MemRegion *MR = L.getAsRegion();
200
201  // Child is allowed to modify only vfork's lhs.
202  if (!MR || MR == VforkLhs)
203    return;
204
205  reportBug("This assignment"C);
206}
207
208// Prohibit return from function in child process.
209void VforkChecker::checkPreStmt(const ReturnStmt *RSCheckerContext &Cconst {
210  ProgramStateRef State = C.getState();
211  if (isChildProcess(State))
212    reportBug("Return"C"call _exit() instead");
213}
214
215void ento::registerVforkChecker(CheckerManager &mgr) {
216  mgr.registerChecker<VforkChecker>();
217}
218
219bool ento::shouldRegisterVforkChecker(const LangOptions &LO) {
220  return true;
221}
222