Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp
Line
Count
Source (jump to first uncovered line)
1
//== MIGChecker.cpp - MIG calling convention checker ------------*- 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 MIGChecker, a Mach Interface Generator calling convention
10
// checker. Namely, in MIG callback implementation the following rules apply:
11
// - When a server routine returns an error code that represents success, it
12
//   must take ownership of resources passed to it (and eventually release
13
//   them).
14
// - Additionally, when returning success, all out-parameters must be
15
//   initialized.
16
// - When it returns any other error code, it must not take ownership,
17
//   because the message and its out-of-line parameters will be destroyed
18
//   by the client that called the function.
19
// For now we only check the last rule, as its violations lead to dangerous
20
// use-after-free exploits.
21
//
22
//===----------------------------------------------------------------------===//
23
24
#include "clang/Analysis/AnyCall.h"
25
#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
26
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
27
#include "clang/StaticAnalyzer/Core/Checker.h"
28
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
29
#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
30
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
31
32
using namespace clang;
33
using namespace ento;
34
35
namespace {
36
class MIGChecker : public Checker<check::PostCall, check::PreStmt<ReturnStmt>,
37
                                  check::EndFunction> {
38
  BugType BT{this, "Use-after-free (MIG calling convention violation)",
39
             categories::MemoryError};
40
41
  // The checker knows that an out-of-line object is deallocated if it is
42
  // passed as an argument to one of these functions. If this object is
43
  // additionally an argument of a MIG routine, the checker keeps track of that
44
  // information and issues a warning when an error is returned from the
45
  // respective routine.
46
  std::vector<std::pair<CallDescription, unsigned>> Deallocators = {
47
#define CALL(required_args, deallocated_arg, ...)                              \
48
  {{{__VA_ARGS__}, required_args}, deallocated_arg}
49
      // E.g., if the checker sees a C function 'vm_deallocate' that is
50
      // defined on class 'IOUserClient' that has exactly 3 parameters, it knows
51
      // that argument #1 (starting from 0, i.e. the second argument) is going
52
      // to be consumed in the sense of the MIG consume-on-success convention.
53
      CALL(3, 1, "vm_deallocate"),
54
      CALL(3, 1, "mach_vm_deallocate"),
55
      CALL(2, 0, "mig_deallocate"),
56
      CALL(2, 1, "mach_port_deallocate"),
57
      CALL(1, 0, "device_deallocate"),
58
      CALL(1, 0, "iokit_remove_connect_reference"),
59
      CALL(1, 0, "iokit_remove_reference"),
60
      CALL(1, 0, "iokit_release_port"),
61
      CALL(1, 0, "ipc_port_release"),
62
      CALL(1, 0, "ipc_port_release_sonce"),
63
      CALL(1, 0, "ipc_voucher_attr_control_release"),
64
      CALL(1, 0, "ipc_voucher_release"),
65
      CALL(1, 0, "lock_set_dereference"),
66
      CALL(1, 0, "memory_object_control_deallocate"),
67
      CALL(1, 0, "pset_deallocate"),
68
      CALL(1, 0, "semaphore_dereference"),
69
      CALL(1, 0, "space_deallocate"),
70
      CALL(1, 0, "space_inspect_deallocate"),
71
      CALL(1, 0, "task_deallocate"),
72
      CALL(1, 0, "task_inspect_deallocate"),
73
      CALL(1, 0, "task_name_deallocate"),
74
      CALL(1, 0, "thread_deallocate"),
75
      CALL(1, 0, "thread_inspect_deallocate"),
76
      CALL(1, 0, "upl_deallocate"),
77
      CALL(1, 0, "vm_map_deallocate"),
78
      // E.g., if the checker sees a method 'releaseAsyncReference64()' that is
79
      // defined on class 'IOUserClient' that takes exactly 1 argument, it knows
80
      // that the argument is going to be consumed in the sense of the MIG
81
      // consume-on-success convention.
82
      CALL(1, 0, "IOUserClient", "releaseAsyncReference64"),
83
      CALL(1, 0, "IOUserClient", "releaseNotificationPort"),
84
#undef CALL
85
  };
86
87
  CallDescription OsRefRetain{"os_ref_retain", 1};
88
89
  void checkReturnAux(const ReturnStmt *RS, CheckerContext &C) const;
90
91
public:
92
  void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
93
94
  // HACK: We're making two attempts to find the bug: checkEndFunction
95
  // should normally be enough but it fails when the return value is a literal
96
  // that never gets put into the Environment and ends of function with multiple
97
  // returns get agglutinated across returns, preventing us from obtaining
98
  // the return value. The problem is similar to https://reviews.llvm.org/D25326
99
  // but now we step into it in the top-level function.
100
100
  void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const {
101
100
    checkReturnAux(RS, C);
102
100
  }
103
270
  void checkEndFunction(const ReturnStmt *RS, CheckerContext &C) const {
104
270
    checkReturnAux(RS, C);
105
270
  }
106
107
};
108
} // end anonymous namespace
109
110
// A flag that says that the programmer has called a MIG destructor
111
// for at least one parameter.
112
REGISTER_TRAIT_WITH_PROGRAMSTATE(ReleasedParameter, bool)
113
// A set of parameters for which the check is suppressed because
114
// reference counting is being performed.
115
REGISTER_SET_WITH_PROGRAMSTATE(RefCountedParameters, const ParmVarDecl *)
116
117
static const ParmVarDecl *getOriginParam(SVal V, CheckerContext &C,
118
21
                                         bool IncludeBaseRegions = false) {
119
21
  // TODO: We should most likely always include base regions here.
120
21
  SymbolRef Sym = V.getAsSymbol(IncludeBaseRegions);
121
21
  if (!Sym)
122
0
    return nullptr;
123
21
124
21
  // If we optimistically assume that the MIG routine never re-uses the storage
125
21
  // that was passed to it as arguments when it invalidates it (but at most when
126
21
  // it assigns to parameter variables directly), this procedure correctly
127
21
  // determines if the value was loaded from the transitive closure of MIG
128
21
  // routine arguments in the heap.
129
23
  
while (const MemRegion *21
MR = Sym->getOriginRegion()) {
130
23
    const auto *VR = dyn_cast<VarRegion>(MR);
131
23
    if (VR && 
VR->hasStackParametersStorage()21
&&
132
23
           
VR->getStackFrame()->inTopFrame()21
)
133
21
      return cast<ParmVarDecl>(VR->getDecl());
134
2
135
2
    const SymbolicRegion *SR = MR->getSymbolicBase();
136
2
    if (!SR)
137
0
      return nullptr;
138
2
139
2
    Sym = SR->getSymbol();
140
2
  }
141
21
142
21
  
return nullptr0
;
143
21
}
144
145
611
static bool isInMIGCall(CheckerContext &C) {
146
611
  const LocationContext *LC = C.getLocationContext();
147
611
  assert(LC && "Unknown location context");
148
611
149
611
  const StackFrameContext *SFC;
150
611
  // Find the top frame.
151
1.30k
  while (LC) {
152
691
    SFC = LC->getStackFrame();
153
691
    LC = SFC->getParent();
154
691
  }
155
611
156
611
  const Decl *D = SFC->getDecl();
157
611
158
611
  if (Optional<AnyCall> AC = AnyCall::forDecl(D)) {
159
605
    // Even though there's a Sema warning when the return type of an annotated
160
605
    // function is not a kern_return_t, this warning isn't an error, so we need
161
605
    // an extra sanity check here.
162
605
    // FIXME: AnyCall doesn't support blocks yet, so they remain unchecked
163
605
    // for now.
164
605
    if (!AC->getReturnType(C.getASTContext())
165
605
             .getCanonicalType()->isSignedIntegerType())
166
487
      return false;
167
124
  }
168
124
169
124
  if (D->hasAttr<MIGServerRoutineAttr>())
170
46
    return true;
171
78
172
78
  // See if there's an annotated method in the superclass.
173
78
  if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
174
4
    for (const auto *OMD: MD->overridden_methods())
175
4
      if (OMD->hasAttr<MIGServerRoutineAttr>())
176
4
        return true;
177
78
178
78
  
return false74
;
179
78
}
180
181
392
void MIGChecker::checkPostCall(const CallEvent &Call, CheckerContext &C) const {
182
392
  if (Call.isCalled(OsRefRetain)) {
183
1
    // If the code is doing reference counting over the parameter,
184
1
    // it opens up an opportunity for safely calling a destructor function.
185
1
    // TODO: We should still check for over-releases.
186
1
    if (const ParmVarDecl *PVD =
187
1
            getOriginParam(Call.getArgSVal(0), C, /*IncludeBaseRegions=*/true)) {
188
1
      // We never need to clean up the program state because these are
189
1
      // top-level parameters anyway, so they're always live.
190
1
      C.addTransition(C.getState()->add<RefCountedParameters>(PVD));
191
1
    }
192
1
    return;
193
1
  }
194
391
195
391
  if (!isInMIGCall(C))
196
367
    return;
197
24
198
24
  auto I = llvm::find_if(Deallocators,
199
242
                         [&](const std::pair<CallDescription, unsigned> &Item) {
200
242
                           return Call.isCalled(Item.first);
201
242
                         });
202
24
  if (I == Deallocators.end())
203
4
    return;
204
20
205
20
  ProgramStateRef State = C.getState();
206
20
  unsigned ArgIdx = I->second;
207
20
  SVal Arg = Call.getArgSVal(ArgIdx);
208
20
  const ParmVarDecl *PVD = getOriginParam(Arg, C);
209
20
  if (!PVD || State->contains<RefCountedParameters>(PVD))
210
1
    return;
211
19
212
19
  const NoteTag *T = C.getNoteTag([this, PVD](BugReport &BR) -> std::string {
213
14
    if (&BR.getBugType() != &BT)
214
1
      return "";
215
13
    SmallString<64> Str;
216
13
    llvm::raw_svector_ostream OS(Str);
217
13
    OS << "Value passed through parameter '" << PVD->getName()
218
13
       << "\' is deallocated";
219
13
    return OS.str();
220
13
  });
221
19
  C.addTransition(State->set<ReleasedParameter>(true), T);
222
19
}
223
224
// Returns true if V can potentially represent a "successful" kern_return_t.
225
21
static bool mayBeSuccess(SVal V, CheckerContext &C) {
226
21
  ProgramStateRef State = C.getState();
227
21
228
21
  // Can V represent KERN_SUCCESS?
229
21
  if (!State->isNull(V).isConstrainedFalse())
230
7
    return true;
231
14
232
14
  SValBuilder &SVB = C.getSValBuilder();
233
14
  ASTContext &ACtx = C.getASTContext();
234
14
235
14
  // Can V represent MIG_NO_REPLY?
236
14
  static const int MigNoReply = -305;
237
14
  V = SVB.evalEQ(C.getState(), V, SVB.makeIntVal(MigNoReply, ACtx.IntTy));
238
14
  if (!State->isNull(V).isConstrainedTrue())
239
2
    return true;
240
12
241
12
  // If none of the above, it's definitely an error.
242
12
  return false;
243
12
}
244
245
370
void MIGChecker::checkReturnAux(const ReturnStmt *RS, CheckerContext &C) const {
246
370
  // It is very unlikely that a MIG callback will be called from anywhere
247
370
  // within the project under analysis and the caller isn't itself a routine
248
370
  // that follows the MIG calling convention. Therefore we're safe to believe
249
370
  // that it's always the top frame that is of interest. There's a slight chance
250
370
  // that the user would want to enforce the MIG calling convention upon
251
370
  // a random routine in the middle of nowhere, but given that the convention is
252
370
  // fairly weird and hard to follow in the first place, there's relatively
253
370
  // little motivation to spread it this way.
254
370
  if (!C.inTopFrame())
255
150
    return;
256
220
257
220
  if (!isInMIGCall(C))
258
194
    return;
259
26
260
26
  // We know that the function is non-void, but what if the return statement
261
26
  // is not there in the code? It's not a compile error, we should not crash.
262
26
  if (!RS)
263
1
    return;
264
25
265
25
  ProgramStateRef State = C.getState();
266
25
  if (!State->get<ReleasedParameter>())
267
4
    return;
268
21
269
21
  SVal V = C.getSVal(RS);
270
21
  if (mayBeSuccess(V, C))
271
9
    return;
272
12
273
12
  ExplodedNode *N = C.generateErrorNode();
274
12
  if (!N)
275
0
    return;
276
12
277
12
  auto R = llvm::make_unique<BugReport>(
278
12
      BT,
279
12
      "MIG callback fails with error after deallocating argument value. "
280
12
      "This is a use-after-free vulnerability because the caller will try to "
281
12
      "deallocate it again",
282
12
      N);
283
12
284
12
  R->addRange(RS->getSourceRange());
285
12
  bugreporter::trackExpressionValue(N, RS->getRetValue(), *R, false);
286
12
  C.emitReport(std::move(R));
287
12
}
288
289
24
void ento::registerMIGChecker(CheckerManager &Mgr) {
290
24
  Mgr.registerChecker<MIGChecker>();
291
24
}
292
293
24
bool ento::shouldRegisterMIGChecker(const LangOptions &LO) {
294
24
  return true;
295
24
}