Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp
Line
Count
Source (jump to first uncovered line)
1
//==--- MacOSKeychainAPIChecker.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
// This checker flags misuses of KeyChainAPI. In particular, the password data
9
// allocated/returned by SecKeychainItemCopyContent,
10
// SecKeychainFindGenericPassword, SecKeychainFindInternetPassword functions has
11
// to be freed using a call to SecKeychainItemFreeContent.
12
//===----------------------------------------------------------------------===//
13
14
#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
15
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
16
#include "clang/StaticAnalyzer/Core/Checker.h"
17
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
18
#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
19
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
20
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
21
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
22
#include "llvm/ADT/SmallString.h"
23
#include "llvm/Support/raw_ostream.h"
24
25
using namespace clang;
26
using namespace ento;
27
28
namespace {
29
class MacOSKeychainAPIChecker : public Checker<check::PreStmt<CallExpr>,
30
                                               check::PostStmt<CallExpr>,
31
                                               check::DeadSymbols,
32
                                               check::PointerEscape,
33
                                               eval::Assume> {
34
  mutable std::unique_ptr<BugType> BT;
35
36
public:
37
  /// AllocationState is a part of the checker specific state together with the
38
  /// MemRegion corresponding to the allocated data.
39
  struct AllocationState {
40
    /// The index of the allocator function.
41
    unsigned int AllocatorIdx;
42
    SymbolRef Region;
43
44
    AllocationState(const Expr *E, unsigned int Idx, SymbolRef R) :
45
      AllocatorIdx(Idx),
46
28
      Region(R) {}
47
48
2
    bool operator==(const AllocationState &X) const {
49
2
      return (AllocatorIdx == X.AllocatorIdx &&
50
2
              Region == X.Region);
51
2
    }
52
53
31
    void Profile(llvm::FoldingSetNodeID &ID) const {
54
31
      ID.AddInteger(AllocatorIdx);
55
31
      ID.AddPointer(Region);
56
31
    }
57
  };
58
59
  void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
60
  void checkPostStmt(const CallExpr *S, CheckerContext &C) const;
61
  void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
62
  ProgramStateRef checkPointerEscape(ProgramStateRef State,
63
                                     const InvalidatedSymbols &Escaped,
64
                                     const CallEvent *Call,
65
                                     PointerEscapeKind Kind) const;
66
  ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
67
                             bool Assumption) const;
68
  void printState(raw_ostream &Out, ProgramStateRef State,
69
                  const char *NL, const char *Sep) const;
70
71
private:
72
  typedef std::pair<SymbolRef, const AllocationState*> AllocationPair;
73
  typedef SmallVector<AllocationPair, 2> AllocationPairVec;
74
75
  enum APIKind {
76
    /// Denotes functions tracked by this checker.
77
    ValidAPI = 0,
78
    /// The functions commonly/mistakenly used in place of the given API.
79
    ErrorAPI = 1,
80
    /// The functions which may allocate the data. These are tracked to reduce
81
    /// the false alarm rate.
82
    PossibleAPI = 2
83
  };
84
  /// Stores the information about the allocator and deallocator functions -
85
  /// these are the functions the checker is tracking.
86
  struct ADFunctionInfo {
87
    const char* Name;
88
    unsigned int Param;
89
    unsigned int DeallocatorIdx;
90
    APIKind Kind;
91
  };
92
  static const unsigned InvalidIdx = 100000;
93
  static const unsigned FunctionsToTrackSize = 8;
94
  static const ADFunctionInfo FunctionsToTrack[FunctionsToTrackSize];
95
  /// The value, which represents no error return value for allocator functions.
96
  static const unsigned NoErr = 0;
97
98
  /// Given the function name, returns the index of the allocator/deallocator
99
  /// function.
100
  static unsigned getTrackedFunctionIndex(StringRef Name, bool IsAllocator);
101
102
14
  inline void initBugType() const {
103
14
    if (!BT)
104
2
      BT.reset(new BugType(this, "Improper use of SecKeychain API",
105
2
                           "API Misuse (Apple)"));
106
14
  }
107
108
  void generateDeallocatorMismatchReport(const AllocationPair &AP,
109
                                         const Expr *ArgExpr,
110
                                         CheckerContext &C) const;
111
112
  /// Find the allocation site for Sym on the path leading to the node N.
113
  const ExplodedNode *getAllocationNode(const ExplodedNode *N, SymbolRef Sym,
114
                                        CheckerContext &C) const;
115
116
  std::unique_ptr<BugReport> generateAllocatedDataNotReleasedReport(
117
      const AllocationPair &AP, ExplodedNode *N, CheckerContext &C) const;
118
119
  /// Mark an AllocationPair interesting for diagnostic reporting.
120
13
  void markInteresting(BugReport *R, const AllocationPair &AP) const {
121
13
    R->markInteresting(AP.first);
122
13
    R->markInteresting(AP.second->Region);
123
13
  }
124
125
  /// The bug visitor which allows us to print extra diagnostics along the
126
  /// BugReport path. For example, showing the allocation site of the leaked
127
  /// region.
128
  class SecKeychainBugVisitor : public BugReporterVisitor {
129
  protected:
130
    // The allocated region symbol tracked by the main analysis.
131
    SymbolRef Sym;
132
133
  public:
134
14
    SecKeychainBugVisitor(SymbolRef S) : Sym(S) {}
135
136
14
    void Profile(llvm::FoldingSetNodeID &ID) const override {
137
14
      static int X = 0;
138
14
      ID.AddPointer(&X);
139
14
      ID.AddPointer(Sym);
140
14
    }
141
142
    std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
143
                                                   BugReporterContext &BRC,
144
                                                   BugReport &BR) override;
145
  };
146
};
147
}
148
149
/// ProgramState traits to store the currently allocated (and not yet freed)
150
/// symbols. This is a map from the allocated content symbol to the
151
/// corresponding AllocationState.
152
REGISTER_MAP_WITH_PROGRAMSTATE(AllocatedData,
153
                               SymbolRef,
154
                               MacOSKeychainAPIChecker::AllocationState)
155
156
31
static bool isEnclosingFunctionParam(const Expr *E) {
157
31
  E = E->IgnoreParenCasts();
158
31
  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
159
5
    const ValueDecl *VD = DRE->getDecl();
160
5
    if (isa<ImplicitParamDecl>(VD) || isa<ParmVarDecl>(VD))
161
4
      return true;
162
27
  }
163
27
  return false;
164
27
}
165
166
const MacOSKeychainAPIChecker::ADFunctionInfo
167
  MacOSKeychainAPIChecker::FunctionsToTrack[FunctionsToTrackSize] = {
168
    {"SecKeychainItemCopyContent", 4, 3, ValidAPI},                       // 0
169
    {"SecKeychainFindGenericPassword", 6, 3, ValidAPI},                   // 1
170
    {"SecKeychainFindInternetPassword", 13, 3, ValidAPI},                 // 2
171
    {"SecKeychainItemFreeContent", 1, InvalidIdx, ValidAPI},              // 3
172
    {"SecKeychainItemCopyAttributesAndData", 5, 5, ValidAPI},             // 4
173
    {"SecKeychainItemFreeAttributesAndData", 1, InvalidIdx, ValidAPI},    // 5
174
    {"free", 0, InvalidIdx, ErrorAPI},                                    // 6
175
    {"CFStringCreateWithBytesNoCopy", 1, InvalidIdx, PossibleAPI},        // 7
176
};
177
178
unsigned MacOSKeychainAPIChecker::getTrackedFunctionIndex(StringRef Name,
179
462
                                                          bool IsAllocator) {
180
3.32k
  for (unsigned I = 0; I < FunctionsToTrackSize; 
++I2.86k
) {
181
3.01k
    ADFunctionInfo FI = FunctionsToTrack[I];
182
3.01k
    if (FI.Name != Name)
183
2.86k
      continue;
184
150
    // Make sure the function is of the right type (allocator vs deallocator).
185
150
    if (IsAllocator && 
(FI.DeallocatorIdx == InvalidIdx)125
)
186
50
      return InvalidIdx;
187
100
    if (!IsAllocator && 
(FI.DeallocatorIdx != InvalidIdx)25
)
188
0
      return InvalidIdx;
189
100
190
100
    return I;
191
100
  }
192
462
  // The function is not tracked.
193
462
  
return InvalidIdx312
;
194
462
}
195
196
0
static bool isBadDeallocationArgument(const MemRegion *Arg) {
197
0
  if (!Arg)
198
0
    return false;
199
0
  return isa<AllocaRegion>(Arg) || isa<BlockDataRegion>(Arg) ||
200
0
         isa<TypedRegion>(Arg);
201
0
}
202
203
/// Given the address expression, retrieve the value it's pointing to. Assume
204
/// that value is itself an address, and return the corresponding symbol.
205
static SymbolRef getAsPointeeSymbol(const Expr *Expr,
206
61
                                    CheckerContext &C) {
207
61
  ProgramStateRef State = C.getState();
208
61
  SVal ArgV = C.getSVal(Expr);
209
61
210
61
  if (Optional<loc::MemRegionVal> X = ArgV.getAs<loc::MemRegionVal>()) {
211
57
    StoreManager& SM = C.getStoreManager();
212
57
    SymbolRef sym = SM.getBinding(State->getStore(), *X).getAsLocSymbol();
213
57
    if (sym)
214
31
      return sym;
215
30
  }
216
30
  return nullptr;
217
30
}
218
219
// Report deallocator mismatch. Remove the region from tracking - reporting a
220
// missing free error after this one is redundant.
221
void MacOSKeychainAPIChecker::
222
  generateDeallocatorMismatchReport(const AllocationPair &AP,
223
                                    const Expr *ArgExpr,
224
4
                                    CheckerContext &C) const {
225
4
  ProgramStateRef State = C.getState();
226
4
  State = State->remove<AllocatedData>(AP.first);
227
4
  ExplodedNode *N = C.generateNonFatalErrorNode(State);
228
4
229
4
  if (!N)
230
0
    return;
231
4
  initBugType();
232
4
  SmallString<80> sbuf;
233
4
  llvm::raw_svector_ostream os(sbuf);
234
4
  unsigned int PDeallocIdx =
235
4
               FunctionsToTrack[AP.second->AllocatorIdx].DeallocatorIdx;
236
4
237
4
  os << "Deallocator doesn't match the allocator: '"
238
4
     << FunctionsToTrack[PDeallocIdx].Name << "' should be used.";
239
4
  auto Report = llvm::make_unique<BugReport>(*BT, os.str(), N);
240
4
  Report->addVisitor(llvm::make_unique<SecKeychainBugVisitor>(AP.first));
241
4
  Report->addRange(ArgExpr->getSourceRange());
242
4
  markInteresting(Report.get(), AP);
243
4
  C.emitReport(std::move(Report));
244
4
}
245
246
void MacOSKeychainAPIChecker::checkPreStmt(const CallExpr *CE,
247
313
                                           CheckerContext &C) const {
248
313
  unsigned idx = InvalidIdx;
249
313
  ProgramStateRef State = C.getState();
250
313
251
313
  const FunctionDecl *FD = C.getCalleeDecl(CE);
252
313
  if (!FD || 
FD->getKind() != Decl::Function310
)
253
157
    return;
254
156
255
156
  StringRef funName = C.getCalleeName(FD);
256
156
  if (funName.empty())
257
0
    return;
258
156
259
156
  // If it is a call to an allocator function, it could be a double allocation.
260
156
  idx = getTrackedFunctionIndex(funName, true);
261
156
  if (idx != InvalidIdx) {
262
31
    unsigned paramIdx = FunctionsToTrack[idx].Param;
263
31
    if (CE->getNumArgs() <= paramIdx)
264
0
      return;
265
31
266
31
    const Expr *ArgExpr = CE->getArg(paramIdx);
267
31
    if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C))
268
3
      if (const AllocationState *AS = State->get<AllocatedData>(V)) {
269
1
        // Remove the value from the state. The new symbol will be added for
270
1
        // tracking when the second allocator is processed in checkPostStmt().
271
1
        State = State->remove<AllocatedData>(V);
272
1
        ExplodedNode *N = C.generateNonFatalErrorNode(State);
273
1
        if (!N)
274
0
          return;
275
1
        initBugType();
276
1
        SmallString<128> sbuf;
277
1
        llvm::raw_svector_ostream os(sbuf);
278
1
        unsigned int DIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
279
1
        os << "Allocated data should be released before another call to "
280
1
            << "the allocator: missing a call to '"
281
1
            << FunctionsToTrack[DIdx].Name
282
1
            << "'.";
283
1
        auto Report = llvm::make_unique<BugReport>(*BT, os.str(), N);
284
1
        Report->addVisitor(llvm::make_unique<SecKeychainBugVisitor>(V));
285
1
        Report->addRange(ArgExpr->getSourceRange());
286
1
        Report->markInteresting(AS->Region);
287
1
        C.emitReport(std::move(Report));
288
1
      }
289
31
    return;
290
125
  }
291
125
292
125
  // Is it a call to one of deallocator functions?
293
125
  idx = getTrackedFunctionIndex(funName, false);
294
125
  if (idx == InvalidIdx)
295
100
    return;
296
25
297
25
  unsigned paramIdx = FunctionsToTrack[idx].Param;
298
25
  if (CE->getNumArgs() <= paramIdx)
299
1
    return;
300
24
301
24
  // Check the argument to the deallocator.
302
24
  const Expr *ArgExpr = CE->getArg(paramIdx);
303
24
  SVal ArgSVal = C.getSVal(ArgExpr);
304
24
305
24
  // Undef is reported by another checker.
306
24
  if (ArgSVal.isUndef())
307
1
    return;
308
23
309
23
  SymbolRef ArgSM = ArgSVal.getAsLocSymbol();
310
23
311
23
  // If the argument is coming from the heap, globals, or unknown, do not
312
23
  // report it.
313
23
  bool RegionArgIsBad = false;
314
23
  if (!ArgSM) {
315
0
    if (!isBadDeallocationArgument(ArgSVal.getAsRegion()))
316
0
      return;
317
0
    RegionArgIsBad = true;
318
0
  }
319
23
320
23
  // Is the argument to the call being tracked?
321
23
  const AllocationState *AS = State->get<AllocatedData>(ArgSM);
322
23
  if (!AS)
323
4
    return;
324
19
325
19
  // TODO: We might want to report double free here.
326
19
  // (that would involve tracking all the freed symbols in the checker state).
327
19
  if (RegionArgIsBad) {
328
0
    // It is possible that this is a false positive - the argument might
329
0
    // have entered as an enclosing function parameter.
330
0
    if (isEnclosingFunctionParam(ArgExpr))
331
0
      return;
332
0
333
0
    ExplodedNode *N = C.generateNonFatalErrorNode(State);
334
0
    if (!N)
335
0
      return;
336
0
    initBugType();
337
0
    auto Report = llvm::make_unique<BugReport>(
338
0
        *BT, "Trying to free data which has not been allocated.", N);
339
0
    Report->addRange(ArgExpr->getSourceRange());
340
0
    if (AS)
341
0
      Report->markInteresting(AS->Region);
342
0
    C.emitReport(std::move(Report));
343
0
    return;
344
0
  }
345
19
346
19
  // Process functions which might deallocate.
347
19
  if (FunctionsToTrack[idx].Kind == PossibleAPI) {
348
5
349
5
    if (funName == "CFStringCreateWithBytesNoCopy") {
350
5
      const Expr *DeallocatorExpr = CE->getArg(5)->IgnoreParenCasts();
351
5
      // NULL ~ default deallocator, so warn.
352
5
      if (DeallocatorExpr->isNullPointerConstant(C.getASTContext(),
353
5
          Expr::NPC_ValueDependentIsNotNull)) {
354
1
        const AllocationPair AP = std::make_pair(ArgSM, AS);
355
1
        generateDeallocatorMismatchReport(AP, ArgExpr, C);
356
1
        return;
357
1
      }
358
4
      // One of the default allocators, so warn.
359
4
      if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(DeallocatorExpr)) {
360
3
        StringRef DeallocatorName = DE->getFoundDecl()->getName();
361
3
        if (DeallocatorName == "kCFAllocatorDefault" ||
362
3
            
DeallocatorName == "kCFAllocatorSystemDefault"2
||
363
3
            
DeallocatorName == "kCFAllocatorMalloc"2
) {
364
1
          const AllocationPair AP = std::make_pair(ArgSM, AS);
365
1
          generateDeallocatorMismatchReport(AP, ArgExpr, C);
366
1
          return;
367
1
        }
368
2
        // If kCFAllocatorNull, which does not deallocate, we still have to
369
2
        // find the deallocator.
370
2
        if (DE->getFoundDecl()->getName() == "kCFAllocatorNull")
371
1
          return;
372
2
      }
373
2
      // In all other cases, assume the user supplied a correct deallocator
374
2
      // that will free memory so stop tracking.
375
2
      State = State->remove<AllocatedData>(ArgSM);
376
2
      C.addTransition(State);
377
2
      return;
378
2
    }
379
0
380
0
    llvm_unreachable("We know of no other possible APIs.");
381
0
  }
382
14
383
14
  // The call is deallocating a value we previously allocated, so remove it
384
14
  // from the next state.
385
14
  State = State->remove<AllocatedData>(ArgSM);
386
14
387
14
  // Check if the proper deallocator is used.
388
14
  unsigned int PDeallocIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
389
14
  if (PDeallocIdx != idx || 
(FunctionsToTrack[idx].Kind == ErrorAPI)12
) {
390
2
    const AllocationPair AP = std::make_pair(ArgSM, AS);
391
2
    generateDeallocatorMismatchReport(AP, ArgExpr, C);
392
2
    return;
393
2
  }
394
12
395
12
  C.addTransition(State);
396
12
}
397
398
void MacOSKeychainAPIChecker::checkPostStmt(const CallExpr *CE,
399
324
                                            CheckerContext &C) const {
400
324
  ProgramStateRef State = C.getState();
401
324
  const FunctionDecl *FD = C.getCalleeDecl(CE);
402
324
  if (!FD || 
FD->getKind() != Decl::Function321
)
403
156
    return;
404
168
405
168
  StringRef funName = C.getCalleeName(FD);
406
168
407
168
  // If a value has been allocated, add it to the set for tracking.
408
168
  unsigned idx = getTrackedFunctionIndex(funName, true);
409
168
  if (idx == InvalidIdx)
410
137
    return;
411
31
412
31
  const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
413
31
  // If the argument entered as an enclosing function parameter, skip it to
414
31
  // avoid false positives.
415
31
  if (isEnclosingFunctionParam(ArgExpr) &&
416
31
      
C.getLocationContext()->getParent() == nullptr4
)
417
1
    return;
418
30
419
30
  if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C)) {
420
28
    // If the argument points to something that's not a symbolic region, it
421
28
    // can be:
422
28
    //  - unknown (cannot reason about it)
423
28
    //  - undefined (already reported by other checker)
424
28
    //  - constant (null - should not be tracked,
425
28
    //              other constant will generate a compiler warning)
426
28
    //  - goto (should be reported by other checker)
427
28
428
28
    // The call return value symbol should stay alive for as long as the
429
28
    // allocated value symbol, since our diagnostics depend on the value
430
28
    // returned by the call. Ex: Data should only be freed if noErr was
431
28
    // returned during allocation.)
432
28
    SymbolRef RetStatusSymbol = C.getSVal(CE).getAsSymbol();
433
28
    C.getSymbolManager().addSymbolDependency(V, RetStatusSymbol);
434
28
435
28
    // Track the allocated value in the checker state.
436
28
    State = State->set<AllocatedData>(V, AllocationState(ArgExpr, idx,
437
28
                                                         RetStatusSymbol));
438
28
    assert(State);
439
28
    C.addTransition(State);
440
28
  }
441
30
}
442
443
// TODO: This logic is the same as in Malloc checker.
444
const ExplodedNode *
445
MacOSKeychainAPIChecker::getAllocationNode(const ExplodedNode *N,
446
                                           SymbolRef Sym,
447
9
                                           CheckerContext &C) const {
448
9
  const LocationContext *LeakContext = N->getLocationContext();
449
9
  // Walk the ExplodedGraph backwards and find the first node that referred to
450
9
  // the tracked symbol.
451
9
  const ExplodedNode *AllocNode = N;
452
9
453
303
  while (N) {
454
303
    if (!N->getState()->get<AllocatedData>(Sym))
455
9
      break;
456
294
    // Allocation node, is the last node in the current or parent context in
457
294
    // which the symbol was tracked.
458
294
    const LocationContext *NContext = N->getLocationContext();
459
294
    if (NContext == LeakContext ||
460
294
        
NContext->isParentOf(LeakContext)74
)
461
220
      AllocNode = N;
462
294
    N = N->pred_empty() ? 
nullptr0
: *(N->pred_begin());
463
294
  }
464
9
465
9
  return AllocNode;
466
9
}
467
468
std::unique_ptr<BugReport>
469
MacOSKeychainAPIChecker::generateAllocatedDataNotReleasedReport(
470
9
    const AllocationPair &AP, ExplodedNode *N, CheckerContext &C) const {
471
9
  const ADFunctionInfo &FI = FunctionsToTrack[AP.second->AllocatorIdx];
472
9
  initBugType();
473
9
  SmallString<70> sbuf;
474
9
  llvm::raw_svector_ostream os(sbuf);
475
9
  os << "Allocated data is not released: missing a call to '"
476
9
      << FunctionsToTrack[FI.DeallocatorIdx].Name << "'.";
477
9
478
9
  // Most bug reports are cached at the location where they occurred.
479
9
  // With leaks, we want to unique them by the location where they were
480
9
  // allocated, and only report a single path.
481
9
  PathDiagnosticLocation LocUsedForUniqueing;
482
9
  const ExplodedNode *AllocNode = getAllocationNode(N, AP.first, C);
483
9
  const Stmt *AllocStmt = PathDiagnosticLocation::getStmt(AllocNode);
484
9
485
9
  if (AllocStmt)
486
9
    LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt,
487
9
                                              C.getSourceManager(),
488
9
                                              AllocNode->getLocationContext());
489
9
490
9
  auto Report =
491
9
      llvm::make_unique<BugReport>(*BT, os.str(), N, LocUsedForUniqueing,
492
9
                                  AllocNode->getLocationContext()->getDecl());
493
9
494
9
  Report->addVisitor(llvm::make_unique<SecKeychainBugVisitor>(AP.first));
495
9
  markInteresting(Report.get(), AP);
496
9
  return Report;
497
9
}
498
499
/// If the return symbol is assumed to be error, remove the allocated info
500
/// from consideration.
501
ProgramStateRef MacOSKeychainAPIChecker::evalAssume(ProgramStateRef State,
502
                                                    SVal Cond,
503
1.13k
                                                    bool Assumption) const {
504
1.13k
  AllocatedDataTy AMap = State->get<AllocatedData>();
505
1.13k
  if (AMap.isEmpty())
506
1.06k
    return State;
507
72
508
72
  auto *CondBSE = dyn_cast_or_null<BinarySymExpr>(Cond.getAsSymExpr());
509
72
  if (!CondBSE)
510
22
    return State;
511
50
  BinaryOperator::Opcode OpCode = CondBSE->getOpcode();
512
50
  if (OpCode != BO_EQ && 
OpCode != BO_NE6
)
513
0
    return State;
514
50
515
50
  // Match for a restricted set of patterns for cmparison of error codes.
516
50
  // Note, the comparisons of type '0 == st' are transformed into SymIntExpr.
517
50
  SymbolRef ReturnSymbol = nullptr;
518
50
  if (auto *SIE = dyn_cast<SymIntExpr>(CondBSE)) {
519
50
    const llvm::APInt &RHS = SIE->getRHS();
520
50
    bool ErrorIsReturned = (OpCode == BO_EQ && 
RHS != NoErr44
) ||
521
50
                           
(44
OpCode == BO_NE44
&&
RHS == NoErr6
);
522
50
    if (!Assumption)
523
25
      ErrorIsReturned = !ErrorIsReturned;
524
50
    if (ErrorIsReturned)
525
25
      ReturnSymbol = SIE->getLHS();
526
50
  }
527
50
528
50
  if (ReturnSymbol)
529
51
    
for (auto I = AMap.begin(), E = AMap.end(); 25
I != E;
++I26
) {
530
26
      if (ReturnSymbol == I->second.Region)
531
20
        State = State->remove<AllocatedData>(I->first);
532
26
    }
533
50
534
50
  return State;
535
50
}
536
537
void MacOSKeychainAPIChecker::checkDeadSymbols(SymbolReaper &SR,
538
1.52k
                                               CheckerContext &C) const {
539
1.52k
  ProgramStateRef State = C.getState();
540
1.52k
  AllocatedDataTy AMap = State->get<AllocatedData>();
541
1.52k
  if (AMap.isEmpty())
542
1.40k
    return;
543
116
544
116
  bool Changed = false;
545
116
  AllocationPairVec Errors;
546
235
  for (auto I = AMap.begin(), E = AMap.end(); I != E; 
++I119
) {
547
119
    if (!SR.isDead(I->first))
548
106
      continue;
549
13
550
13
    Changed = true;
551
13
    State = State->remove<AllocatedData>(I->first);
552
13
    // If the allocated symbol is null do not report.
553
13
    ConstraintManager &CMgr = State->getConstraintManager();
554
13
    ConditionTruthVal AllocFailed = CMgr.isNull(State, I.getKey());
555
13
    if (AllocFailed.isConstrainedTrue())
556
4
      continue;
557
9
    Errors.push_back(std::make_pair(I->first, &I->second));
558
9
  }
559
116
  if (!Changed) {
560
103
    // Generate the new, cleaned up state.
561
103
    C.addTransition(State);
562
103
    return;
563
103
  }
564
13
565
13
  static CheckerProgramPointTag Tag(this, "DeadSymbolsLeak");
566
13
  ExplodedNode *N = C.generateNonFatalErrorNode(C.getState(), &Tag);
567
13
  if (!N)
568
0
    return;
569
13
570
13
  // Generate the error reports.
571
13
  for (const auto &P : Errors)
572
9
    C.emitReport(generateAllocatedDataNotReleasedReport(P, N, C));
573
13
574
13
  // Generate the new, cleaned up state.
575
13
  C.addTransition(State, N);
576
13
}
577
578
ProgramStateRef MacOSKeychainAPIChecker::checkPointerEscape(
579
    ProgramStateRef State, const InvalidatedSymbols &Escaped,
580
227
    const CallEvent *Call, PointerEscapeKind Kind) const {
581
227
  // FIXME: This branch doesn't make any sense at all, but it is an overfitted
582
227
  // replacement for a previous overfitted code that was making even less sense.
583
227
  if (!Call || 
Call->getDecl()202
)
584
222
    return State;
585
5
586
5
  for (auto I : State->get<AllocatedData>()) {
587
2
    SymbolRef Sym = I.first;
588
2
    if (Escaped.count(Sym))
589
0
      State = State->remove<AllocatedData>(Sym);
590
2
591
2
    // This checker is special. Most checkers in fact only track symbols of
592
2
    // SymbolConjured type, eg. symbols returned from functions such as
593
2
    // malloc(). This checker tracks symbols returned as out-parameters.
594
2
    //
595
2
    // When a function is evaluated conservatively, the out-parameter's pointee
596
2
    // base region gets invalidated with a SymbolConjured. If the base region is
597
2
    // larger than the region we're interested in, the value we're interested in
598
2
    // would be SymbolDerived based on that SymbolConjured. However, such
599
2
    // SymbolDerived will never be listed in the Escaped set when the base
600
2
    // region is invalidated because ExprEngine doesn't know which symbols
601
2
    // were derived from a given symbol, while there can be infinitely many
602
2
    // valid symbols derived from any given symbol.
603
2
    //
604
2
    // Hence the extra boilerplate: remove the derived symbol when its parent
605
2
    // symbol escapes.
606
2
    //
607
2
    if (const auto *SD = dyn_cast<SymbolDerived>(Sym)) {
608
2
      SymbolRef ParentSym = SD->getParentSymbol();
609
2
      if (Escaped.count(ParentSym))
610
2
        State = State->remove<AllocatedData>(Sym);
611
2
    }
612
2
  }
613
5
  return State;
614
5
}
615
616
std::shared_ptr<PathDiagnosticPiece>
617
MacOSKeychainAPIChecker::SecKeychainBugVisitor::VisitNode(
618
1.06k
    const ExplodedNode *N, BugReporterContext &BRC, BugReport &BR) {
619
1.06k
  const AllocationState *AS = N->getState()->get<AllocatedData>(Sym);
620
1.06k
  if (!AS)
621
657
    return nullptr;
622
412
  const AllocationState *ASPrev =
623
412
      N->getFirstPred()->getState()->get<AllocatedData>(Sym);
624
412
  if (ASPrev)
625
399
    return nullptr;
626
13
627
13
  // (!ASPrev && AS) ~ We started tracking symbol in node N, it must be the
628
13
  // allocation site.
629
13
  const CallExpr *CE =
630
13
      cast<CallExpr>(N->getLocation().castAs<StmtPoint>().getStmt());
631
13
  const FunctionDecl *funDecl = CE->getDirectCallee();
632
13
  assert(funDecl && "We do not support indirect function calls as of now.");
633
13
  StringRef funName = funDecl->getName();
634
13
635
13
  // Get the expression of the corresponding argument.
636
13
  unsigned Idx = getTrackedFunctionIndex(funName, true);
637
13
  assert(Idx != InvalidIdx && "This should be a call to an allocator.");
638
13
  const Expr *ArgExpr = CE->getArg(FunctionsToTrack[Idx].Param);
639
13
  PathDiagnosticLocation Pos(ArgExpr, BRC.getSourceManager(),
640
13
                             N->getLocationContext());
641
13
  return std::make_shared<PathDiagnosticEventPiece>(Pos,
642
13
                                                    "Data is allocated here.");
643
13
}
644
645
void MacOSKeychainAPIChecker::printState(raw_ostream &Out,
646
                                         ProgramStateRef State,
647
                                         const char *NL,
648
0
                                         const char *Sep) const {
649
0
650
0
  AllocatedDataTy AMap = State->get<AllocatedData>();
651
0
652
0
  if (!AMap.isEmpty()) {
653
0
    Out << Sep << "KeychainAPIChecker :" << NL;
654
0
    for (auto I = AMap.begin(), E = AMap.end(); I != E; ++I) {
655
0
      I.getKey()->dumpToStream(Out);
656
0
    }
657
0
  }
658
0
}
659
660
661
25
void ento::registerMacOSKeychainAPIChecker(CheckerManager &mgr) {
662
25
  mgr.registerChecker<MacOSKeychainAPIChecker>();
663
25
}
664
665
25
bool ento::shouldRegisterMacOSKeychainAPIChecker(const LangOptions &LO) {
666
25
  return true;
667
25
}