Coverage Report

Created: 2022-01-18 06:27

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
Line
Count
Source (jump to first uncovered line)
1
//=== MallocChecker.cpp - A malloc/free 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 a variety of memory management related checkers, such as
10
// leak, double free, and use-after-free.
11
//
12
// The following checkers are defined here:
13
//
14
//   * MallocChecker
15
//       Despite its name, it models all sorts of memory allocations and
16
//       de- or reallocation, including but not limited to malloc, free,
17
//       relloc, new, delete. It also reports on a variety of memory misuse
18
//       errors.
19
//       Many other checkers interact very closely with this checker, in fact,
20
//       most are merely options to this one. Other checkers may register
21
//       MallocChecker, but do not enable MallocChecker's reports (more details
22
//       to follow around its field, ChecksEnabled).
23
//       It also has a boolean "Optimistic" checker option, which if set to true
24
//       will cause the checker to model user defined memory management related
25
//       functions annotated via the attribute ownership_takes, ownership_holds
26
//       and ownership_returns.
27
//
28
//   * NewDeleteChecker
29
//       Enables the modeling of new, new[], delete, delete[] in MallocChecker,
30
//       and checks for related double-free and use-after-free errors.
31
//
32
//   * NewDeleteLeaksChecker
33
//       Checks for leaks related to new, new[], delete, delete[].
34
//       Depends on NewDeleteChecker.
35
//
36
//   * MismatchedDeallocatorChecker
37
//       Enables checking whether memory is deallocated with the correspending
38
//       allocation function in MallocChecker, such as malloc() allocated
39
//       regions are only freed by free(), new by delete, new[] by delete[].
40
//
41
//  InnerPointerChecker interacts very closely with MallocChecker, but unlike
42
//  the above checkers, it has it's own file, hence the many InnerPointerChecker
43
//  related headers and non-static functions.
44
//
45
//===----------------------------------------------------------------------===//
46
47
#include "AllocationState.h"
48
#include "InterCheckerAPI.h"
49
#include "clang/AST/Attr.h"
50
#include "clang/AST/DeclCXX.h"
51
#include "clang/AST/DeclTemplate.h"
52
#include "clang/AST/Expr.h"
53
#include "clang/AST/ExprCXX.h"
54
#include "clang/AST/ParentMap.h"
55
#include "clang/ASTMatchers/ASTMatchFinder.h"
56
#include "clang/ASTMatchers/ASTMatchers.h"
57
#include "clang/Analysis/ProgramPoint.h"
58
#include "clang/Basic/LLVM.h"
59
#include "clang/Basic/SourceManager.h"
60
#include "clang/Basic/TargetInfo.h"
61
#include "clang/Lex/Lexer.h"
62
#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
63
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
64
#include "clang/StaticAnalyzer/Core/BugReporter/CommonBugCategories.h"
65
#include "clang/StaticAnalyzer/Core/Checker.h"
66
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
67
#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
68
#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
69
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
70
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
71
#include "clang/StaticAnalyzer/Core/PathSensitive/DynamicExtent.h"
72
#include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
73
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
74
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
75
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
76
#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
77
#include "clang/StaticAnalyzer/Core/PathSensitive/StoreRef.h"
78
#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
79
#include "llvm/ADT/STLExtras.h"
80
#include "llvm/ADT/SetOperations.h"
81
#include "llvm/ADT/SmallString.h"
82
#include "llvm/ADT/StringExtras.h"
83
#include "llvm/Support/Casting.h"
84
#include "llvm/Support/Compiler.h"
85
#include "llvm/Support/ErrorHandling.h"
86
#include "llvm/Support/raw_ostream.h"
87
#include <climits>
88
#include <functional>
89
#include <utility>
90
91
using namespace clang;
92
using namespace ento;
93
using namespace std::placeholders;
94
95
//===----------------------------------------------------------------------===//
96
// The types of allocation we're modeling. This is used to check whether a
97
// dynamically allocated object is deallocated with the correct function, like
98
// not using operator delete on an object created by malloc(), or alloca regions
99
// aren't ever deallocated manually.
100
//===----------------------------------------------------------------------===//
101
102
namespace {
103
104
// Used to check correspondence between allocators and deallocators.
105
enum AllocationFamily {
106
  AF_None,
107
  AF_Malloc,
108
  AF_CXXNew,
109
  AF_CXXNewArray,
110
  AF_IfNameIndex,
111
  AF_Alloca,
112
  AF_InnerBuffer
113
};
114
115
} // end of anonymous namespace
116
117
/// Print names of allocators and deallocators.
118
///
119
/// \returns true on success.
120
static bool printMemFnName(raw_ostream &os, CheckerContext &C, const Expr *E);
121
122
/// Print expected name of an allocator based on the deallocator's family
123
/// derived from the DeallocExpr.
124
static void printExpectedAllocName(raw_ostream &os, AllocationFamily Family);
125
126
/// Print expected name of a deallocator based on the allocator's
127
/// family.
128
static void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family);
129
130
//===----------------------------------------------------------------------===//
131
// The state of a symbol, in terms of memory management.
132
//===----------------------------------------------------------------------===//
133
134
namespace {
135
136
class RefState {
137
  enum Kind {
138
    // Reference to allocated memory.
139
    Allocated,
140
    // Reference to zero-allocated memory.
141
    AllocatedOfSizeZero,
142
    // Reference to released/freed memory.
143
    Released,
144
    // The responsibility for freeing resources has transferred from
145
    // this reference. A relinquished symbol should not be freed.
146
    Relinquished,
147
    // We are no longer guaranteed to have observed all manipulations
148
    // of this pointer/memory. For example, it could have been
149
    // passed as a parameter to an opaque function.
150
    Escaped
151
  };
152
153
  const Stmt *S;
154
155
  Kind K;
156
  AllocationFamily Family;
157
158
  RefState(Kind k, const Stmt *s, AllocationFamily family)
159
2.75k
      : S(s), K(k), Family(family) {
160
2.75k
    assert(family != AF_None);
161
2.75k
  }
162
163
public:
164
27.8k
  bool isAllocated() const { return K == Allocated; }
165
5.24k
  bool isAllocatedOfSizeZero() const { return K == AllocatedOfSizeZero; }
166
17.9k
  bool isReleased() const { return K == Released; }
167
1.72k
  bool isRelinquished() const { return K == Relinquished; }
168
108
  bool isEscaped() const { return K == Escaped; }
169
4.30k
  AllocationFamily getAllocationFamily() const { return Family; }
170
668
  const Stmt *getStmt() const { return S; }
171
172
609
  bool operator==(const RefState &X) const {
173
609
    return K == X.K && S == X.S && Family == X.Family;
174
609
  }
175
176
1.47k
  static RefState getAllocated(AllocationFamily family, const Stmt *s) {
177
1.47k
    return RefState(Allocated, s, family);
178
1.47k
  }
179
80
  static RefState getAllocatedOfSizeZero(const RefState *RS) {
180
80
    return RefState(AllocatedOfSizeZero, RS->getStmt(),
181
80
                    RS->getAllocationFamily());
182
80
  }
183
757
  static RefState getReleased(AllocationFamily family, const Stmt *s) {
184
757
    return RefState(Released, s, family);
185
757
  }
186
27
  static RefState getRelinquished(AllocationFamily family, const Stmt *s) {
187
27
    return RefState(Relinquished, s, family);
188
27
  }
189
420
  static RefState getEscaped(const RefState *RS) {
190
420
    return RefState(Escaped, RS->getStmt(), RS->getAllocationFamily());
191
420
  }
192
193
3.77k
  void Profile(llvm::FoldingSetNodeID &ID) const {
194
3.77k
    ID.AddInteger(K);
195
3.77k
    ID.AddPointer(S);
196
3.77k
    ID.AddInteger(Family);
197
3.77k
  }
198
199
0
  LLVM_DUMP_METHOD void dump(raw_ostream &OS) const {
200
0
    switch (K) {
201
0
#define CASE(ID) case ID: OS << #ID; break;
202
0
    CASE(Allocated)
203
0
    CASE(AllocatedOfSizeZero)
204
0
    CASE(Released)
205
0
    CASE(Relinquished)
206
0
    CASE(Escaped)
207
0
    }
208
0
  }
209
210
0
  LLVM_DUMP_METHOD void dump() const { dump(llvm::errs()); }
211
};
212
213
} // end of anonymous namespace
214
215
REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
216
217
/// Check if the memory associated with this symbol was released.
218
static bool isReleased(SymbolRef Sym, CheckerContext &C);
219
220
/// Update the RefState to reflect the new memory allocation.
221
/// The optional \p RetVal parameter specifies the newly allocated pointer
222
/// value; if unspecified, the value of expression \p E is used.
223
static ProgramStateRef MallocUpdateRefState(CheckerContext &C, const Expr *E,
224
                                            ProgramStateRef State,
225
                                            AllocationFamily Family,
226
                                            Optional<SVal> RetVal = None);
227
228
//===----------------------------------------------------------------------===//
229
// The modeling of memory reallocation.
230
//
231
// The terminology 'toPtr' and 'fromPtr' will be used:
232
//   toPtr = realloc(fromPtr, 20);
233
//===----------------------------------------------------------------------===//
234
235
REGISTER_SET_WITH_PROGRAMSTATE(ReallocSizeZeroSymbols, SymbolRef)
236
237
namespace {
238
239
/// The state of 'fromPtr' after reallocation is known to have failed.
240
enum OwnershipAfterReallocKind {
241
  // The symbol needs to be freed (e.g.: realloc)
242
  OAR_ToBeFreedAfterFailure,
243
  // The symbol has been freed (e.g.: reallocf)
244
  OAR_FreeOnFailure,
245
  // The symbol doesn't have to freed (e.g.: we aren't sure if, how and where
246
  // 'fromPtr' was allocated:
247
  //    void Haha(int *ptr) {
248
  //      ptr = realloc(ptr, 67);
249
  //      // ...
250
  //    }
251
  // ).
252
  OAR_DoNotTrackAfterFailure
253
};
254
255
/// Stores information about the 'fromPtr' symbol after reallocation.
256
///
257
/// This is important because realloc may fail, and that needs special modeling.
258
/// Whether reallocation failed or not will not be known until later, so we'll
259
/// store whether upon failure 'fromPtr' will be freed, or needs to be freed
260
/// later, etc.
261
struct ReallocPair {
262
263
  // The 'fromPtr'.
264
  SymbolRef ReallocatedSym;
265
  OwnershipAfterReallocKind Kind;
266
267
  ReallocPair(SymbolRef S, OwnershipAfterReallocKind K)
268
56
      : ReallocatedSym(S), Kind(K) {}
269
114
  void Profile(llvm::FoldingSetNodeID &ID) const {
270
114
    ID.AddInteger(Kind);
271
114
    ID.AddPointer(ReallocatedSym);
272
114
  }
273
24
  bool operator==(const ReallocPair &X) const {
274
24
    return ReallocatedSym == X.ReallocatedSym &&
275
24
           Kind == X.Kind;
276
24
  }
277
};
278
279
} // end of anonymous namespace
280
281
REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
282
283
/// Tells if the callee is one of the builtin new/delete operators, including
284
/// placement operators and other standard overloads.
285
static bool isStandardNewDelete(const FunctionDecl *FD);
286
30.3k
static bool isStandardNewDelete(const CallEvent &Call) {
287
30.3k
  if (!Call.getDecl() || 
!isa<FunctionDecl>(Call.getDecl())30.3k
)
288
105
    return false;
289
30.2k
  return isStandardNewDelete(cast<FunctionDecl>(Call.getDecl()));
290
30.3k
}
291
292
//===----------------------------------------------------------------------===//
293
// Definition of the MallocChecker class.
294
//===----------------------------------------------------------------------===//
295
296
namespace {
297
298
class MallocChecker
299
    : public Checker<check::DeadSymbols, check::PointerEscape,
300
                     check::ConstPointerEscape, check::PreStmt<ReturnStmt>,
301
                     check::EndFunction, check::PreCall, check::PostCall,
302
                     check::NewAllocator, check::PostStmt<BlockExpr>,
303
                     check::PostObjCMessage, check::Location, eval::Assume> {
304
public:
305
  /// In pessimistic mode, the checker assumes that it does not know which
306
  /// functions might free the memory.
307
  /// In optimistic mode, the checker assumes that all user-defined functions
308
  /// which might free a pointer are annotated.
309
  DefaultBool ShouldIncludeOwnershipAnnotatedFunctions;
310
311
  DefaultBool ShouldRegisterNoOwnershipChangeVisitor;
312
313
  /// Many checkers are essentially built into this one, so enabling them will
314
  /// make MallocChecker perform additional modeling and reporting.
315
  enum CheckKind {
316
    /// When a subchecker is enabled but MallocChecker isn't, model memory
317
    /// management but do not emit warnings emitted with MallocChecker only
318
    /// enabled.
319
    CK_MallocChecker,
320
    CK_NewDeleteChecker,
321
    CK_NewDeleteLeaksChecker,
322
    CK_MismatchedDeallocatorChecker,
323
    CK_InnerPointerChecker,
324
    CK_NumCheckKinds
325
  };
326
327
  using LeakInfo = std::pair<const ExplodedNode *, const MemRegion *>;
328
329
  DefaultBool ChecksEnabled[CK_NumCheckKinds];
330
  CheckerNameRef CheckNames[CK_NumCheckKinds];
331
332
  void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
333
  void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
334
  void checkNewAllocator(const CXXAllocatorCall &Call, CheckerContext &C) const;
335
  void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
336
  void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
337
  void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
338
  void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
339
  void checkEndFunction(const ReturnStmt *S, CheckerContext &C) const;
340
  ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
341
                            bool Assumption) const;
342
  void checkLocation(SVal l, bool isLoad, const Stmt *S,
343
                     CheckerContext &C) const;
344
345
  ProgramStateRef checkPointerEscape(ProgramStateRef State,
346
                                    const InvalidatedSymbols &Escaped,
347
                                    const CallEvent *Call,
348
                                    PointerEscapeKind Kind) const;
349
  ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
350
                                          const InvalidatedSymbols &Escaped,
351
                                          const CallEvent *Call,
352
                                          PointerEscapeKind Kind) const;
353
354
  void printState(raw_ostream &Out, ProgramStateRef State,
355
                  const char *NL, const char *Sep) const override;
356
357
private:
358
  mutable std::unique_ptr<BugType> BT_DoubleFree[CK_NumCheckKinds];
359
  mutable std::unique_ptr<BugType> BT_DoubleDelete;
360
  mutable std::unique_ptr<BugType> BT_Leak[CK_NumCheckKinds];
361
  mutable std::unique_ptr<BugType> BT_UseFree[CK_NumCheckKinds];
362
  mutable std::unique_ptr<BugType> BT_BadFree[CK_NumCheckKinds];
363
  mutable std::unique_ptr<BugType> BT_FreeAlloca[CK_NumCheckKinds];
364
  mutable std::unique_ptr<BugType> BT_MismatchedDealloc;
365
  mutable std::unique_ptr<BugType> BT_OffsetFree[CK_NumCheckKinds];
366
  mutable std::unique_ptr<BugType> BT_UseZerroAllocated[CK_NumCheckKinds];
367
368
#define CHECK_FN(NAME)                                                         \
369
  void NAME(const CallEvent &Call, CheckerContext &C) const;
370
371
  CHECK_FN(checkFree)
372
  CHECK_FN(checkIfNameIndex)
373
  CHECK_FN(checkBasicAlloc)
374
  CHECK_FN(checkKernelMalloc)
375
  CHECK_FN(checkCalloc)
376
  CHECK_FN(checkAlloca)
377
  CHECK_FN(checkStrdup)
378
  CHECK_FN(checkIfFreeNameIndex)
379
  CHECK_FN(checkCXXNewOrCXXDelete)
380
  CHECK_FN(checkGMalloc0)
381
  CHECK_FN(checkGMemdup)
382
  CHECK_FN(checkGMallocN)
383
  CHECK_FN(checkGMallocN0)
384
  CHECK_FN(checkReallocN)
385
  CHECK_FN(checkOwnershipAttr)
386
387
  void checkRealloc(const CallEvent &Call, CheckerContext &C,
388
                    bool ShouldFreeOnFail) const;
389
390
  using CheckFn = std::function<void(const MallocChecker *,
391
                                     const CallEvent &Call, CheckerContext &C)>;
392
393
  const CallDescriptionMap<CheckFn> FreeingMemFnMap{
394
      {{"free", 1}, &MallocChecker::checkFree},
395
      {{"if_freenameindex", 1}, &MallocChecker::checkIfFreeNameIndex},
396
      {{"kfree", 1}, &MallocChecker::checkFree},
397
      {{"g_free", 1}, &MallocChecker::checkFree},
398
  };
399
400
  bool isFreeingCall(const CallEvent &Call) const;
401
402
  CallDescriptionMap<CheckFn> AllocatingMemFnMap{
403
      {{"alloca", 1}, &MallocChecker::checkAlloca},
404
      {{"_alloca", 1}, &MallocChecker::checkAlloca},
405
      {{"malloc", 1}, &MallocChecker::checkBasicAlloc},
406
      {{"malloc", 3}, &MallocChecker::checkKernelMalloc},
407
      {{"calloc", 2}, &MallocChecker::checkCalloc},
408
      {{"valloc", 1}, &MallocChecker::checkBasicAlloc},
409
      {{CDF_MaybeBuiltin, "strndup", 2}, &MallocChecker::checkStrdup},
410
      {{CDF_MaybeBuiltin, "strdup", 1}, &MallocChecker::checkStrdup},
411
      {{"_strdup", 1}, &MallocChecker::checkStrdup},
412
      {{"kmalloc", 2}, &MallocChecker::checkKernelMalloc},
413
      {{"if_nameindex", 1}, &MallocChecker::checkIfNameIndex},
414
      {{CDF_MaybeBuiltin, "wcsdup", 1}, &MallocChecker::checkStrdup},
415
      {{CDF_MaybeBuiltin, "_wcsdup", 1}, &MallocChecker::checkStrdup},
416
      {{"g_malloc", 1}, &MallocChecker::checkBasicAlloc},
417
      {{"g_malloc0", 1}, &MallocChecker::checkGMalloc0},
418
      {{"g_try_malloc", 1}, &MallocChecker::checkBasicAlloc},
419
      {{"g_try_malloc0", 1}, &MallocChecker::checkGMalloc0},
420
      {{"g_memdup", 2}, &MallocChecker::checkGMemdup},
421
      {{"g_malloc_n", 2}, &MallocChecker::checkGMallocN},
422
      {{"g_malloc0_n", 2}, &MallocChecker::checkGMallocN0},
423
      {{"g_try_malloc_n", 2}, &MallocChecker::checkGMallocN},
424
      {{"g_try_malloc0_n", 2}, &MallocChecker::checkGMallocN0},
425
  };
426
427
  CallDescriptionMap<CheckFn> ReallocatingMemFnMap{
428
      {{"realloc", 2},
429
       std::bind(&MallocChecker::checkRealloc, _1, _2, _3, false)},
430
      {{"reallocf", 2},
431
       std::bind(&MallocChecker::checkRealloc, _1, _2, _3, true)},
432
      {{"g_realloc", 2},
433
       std::bind(&MallocChecker::checkRealloc, _1, _2, _3, false)},
434
      {{"g_try_realloc", 2},
435
       std::bind(&MallocChecker::checkRealloc, _1, _2, _3, false)},
436
      {{"g_realloc_n", 3}, &MallocChecker::checkReallocN},
437
      {{"g_try_realloc_n", 3}, &MallocChecker::checkReallocN},
438
  };
439
440
  bool isMemCall(const CallEvent &Call) const;
441
442
  // TODO: Remove mutable by moving the initializtaion to the registry function.
443
  mutable Optional<uint64_t> KernelZeroFlagVal;
444
445
  using KernelZeroSizePtrValueTy = Optional<int>;
446
  /// Store the value of macro called `ZERO_SIZE_PTR`.
447
  /// The value is initialized at first use, before first use the outer
448
  /// Optional is empty, afterwards it contains another Optional that indicates
449
  /// if the macro value could be determined, and if yes the value itself.
450
  mutable Optional<KernelZeroSizePtrValueTy> KernelZeroSizePtrValue;
451
452
  /// Process C++ operator new()'s allocation, which is the part of C++
453
  /// new-expression that goes before the constructor.
454
  LLVM_NODISCARD
455
  ProgramStateRef processNewAllocation(const CXXAllocatorCall &Call,
456
                                       CheckerContext &C,
457
                                       AllocationFamily Family) const;
458
459
  /// Perform a zero-allocation check.
460
  ///
461
  /// \param [in] Call The expression that allocates memory.
462
  /// \param [in] IndexOfSizeArg Index of the argument that specifies the size
463
  ///   of the memory that needs to be allocated. E.g. for malloc, this would be
464
  ///   0.
465
  /// \param [in] RetVal Specifies the newly allocated pointer value;
466
  ///   if unspecified, the value of expression \p E is used.
467
  LLVM_NODISCARD
468
  static ProgramStateRef ProcessZeroAllocCheck(const CallEvent &Call,
469
                                               const unsigned IndexOfSizeArg,
470
                                               ProgramStateRef State,
471
                                               Optional<SVal> RetVal = None);
472
473
  /// Model functions with the ownership_returns attribute.
474
  ///
475
  /// User-defined function may have the ownership_returns attribute, which
476
  /// annotates that the function returns with an object that was allocated on
477
  /// the heap, and passes the ownertship to the callee.
478
  ///
479
  ///   void __attribute((ownership_returns(malloc, 1))) *my_malloc(size_t);
480
  ///
481
  /// It has two parameters:
482
  ///   - first: name of the resource (e.g. 'malloc')
483
  ///   - (OPTIONAL) second: size of the allocated region
484
  ///
485
  /// \param [in] Call The expression that allocates memory.
486
  /// \param [in] Att The ownership_returns attribute.
487
  /// \param [in] State The \c ProgramState right before allocation.
488
  /// \returns The ProgramState right after allocation.
489
  LLVM_NODISCARD
490
  ProgramStateRef MallocMemReturnsAttr(CheckerContext &C, const CallEvent &Call,
491
                                       const OwnershipAttr *Att,
492
                                       ProgramStateRef State) const;
493
494
  /// Models memory allocation.
495
  ///
496
  /// \param [in] Call The expression that allocates memory.
497
  /// \param [in] SizeEx Size of the memory that needs to be allocated.
498
  /// \param [in] Init The value the allocated memory needs to be initialized.
499
  /// with. For example, \c calloc initializes the allocated memory to 0,
500
  /// malloc leaves it undefined.
501
  /// \param [in] State The \c ProgramState right before allocation.
502
  /// \returns The ProgramState right after allocation.
503
  LLVM_NODISCARD
504
  static ProgramStateRef MallocMemAux(CheckerContext &C, const CallEvent &Call,
505
                                      const Expr *SizeEx, SVal Init,
506
                                      ProgramStateRef State,
507
                                      AllocationFamily Family);
508
509
  /// Models memory allocation.
510
  ///
511
  /// \param [in] Call The expression that allocates memory.
512
  /// \param [in] Size Size of the memory that needs to be allocated.
513
  /// \param [in] Init The value the allocated memory needs to be initialized.
514
  /// with. For example, \c calloc initializes the allocated memory to 0,
515
  /// malloc leaves it undefined.
516
  /// \param [in] State The \c ProgramState right before allocation.
517
  /// \returns The ProgramState right after allocation.
518
  LLVM_NODISCARD
519
  static ProgramStateRef MallocMemAux(CheckerContext &C, const CallEvent &Call,
520
                                      SVal Size, SVal Init,
521
                                      ProgramStateRef State,
522
                                      AllocationFamily Family);
523
524
  // Check if this malloc() for special flags. At present that means M_ZERO or
525
  // __GFP_ZERO (in which case, treat it like calloc).
526
  LLVM_NODISCARD
527
  llvm::Optional<ProgramStateRef>
528
  performKernelMalloc(const CallEvent &Call, CheckerContext &C,
529
                      const ProgramStateRef &State) const;
530
531
  /// Model functions with the ownership_takes and ownership_holds attributes.
532
  ///
533
  /// User-defined function may have the ownership_takes and/or ownership_holds
534
  /// attributes, which annotates that the function frees the memory passed as a
535
  /// parameter.
536
  ///
537
  ///   void __attribute((ownership_takes(malloc, 1))) my_free(void *);
538
  ///   void __attribute((ownership_holds(malloc, 1))) my_hold(void *);
539
  ///
540
  /// They have two parameters:
541
  ///   - first: name of the resource (e.g. 'malloc')
542
  ///   - second: index of the parameter the attribute applies to
543
  ///
544
  /// \param [in] Call The expression that frees memory.
545
  /// \param [in] Att The ownership_takes or ownership_holds attribute.
546
  /// \param [in] State The \c ProgramState right before allocation.
547
  /// \returns The ProgramState right after deallocation.
548
  LLVM_NODISCARD
549
  ProgramStateRef FreeMemAttr(CheckerContext &C, const CallEvent &Call,
550
                              const OwnershipAttr *Att,
551
                              ProgramStateRef State) const;
552
553
  /// Models memory deallocation.
554
  ///
555
  /// \param [in] Call The expression that frees memory.
556
  /// \param [in] State The \c ProgramState right before allocation.
557
  /// \param [in] Num Index of the argument that needs to be freed. This is
558
  ///   normally 0, but for custom free functions it may be different.
559
  /// \param [in] Hold Whether the parameter at \p Index has the ownership_holds
560
  ///   attribute.
561
  /// \param [out] IsKnownToBeAllocated Whether the memory to be freed is known
562
  ///   to have been allocated, or in other words, the symbol to be freed was
563
  ///   registered as allocated by this checker. In the following case, \c ptr
564
  ///   isn't known to be allocated.
565
  ///      void Haha(int *ptr) {
566
  ///        ptr = realloc(ptr, 67);
567
  ///        // ...
568
  ///      }
569
  /// \param [in] ReturnsNullOnFailure Whether the memory deallocation function
570
  ///   we're modeling returns with Null on failure.
571
  /// \returns The ProgramState right after deallocation.
572
  LLVM_NODISCARD
573
  ProgramStateRef FreeMemAux(CheckerContext &C, const CallEvent &Call,
574
                             ProgramStateRef State, unsigned Num, bool Hold,
575
                             bool &IsKnownToBeAllocated,
576
                             AllocationFamily Family,
577
                             bool ReturnsNullOnFailure = false) const;
578
579
  /// Models memory deallocation.
580
  ///
581
  /// \param [in] ArgExpr The variable who's pointee needs to be freed.
582
  /// \param [in] Call The expression that frees the memory.
583
  /// \param [in] State The \c ProgramState right before allocation.
584
  ///   normally 0, but for custom free functions it may be different.
585
  /// \param [in] Hold Whether the parameter at \p Index has the ownership_holds
586
  ///   attribute.
587
  /// \param [out] IsKnownToBeAllocated Whether the memory to be freed is known
588
  ///   to have been allocated, or in other words, the symbol to be freed was
589
  ///   registered as allocated by this checker. In the following case, \c ptr
590
  ///   isn't known to be allocated.
591
  ///      void Haha(int *ptr) {
592
  ///        ptr = realloc(ptr, 67);
593
  ///        // ...
594
  ///      }
595
  /// \param [in] ReturnsNullOnFailure Whether the memory deallocation function
596
  ///   we're modeling returns with Null on failure.
597
  /// \returns The ProgramState right after deallocation.
598
  LLVM_NODISCARD
599
  ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *ArgExpr,
600
                             const CallEvent &Call, ProgramStateRef State,
601
                             bool Hold, bool &IsKnownToBeAllocated,
602
                             AllocationFamily Family,
603
                             bool ReturnsNullOnFailure = false) const;
604
605
  // TODO: Needs some refactoring, as all other deallocation modeling
606
  // functions are suffering from out parameters and messy code due to how
607
  // realloc is handled.
608
  //
609
  /// Models memory reallocation.
610
  ///
611
  /// \param [in] Call The expression that reallocated memory
612
  /// \param [in] ShouldFreeOnFail Whether if reallocation fails, the supplied
613
  ///   memory should be freed.
614
  /// \param [in] State The \c ProgramState right before reallocation.
615
  /// \param [in] SuffixWithN Whether the reallocation function we're modeling
616
  ///   has an '_n' suffix, such as g_realloc_n.
617
  /// \returns The ProgramState right after reallocation.
618
  LLVM_NODISCARD
619
  ProgramStateRef ReallocMemAux(CheckerContext &C, const CallEvent &Call,
620
                                bool ShouldFreeOnFail, ProgramStateRef State,
621
                                AllocationFamily Family,
622
                                bool SuffixWithN = false) const;
623
624
  /// Evaluates the buffer size that needs to be allocated.
625
  ///
626
  /// \param [in] Blocks The amount of blocks that needs to be allocated.
627
  /// \param [in] BlockBytes The size of a block.
628
  /// \returns The symbolic value of \p Blocks * \p BlockBytes.
629
  LLVM_NODISCARD
630
  static SVal evalMulForBufferSize(CheckerContext &C, const Expr *Blocks,
631
                                   const Expr *BlockBytes);
632
633
  /// Models zero initialized array allocation.
634
  ///
635
  /// \param [in] Call The expression that reallocated memory
636
  /// \param [in] State The \c ProgramState right before reallocation.
637
  /// \returns The ProgramState right after allocation.
638
  LLVM_NODISCARD
639
  static ProgramStateRef CallocMem(CheckerContext &C, const CallEvent &Call,
640
                                   ProgramStateRef State);
641
642
  /// See if deallocation happens in a suspicious context. If so, escape the
643
  /// pointers that otherwise would have been deallocated and return true.
644
  bool suppressDeallocationsInSuspiciousContexts(const CallEvent &Call,
645
                                                 CheckerContext &C) const;
646
647
  /// If in \p S  \p Sym is used, check whether \p Sym was already freed.
648
  bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
649
650
  /// If in \p S \p Sym is used, check whether \p Sym was allocated as a zero
651
  /// sized memory region.
652
  void checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
653
                             const Stmt *S) const;
654
655
  /// If in \p S \p Sym is being freed, check whether \p Sym was already freed.
656
  bool checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const;
657
658
  /// Check if the function is known to free memory, or if it is
659
  /// "interesting" and should be modeled explicitly.
660
  ///
661
  /// \param [out] EscapingSymbol A function might not free memory in general,
662
  ///   but could be known to free a particular symbol. In this case, false is
663
  ///   returned and the single escaping symbol is returned through the out
664
  ///   parameter.
665
  ///
666
  /// We assume that pointers do not escape through calls to system functions
667
  /// not handled by this checker.
668
  bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent *Call,
669
                                   ProgramStateRef State,
670
                                   SymbolRef &EscapingSymbol) const;
671
672
  /// Implementation of the checkPointerEscape callbacks.
673
  LLVM_NODISCARD
674
  ProgramStateRef checkPointerEscapeAux(ProgramStateRef State,
675
                                        const InvalidatedSymbols &Escaped,
676
                                        const CallEvent *Call,
677
                                        PointerEscapeKind Kind,
678
                                        bool IsConstPointerEscape) const;
679
680
  // Implementation of the checkPreStmt and checkEndFunction callbacks.
681
  void checkEscapeOnReturn(const ReturnStmt *S, CheckerContext &C) const;
682
683
  ///@{
684
  /// Tells if a given family/call/symbol is tracked by the current checker.
685
  /// Sets CheckKind to the kind of the checker responsible for this
686
  /// family/call/symbol.
687
  Optional<CheckKind> getCheckIfTracked(AllocationFamily Family,
688
                                        bool IsALeakCheck = false) const;
689
690
  Optional<CheckKind> getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
691
                                        bool IsALeakCheck = false) const;
692
  ///@}
693
  static bool SummarizeValue(raw_ostream &os, SVal V);
694
  static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
695
696
  void HandleNonHeapDealloc(CheckerContext &C, SVal ArgVal, SourceRange Range,
697
                            const Expr *DeallocExpr,
698
                            AllocationFamily Family) const;
699
700
  void HandleFreeAlloca(CheckerContext &C, SVal ArgVal,
701
                        SourceRange Range) const;
702
703
  void HandleMismatchedDealloc(CheckerContext &C, SourceRange Range,
704
                               const Expr *DeallocExpr, const RefState *RS,
705
                               SymbolRef Sym, bool OwnershipTransferred) const;
706
707
  void HandleOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
708
                        const Expr *DeallocExpr, AllocationFamily Family,
709
                        const Expr *AllocExpr = nullptr) const;
710
711
  void HandleUseAfterFree(CheckerContext &C, SourceRange Range,
712
                          SymbolRef Sym) const;
713
714
  void HandleDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
715
                        SymbolRef Sym, SymbolRef PrevSym) const;
716
717
  void HandleDoubleDelete(CheckerContext &C, SymbolRef Sym) const;
718
719
  void HandleUseZeroAlloc(CheckerContext &C, SourceRange Range,
720
                          SymbolRef Sym) const;
721
722
  void HandleFunctionPtrFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
723
                             const Expr *FreeExpr,
724
                             AllocationFamily Family) const;
725
726
  /// Find the location of the allocation for Sym on the path leading to the
727
  /// exploded node N.
728
  static LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
729
                                    CheckerContext &C);
730
731
  void HandleLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
732
733
  /// Test if value in ArgVal equals to value in macro `ZERO_SIZE_PTR`.
734
  bool isArgZERO_SIZE_PTR(ProgramStateRef State, CheckerContext &C,
735
                          SVal ArgVal) const;
736
};
737
} // end anonymous namespace
738
739
//===----------------------------------------------------------------------===//
740
// Definition of NoOwnershipChangeVisitor.
741
//===----------------------------------------------------------------------===//
742
743
namespace {
744
class NoOwnershipChangeVisitor final : public NoStateChangeFuncVisitor {
745
  SymbolRef Sym;
746
  using OwnerSet = llvm::SmallPtrSet<const MemRegion *, 8>;
747
748
  // Collect which entities point to the allocated memory, and could be
749
  // responsible for deallocating it.
750
  class OwnershipBindingsHandler : public StoreManager::BindingsHandler {
751
    SymbolRef Sym;
752
    OwnerSet &Owners;
753
754
  public:
755
    OwnershipBindingsHandler(SymbolRef Sym, OwnerSet &Owners)
756
6
        : Sym(Sym), Owners(Owners) {}
757
758
    bool HandleBinding(StoreManager &SMgr, Store Store, const MemRegion *Region,
759
11
                       SVal Val) override {
760
11
      if (Val.getAsSymbol() == Sym)
761
4
        Owners.insert(Region);
762
11
      return true;
763
11
    }
764
765
0
    LLVM_DUMP_METHOD void dump() const { dumpToStream(llvm::errs()); }
766
0
    LLVM_DUMP_METHOD void dumpToStream(llvm::raw_ostream &out) const {
767
0
      out << "Owners: {\n";
768
0
      for (const MemRegion *Owner : Owners) {
769
0
        out << "  ";
770
0
        Owner->dumpToStream(out);
771
0
        out << ",\n";
772
0
      }
773
0
      out << "}\n";
774
0
    }
775
  };
776
777
protected:
778
6
  OwnerSet getOwnersAtNode(const ExplodedNode *N) {
779
6
    OwnerSet Ret;
780
781
6
    ProgramStateRef State = N->getState();
782
6
    OwnershipBindingsHandler Handler{Sym, Ret};
783
6
    State->getStateManager().getStoreManager().iterBindings(State->getStore(),
784
6
                                                            Handler);
785
6
    return Ret;
786
6
  }
787
788
  LLVM_DUMP_METHOD static std::string
789
0
  getFunctionName(const ExplodedNode *CallEnterN) {
790
0
    if (const CallExpr *CE = llvm::dyn_cast_or_null<CallExpr>(
791
0
            CallEnterN->getLocationAs<CallEnter>()->getCallExpr()))
792
0
      if (const FunctionDecl *FD = CE->getDirectCallee())
793
0
        return FD->getQualifiedNameAsString();
794
0
    return "";
795
0
  }
796
797
73
  bool doesFnIntendToHandleOwnership(const Decl *Callee, ASTContext &ACtx) {
798
73
    using namespace clang::ast_matchers;
799
73
    const FunctionDecl *FD = dyn_cast<FunctionDecl>(Callee);
800
73
    if (!FD)
801
0
      return false;
802
    // TODO: Operator delete is hardly the only deallocator -- Can we reuse
803
    // isFreeingCall() or something thats already here?
804
73
    auto Deallocations = match(
805
73
        stmt(hasDescendant(cxxDeleteExpr().bind("delete"))
806
73
             ), *FD->getBody(), ACtx);
807
    // TODO: Ownership my change with an attempt to store the allocated memory.
808
73
    return !Deallocations.empty();
809
73
  }
810
811
  virtual bool
812
  wasModifiedInFunction(const ExplodedNode *CallEnterN,
813
73
                        const ExplodedNode *CallExitEndN) override {
814
73
    if (!doesFnIntendToHandleOwnership(
815
73
            CallExitEndN->getFirstPred()->getLocationContext()->getDecl(),
816
73
            CallExitEndN->getState()->getAnalysisManager().getASTContext()))
817
70
      return true;
818
819
3
    if (CallEnterN->getState()->get<RegionState>(Sym) !=
820
3
        CallExitEndN->getState()->get<RegionState>(Sym))
821
0
      return true;
822
823
3
    OwnerSet CurrOwners = getOwnersAtNode(CallEnterN);
824
3
    OwnerSet ExitOwners = getOwnersAtNode(CallExitEndN);
825
826
    // Owners in the current set may be purged from the analyzer later on.
827
    // If a variable is dead (is not referenced directly or indirectly after
828
    // some point), it will be removed from the Store before the end of its
829
    // actual lifetime.
830
    // This means that that if the ownership status didn't change, CurrOwners
831
    // must be a superset of, but not necessarily equal to ExitOwners.
832
3
    return !llvm::set_is_subset(ExitOwners, CurrOwners);
833
3
  }
834
835
2
  static PathDiagnosticPieceRef emitNote(const ExplodedNode *N) {
836
2
    PathDiagnosticLocation L = PathDiagnosticLocation::create(
837
2
        N->getLocation(),
838
2
        N->getState()->getStateManager().getContext().getSourceManager());
839
2
    return std::make_shared<PathDiagnosticEventPiece>(
840
2
        L, "Returning without deallocating memory or storing the pointer for "
841
2
           "later deallocation");
842
2
  }
843
844
  virtual PathDiagnosticPieceRef
845
  maybeEmitNoteForObjCSelf(PathSensitiveBugReport &R,
846
                           const ObjCMethodCall &Call,
847
0
                           const ExplodedNode *N) override {
848
    // TODO: Implement.
849
0
    return nullptr;
850
0
  }
851
852
  virtual PathDiagnosticPieceRef
853
  maybeEmitNoteForCXXThis(PathSensitiveBugReport &R,
854
                          const CXXConstructorCall &Call,
855
0
                          const ExplodedNode *N) override {
856
    // TODO: Implement.
857
0
    return nullptr;
858
0
  }
859
860
  virtual PathDiagnosticPieceRef
861
  maybeEmitNoteForParameters(PathSensitiveBugReport &R, const CallEvent &Call,
862
4
                             const ExplodedNode *N) override {
863
    // TODO: Factor the logic of "what constitutes as an entity being passed
864
    // into a function call" out by reusing the code in
865
    // NoStoreFuncVisitor::maybeEmitNoteForParameters, maybe by incorporating
866
    // the printing technology in UninitializedObject's FieldChainInfo.
867
4
    ArrayRef<ParmVarDecl *> Parameters = Call.parameters();
868
5
    for (unsigned I = 0; I < Call.getNumArgs() && 
I < Parameters.size()3
;
++I1
) {
869
3
      SVal V = Call.getArgSVal(I);
870
3
      if (V.getAsSymbol() == Sym)
871
2
        return emitNote(N);
872
3
    }
873
2
    return nullptr;
874
4
  }
875
876
public:
877
  NoOwnershipChangeVisitor(SymbolRef Sym)
878
      : NoStateChangeFuncVisitor(bugreporter::TrackingKind::Thorough),
879
253
        Sym(Sym) {}
880
881
253
  void Profile(llvm::FoldingSetNodeID &ID) const override {
882
253
    static int Tag = 0;
883
253
    ID.AddPointer(&Tag);
884
253
    ID.AddPointer(Sym);
885
253
  }
886
887
0
  void *getTag() const {
888
0
    static int Tag = 0;
889
0
    return static_cast<void *>(&Tag);
890
0
  }
891
};
892
893
} // end anonymous namespace
894
895
//===----------------------------------------------------------------------===//
896
// Definition of MallocBugVisitor.
897
//===----------------------------------------------------------------------===//
898
899
namespace {
900
/// The bug visitor which allows us to print extra diagnostics along the
901
/// BugReport path. For example, showing the allocation site of the leaked
902
/// region.
903
class MallocBugVisitor final : public BugReporterVisitor {
904
protected:
905
  enum NotificationMode { Normal, ReallocationFailed };
906
907
  // The allocated region symbol tracked by the main analysis.
908
  SymbolRef Sym;
909
910
  // The mode we are in, i.e. what kind of diagnostics will be emitted.
911
  NotificationMode Mode;
912
913
  // A symbol from when the primary region should have been reallocated.
914
  SymbolRef FailedReallocSymbol;
915
916
  // A C++ destructor stack frame in which memory was released. Used for
917
  // miscellaneous false positive suppression.
918
  const StackFrameContext *ReleaseDestructorLC;
919
920
  bool IsLeak;
921
922
public:
923
  MallocBugVisitor(SymbolRef S, bool isLeak = false)
924
      : Sym(S), Mode(Normal), FailedReallocSymbol(nullptr),
925
523
        ReleaseDestructorLC(nullptr), IsLeak(isLeak) {}
926
927
531
  static void *getTag() {
928
531
    static int Tag = 0;
929
531
    return &Tag;
930
531
  }
931
932
523
  void Profile(llvm::FoldingSetNodeID &ID) const override {
933
523
    ID.AddPointer(getTag());
934
523
    ID.AddPointer(Sym);
935
523
  }
936
937
  /// Did not track -> allocated. Other state (released) -> allocated.
938
  static inline bool isAllocated(const RefState *RSCurr, const RefState *RSPrev,
939
23.7k
                                 const Stmt *Stmt) {
940
23.7k
    return (isa_and_nonnull<CallExpr, CXXNewExpr>(Stmt) &&
941
23.7k
            
(4.10k
RSCurr4.10k
&&
942
4.10k
             
(1.89k
RSCurr->isAllocated()1.89k
||
RSCurr->isAllocatedOfSizeZero()448
)) &&
943
23.7k
            
(1.52k
!RSPrev1.52k
||
944
1.52k
             
!(1.10k
RSPrev->isAllocated()1.10k
||
RSPrev->isAllocatedOfSizeZero()28
)));
945
23.7k
  }
946
947
  /// Did not track -> released. Other state (allocated) -> released.
948
  /// The statement associated with the release might be missing.
949
  static inline bool isReleased(const RefState *RSCurr, const RefState *RSPrev,
950
23.3k
                                const Stmt *Stmt) {
951
23.3k
    bool IsReleased =
952
23.3k
        (RSCurr && 
RSCurr->isReleased()12.9k
) &&
(2.15k
!RSPrev2.15k
||
!RSPrev->isReleased()2.08k
);
953
23.3k
    assert(!IsReleased || (isa_and_nonnull<CallExpr, CXXDeleteExpr>(Stmt)) ||
954
23.3k
           (!Stmt && RSCurr->getAllocationFamily() == AF_InnerBuffer));
955
0
    return IsReleased;
956
23.3k
  }
957
958
  /// Did not track -> relinquished. Other state (allocated) -> relinquished.
959
  static inline bool isRelinquished(const RefState *RSCurr,
960
23.1k
                                    const RefState *RSPrev, const Stmt *Stmt) {
961
23.1k
    return (
962
23.1k
        isa_and_nonnull<CallExpr, ObjCMessageExpr, ObjCPropertyRefExpr>(Stmt) &&
963
23.1k
        
(2.59k
RSCurr2.59k
&&
RSCurr->isRelinquished()1.05k
) &&
964
23.1k
        
(18
!RSPrev18
||
!RSPrev->isRelinquished()17
));
965
23.1k
  }
966
967
  /// If the expression is not a call, and the state change is
968
  /// released -> allocated, it must be the realloc return value
969
  /// check. If we have to handle more cases here, it might be cleaner just
970
  /// to track this extra bit in the state itself.
971
  static inline bool hasReallocFailed(const RefState *RSCurr,
972
                                      const RefState *RSPrev,
973
23.1k
                                      const Stmt *Stmt) {
974
23.1k
    return ((!isa_and_nonnull<CallExpr>(Stmt)) &&
975
23.1k
            
(20.6k
RSCurr20.6k
&&
976
20.6k
             
(11.8k
RSCurr->isAllocated()11.8k
||
RSCurr->isAllocatedOfSizeZero()2.40k
)) &&
977
23.1k
            
(9.83k
RSPrev9.83k
&&
978
9.83k
             !(RSPrev->isAllocated() || 
RSPrev->isAllocatedOfSizeZero()446
)));
979
23.1k
  }
980
981
  PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
982
                                   BugReporterContext &BRC,
983
                                   PathSensitiveBugReport &BR) override;
984
985
  PathDiagnosticPieceRef getEndPath(BugReporterContext &BRC,
986
                                    const ExplodedNode *EndPathNode,
987
487
                                    PathSensitiveBugReport &BR) override {
988
487
    if (!IsLeak)
989
253
      return nullptr;
990
991
234
    PathDiagnosticLocation L = BR.getLocation();
992
    // Do not add the statement itself as a range in case of leak.
993
234
    return std::make_shared<PathDiagnosticEventPiece>(L, BR.getDescription(),
994
234
                                                      false);
995
487
  }
996
997
private:
998
  class StackHintGeneratorForReallocationFailed
999
      : public StackHintGeneratorForSymbol {
1000
  public:
1001
    StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
1002
6
        : StackHintGeneratorForSymbol(S, M) {}
1003
1004
1
    std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex) override {
1005
      // Printed parameters start at 1, not 0.
1006
1
      ++ArgIndex;
1007
1008
1
      SmallString<200> buf;
1009
1
      llvm::raw_svector_ostream os(buf);
1010
1011
1
      os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
1012
1
         << " parameter failed";
1013
1014
1
      return std::string(os.str());
1015
1
    }
1016
1017
0
    std::string getMessageForReturn(const CallExpr *CallExpr) override {
1018
0
      return "Reallocation of returned value failed";
1019
0
    }
1020
  };
1021
};
1022
} // end anonymous namespace
1023
1024
// A map from the freed symbol to the symbol representing the return value of
1025
// the free function.
1026
REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
1027
1028
namespace {
1029
class StopTrackingCallback final : public SymbolVisitor {
1030
  ProgramStateRef state;
1031
1032
public:
1033
5
  StopTrackingCallback(ProgramStateRef st) : state(std::move(st)) {}
1034
5
  ProgramStateRef getState() const { return state; }
1035
1036
1
  bool VisitSymbol(SymbolRef sym) override {
1037
1
    state = state->remove<RegionState>(sym);
1038
1
    return true;
1039
1
  }
1040
};
1041
} // end anonymous namespace
1042
1043
30.6k
static bool isStandardNewDelete(const FunctionDecl *FD) {
1044
30.6k
  if (!FD)
1045
0
    return false;
1046
1047
30.6k
  OverloadedOperatorKind Kind = FD->getOverloadedOperator();
1048
30.6k
  if (Kind != OO_New && 
Kind != OO_Array_New29.6k
&&
Kind != OO_Delete29.4k
&&
1049
30.6k
      
Kind != OO_Array_Delete28.8k
)
1050
28.7k
    return false;
1051
1052
  // This is standard if and only if it's not defined in a user file.
1053
1.87k
  SourceLocation L = FD->getLocation();
1054
  // If the header for operator delete is not included, it's still defined
1055
  // in an invalid source location. Check to make sure we don't crash.
1056
1.87k
  return !L.isValid() ||
1057
1.87k
         
FD->getASTContext().getSourceManager().isInSystemHeader(L)1.21k
;
1058
30.6k
}
1059
1060
//===----------------------------------------------------------------------===//
1061
// Methods of MallocChecker and MallocBugVisitor.
1062
//===----------------------------------------------------------------------===//
1063
1064
9.16k
bool MallocChecker::isFreeingCall(const CallEvent &Call) const {
1065
9.16k
  if (FreeingMemFnMap.lookup(Call) || 
ReallocatingMemFnMap.lookup(Call)8.67k
)
1066
657
    return true;
1067
1068
8.50k
  const auto *Func = dyn_cast<FunctionDecl>(Call.getDecl());
1069
8.50k
  if (Func && Func->hasAttrs()) {
1070
2.17k
    for (const auto *I : Func->specific_attrs<OwnershipAttr>()) {
1071
45
      OwnershipAttr::OwnershipKind OwnKind = I->getOwnKind();
1072
45
      if (OwnKind == OwnershipAttr::Takes || 
OwnKind == OwnershipAttr::Holds39
)
1073
14
        return true;
1074
45
    }
1075
2.17k
  }
1076
8.49k
  return false;
1077
8.50k
}
1078
1079
1.00k
bool MallocChecker::isMemCall(const CallEvent &Call) const {
1080
1.00k
  if (FreeingMemFnMap.lookup(Call) || 
AllocatingMemFnMap.lookup(Call)584
||
1081
1.00k
      
ReallocatingMemFnMap.lookup(Call)545
)
1082
548
    return true;
1083
1084
454
  if (!ShouldIncludeOwnershipAnnotatedFunctions)
1085
446
    return false;
1086
1087
8
  const auto *Func = dyn_cast<FunctionDecl>(Call.getDecl());
1088
8
  return Func && Func->hasAttr<OwnershipAttr>();
1089
454
}
1090
1091
llvm::Optional<ProgramStateRef>
1092
MallocChecker::performKernelMalloc(const CallEvent &Call, CheckerContext &C,
1093
7
                                   const ProgramStateRef &State) const {
1094
  // 3-argument malloc(), as commonly used in {Free,Net,Open}BSD Kernels:
1095
  //
1096
  // void *malloc(unsigned long size, struct malloc_type *mtp, int flags);
1097
  //
1098
  // One of the possible flags is M_ZERO, which means 'give me back an
1099
  // allocation which is already zeroed', like calloc.
1100
1101
  // 2-argument kmalloc(), as used in the Linux kernel:
1102
  //
1103
  // void *kmalloc(size_t size, gfp_t flags);
1104
  //
1105
  // Has the similar flag value __GFP_ZERO.
1106
1107
  // This logic is largely cloned from O_CREAT in UnixAPIChecker, maybe some
1108
  // code could be shared.
1109
1110
7
  ASTContext &Ctx = C.getASTContext();
1111
7
  llvm::Triple::OSType OS = Ctx.getTargetInfo().getTriple().getOS();
1112
1113
7
  if (!KernelZeroFlagVal.hasValue()) {
1114
1
    if (OS == llvm::Triple::FreeBSD)
1115
0
      KernelZeroFlagVal = 0x0100;
1116
1
    else if (OS == llvm::Triple::NetBSD)
1117
0
      KernelZeroFlagVal = 0x0002;
1118
1
    else if (OS == llvm::Triple::OpenBSD)
1119
0
      KernelZeroFlagVal = 0x0008;
1120
1
    else if (OS == llvm::Triple::Linux)
1121
      // __GFP_ZERO
1122
1
      KernelZeroFlagVal = 0x8000;
1123
0
    else
1124
      // FIXME: We need a more general way of getting the M_ZERO value.
1125
      // See also: O_CREAT in UnixAPIChecker.cpp.
1126
1127
      // Fall back to normal malloc behavior on platforms where we don't
1128
      // know M_ZERO.
1129
0
      return None;
1130
1
  }
1131
1132
  // We treat the last argument as the flags argument, and callers fall-back to
1133
  // normal malloc on a None return. This works for the FreeBSD kernel malloc
1134
  // as well as Linux kmalloc.
1135
7
  if (Call.getNumArgs() < 2)
1136
0
    return None;
1137
1138
7
  const Expr *FlagsEx = Call.getArgExpr(Call.getNumArgs() - 1);
1139
7
  const SVal V = C.getSVal(FlagsEx);
1140
7
  if (!V.getAs<NonLoc>()) {
1141
    // The case where 'V' can be a location can only be due to a bad header,
1142
    // so in this case bail out.
1143
0
    return None;
1144
0
  }
1145
1146
7
  NonLoc Flags = V.castAs<NonLoc>();
1147
7
  NonLoc ZeroFlag = C.getSValBuilder()
1148
7
      .makeIntVal(KernelZeroFlagVal.getValue(), FlagsEx->getType())
1149
7
      .castAs<NonLoc>();
1150
7
  SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And,
1151
7
                                                      Flags, ZeroFlag,
1152
7
                                                      FlagsEx->getType());
1153
7
  if (MaskedFlagsUC.isUnknownOrUndef())
1154
0
    return None;
1155
7
  DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>();
1156
1157
  // Check if maskedFlags is non-zero.
1158
7
  ProgramStateRef TrueState, FalseState;
1159
7
  std::tie(TrueState, FalseState) = State->assume(MaskedFlags);
1160
1161
  // If M_ZERO is set, treat this like calloc (initialized).
1162
7
  if (TrueState && 
!FalseState5
) {
1163
2
    SVal ZeroVal = C.getSValBuilder().makeZeroVal(Ctx.CharTy);
1164
2
    return MallocMemAux(C, Call, Call.getArgExpr(0), ZeroVal, TrueState,
1165
2
                        AF_Malloc);
1166
2
  }
1167
1168
5
  return None;
1169
7
}
1170
1171
SVal MallocChecker::evalMulForBufferSize(CheckerContext &C, const Expr *Blocks,
1172
67
                                         const Expr *BlockBytes) {
1173
67
  SValBuilder &SB = C.getSValBuilder();
1174
67
  SVal BlocksVal = C.getSVal(Blocks);
1175
67
  SVal BlockBytesVal = C.getSVal(BlockBytes);
1176
67
  ProgramStateRef State = C.getState();
1177
67
  SVal TotalSize = SB.evalBinOp(State, BO_Mul, BlocksVal, BlockBytesVal,
1178
67
                                SB.getContext().getSizeType());
1179
67
  return TotalSize;
1180
67
}
1181
1182
void MallocChecker::checkBasicAlloc(const CallEvent &Call,
1183
578
                                    CheckerContext &C) const {
1184
578
  ProgramStateRef State = C.getState();
1185
578
  State = MallocMemAux(C, Call, Call.getArgExpr(0), UndefinedVal(), State,
1186
578
                       AF_Malloc);
1187
578
  State = ProcessZeroAllocCheck(Call, 0, State);
1188
578
  C.addTransition(State);
1189
578
}
1190
1191
void MallocChecker::checkKernelMalloc(const CallEvent &Call,
1192
7
                                      CheckerContext &C) const {
1193
7
  ProgramStateRef State = C.getState();
1194
7
  llvm::Optional<ProgramStateRef> MaybeState =
1195
7
      performKernelMalloc(Call, C, State);
1196
7
  if (MaybeState.hasValue())
1197
2
    State = MaybeState.getValue();
1198
5
  else
1199
5
    State = MallocMemAux(C, Call, Call.getArgExpr(0), UndefinedVal(), State,
1200
5
                         AF_Malloc);
1201
7
  C.addTransition(State);
1202
7
}
1203
1204
92
static bool isStandardRealloc(const CallEvent &Call) {
1205
92
  const FunctionDecl *FD = dyn_cast<FunctionDecl>(Call.getDecl());
1206
92
  assert(FD);
1207
0
  ASTContext &AC = FD->getASTContext();
1208
1209
92
  if (isa<CXXMethodDecl>(FD))
1210
4
    return false;
1211
1212
88
  return FD->getDeclaredReturnType().getDesugaredType(AC) == AC.VoidPtrTy &&
1213
88
         
FD->getParamDecl(0)->getType().getDesugaredType(AC) == AC.VoidPtrTy84
&&
1214
88
         FD->getParamDecl(1)->getType().getDesugaredType(AC) ==
1215
80
             AC.getSizeType();
1216
92
}
1217
1218
16
static bool isGRealloc(const CallEvent &Call) {
1219
16
  const FunctionDecl *FD = dyn_cast<FunctionDecl>(Call.getDecl());
1220
16
  assert(FD);
1221
0
  ASTContext &AC = FD->getASTContext();
1222
1223
16
  if (isa<CXXMethodDecl>(FD))
1224
4
    return false;
1225
1226
12
  return FD->getDeclaredReturnType().getDesugaredType(AC) == AC.VoidPtrTy &&
1227
12
         
FD->getParamDecl(0)->getType().getDesugaredType(AC) == AC.VoidPtrTy8
&&
1228
12
         FD->getParamDecl(1)->getType().getDesugaredType(AC) ==
1229
4
             AC.UnsignedLongTy;
1230
16
}
1231
1232
void MallocChecker::checkRealloc(const CallEvent &Call, CheckerContext &C,
1233
92
                                 bool ShouldFreeOnFail) const {
1234
  // HACK: CallDescription currently recognizes non-standard realloc functions
1235
  // as standard because it doesn't check the type, or wether its a non-method
1236
  // function. This should be solved by making CallDescription smarter.
1237
  // Mind that this came from a bug report, and all other functions suffer from
1238
  // this.
1239
  // https://bugs.llvm.org/show_bug.cgi?id=46253
1240
92
  if (!isStandardRealloc(Call) && 
!isGRealloc(Call)16
)
1241
16
    return;
1242
76
  ProgramStateRef State = C.getState();
1243
76
  State = ReallocMemAux(C, Call, ShouldFreeOnFail, State, AF_Malloc);
1244
76
  State = ProcessZeroAllocCheck(Call, 1, State);
1245
76
  C.addTransition(State);
1246
76
}
1247
1248
void MallocChecker::checkCalloc(const CallEvent &Call,
1249
25
                                CheckerContext &C) const {
1250
25
  ProgramStateRef State = C.getState();
1251
25
  State = CallocMem(C, Call, State);
1252
25
  State = ProcessZeroAllocCheck(Call, 0, State);
1253
25
  State = ProcessZeroAllocCheck(Call, 1, State);
1254
25
  C.addTransition(State);
1255
25
}
1256
1257
531
void MallocChecker::checkFree(const CallEvent &Call, CheckerContext &C) const {
1258
531
  ProgramStateRef State = C.getState();
1259
531
  bool IsKnownToBeAllocatedMemory = false;
1260
531
  if (suppressDeallocationsInSuspiciousContexts(Call, C))
1261
1
    return;
1262
530
  State = FreeMemAux(C, Call, State, 0, false, IsKnownToBeAllocatedMemory,
1263
530
                     AF_Malloc);
1264
530
  C.addTransition(State);
1265
530
}
1266
1267
void MallocChecker::checkAlloca(const CallEvent &Call,
1268
47
                                CheckerContext &C) const {
1269
47
  ProgramStateRef State = C.getState();
1270
47
  State = MallocMemAux(C, Call, Call.getArgExpr(0), UndefinedVal(), State,
1271
47
                       AF_Alloca);
1272
47
  State = ProcessZeroAllocCheck(Call, 0, State);
1273
47
  C.addTransition(State);
1274
47
}
1275
1276
void MallocChecker::checkStrdup(const CallEvent &Call,
1277
88
                                CheckerContext &C) const {
1278
88
  ProgramStateRef State = C.getState();
1279
88
  const auto *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
1280
88
  if (!CE)
1281
0
    return;
1282
88
  State = MallocUpdateRefState(C, CE, State, AF_Malloc);
1283
1284
88
  C.addTransition(State);
1285
88
}
1286
1287
void MallocChecker::checkIfNameIndex(const CallEvent &Call,
1288
0
                                     CheckerContext &C) const {
1289
0
  ProgramStateRef State = C.getState();
1290
  // Should we model this differently? We can allocate a fixed number of
1291
  // elements with zeros in the last one.
1292
0
  State =
1293
0
      MallocMemAux(C, Call, UnknownVal(), UnknownVal(), State, AF_IfNameIndex);
1294
1295
0
  C.addTransition(State);
1296
0
}
1297
1298
void MallocChecker::checkIfFreeNameIndex(const CallEvent &Call,
1299
0
                                         CheckerContext &C) const {
1300
0
  ProgramStateRef State = C.getState();
1301
0
  bool IsKnownToBeAllocatedMemory = false;
1302
0
  State = FreeMemAux(C, Call, State, 0, false, IsKnownToBeAllocatedMemory,
1303
0
                     AF_IfNameIndex);
1304
0
  C.addTransition(State);
1305
0
}
1306
1307
void MallocChecker::checkCXXNewOrCXXDelete(const CallEvent &Call,
1308
877
                                           CheckerContext &C) const {
1309
877
  ProgramStateRef State = C.getState();
1310
877
  bool IsKnownToBeAllocatedMemory = false;
1311
877
  const auto *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
1312
877
  if (!CE)
1313
779
    return;
1314
1315
98
  assert(isStandardNewDelete(Call));
1316
1317
  // Process direct calls to operator new/new[]/delete/delete[] functions
1318
  // as distinct from new/new[]/delete/delete[] expressions that are
1319
  // processed by the checkPostStmt callbacks for CXXNewExpr and
1320
  // CXXDeleteExpr.
1321
0
  const FunctionDecl *FD = C.getCalleeDecl(CE);
1322
98
  switch (FD->getOverloadedOperator()) {
1323
56
  case OO_New:
1324
56
    State =
1325
56
        MallocMemAux(C, Call, CE->getArg(0), UndefinedVal(), State, AF_CXXNew);
1326
56
    State = ProcessZeroAllocCheck(Call, 0, State);
1327
56
    break;
1328
15
  case OO_Array_New:
1329
15
    State = MallocMemAux(C, Call, CE->getArg(0), UndefinedVal(), State,
1330
15
                         AF_CXXNewArray);
1331
15
    State = ProcessZeroAllocCheck(Call, 0, State);
1332
15
    break;
1333
24
  case OO_Delete:
1334
24
    State = FreeMemAux(C, Call, State, 0, false, IsKnownToBeAllocatedMemory,
1335
24
                       AF_CXXNew);
1336
24
    break;
1337
3
  case OO_Array_Delete:
1338
3
    State = FreeMemAux(C, Call, State, 0, false, IsKnownToBeAllocatedMemory,
1339
3
                       AF_CXXNewArray);
1340
3
    break;
1341
0
  default:
1342
0
    llvm_unreachable("not a new/delete operator");
1343
98
  }
1344
1345
98
  C.addTransition(State);
1346
98
}
1347
1348
void MallocChecker::checkGMalloc0(const CallEvent &Call,
1349
14
                                  CheckerContext &C) const {
1350
14
  ProgramStateRef State = C.getState();
1351
14
  SValBuilder &svalBuilder = C.getSValBuilder();
1352
14
  SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
1353
14
  State = MallocMemAux(C, Call, Call.getArgExpr(0), zeroVal, State, AF_Malloc);
1354
14
  State = ProcessZeroAllocCheck(Call, 0, State);
1355
14
  C.addTransition(State);
1356
14
}
1357
1358
void MallocChecker::checkGMemdup(const CallEvent &Call,
1359
0
                                 CheckerContext &C) const {
1360
0
  ProgramStateRef State = C.getState();
1361
0
  State = MallocMemAux(C, Call, Call.getArgExpr(1), UndefinedVal(), State,
1362
0
                       AF_Malloc);
1363
0
  State = ProcessZeroAllocCheck(Call, 1, State);
1364
0
  C.addTransition(State);
1365
0
}
1366
1367
void MallocChecker::checkGMallocN(const CallEvent &Call,
1368
14
                                  CheckerContext &C) const {
1369
14
  ProgramStateRef State = C.getState();
1370
14
  SVal Init = UndefinedVal();
1371
14
  SVal TotalSize = evalMulForBufferSize(C, Call.getArgExpr(0), Call.getArgExpr(1));
1372
14
  State = MallocMemAux(C, Call, TotalSize, Init, State, AF_Malloc);
1373
14
  State = ProcessZeroAllocCheck(Call, 0, State);
1374
14
  State = ProcessZeroAllocCheck(Call, 1, State);
1375
14
  C.addTransition(State);
1376
14
}
1377
1378
void MallocChecker::checkGMallocN0(const CallEvent &Call,
1379
14
                                   CheckerContext &C) const {
1380
14
  ProgramStateRef State = C.getState();
1381
14
  SValBuilder &SB = C.getSValBuilder();
1382
14
  SVal Init = SB.makeZeroVal(SB.getContext().CharTy);
1383
14
  SVal TotalSize = evalMulForBufferSize(C, Call.getArgExpr(0), Call.getArgExpr(1));
1384
14
  State = MallocMemAux(C, Call, TotalSize, Init, State, AF_Malloc);
1385
14
  State = ProcessZeroAllocCheck(Call, 0, State);
1386
14
  State = ProcessZeroAllocCheck(Call, 1, State);
1387
14
  C.addTransition(State);
1388
14
}
1389
1390
void MallocChecker::checkReallocN(const CallEvent &Call,
1391
14
                                  CheckerContext &C) const {
1392
14
  ProgramStateRef State = C.getState();
1393
14
  State = ReallocMemAux(C, Call, /*ShouldFreeOnFail=*/false, State, AF_Malloc,
1394
14
                        /*SuffixWithN=*/true);
1395
14
  State = ProcessZeroAllocCheck(Call, 1, State);
1396
14
  State = ProcessZeroAllocCheck(Call, 2, State);
1397
14
  C.addTransition(State);
1398
14
}
1399
1400
void MallocChecker::checkOwnershipAttr(const CallEvent &Call,
1401
28.8k
                                       CheckerContext &C) const {
1402
28.8k
  ProgramStateRef State = C.getState();
1403
28.8k
  const auto *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
1404
28.8k
  if (!CE)
1405
6.64k
    return;
1406
22.2k
  const FunctionDecl *FD = C.getCalleeDecl(CE);
1407
22.2k
  if (!FD)
1408
9
    return;
1409
22.1k
  if (ShouldIncludeOwnershipAnnotatedFunctions ||
1410
22.1k
      
ChecksEnabled[CK_MismatchedDeallocatorChecker]22.1k
) {
1411
    // Check all the attributes, if there are any.
1412
    // There can be multiple of these attributes.
1413
721
    if (FD->hasAttrs())
1414
97
      for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
1415
49
        switch (I->getOwnKind()) {
1416
33
        case OwnershipAttr::Returns:
1417
33
          State = MallocMemReturnsAttr(C, Call, I, State);
1418
33
          break;
1419
6
        case OwnershipAttr::Takes:
1420
16
        case OwnershipAttr::Holds:
1421
16
          State = FreeMemAttr(C, Call, I, State);
1422
16
          break;
1423
49
        }
1424
49
      }
1425
721
  }
1426
22.1k
  C.addTransition(State);
1427
22.1k
}
1428
1429
void MallocChecker::checkPostCall(const CallEvent &Call,
1430
45.0k
                                  CheckerContext &C) const {
1431
45.0k
  if (C.wasInlined)
1432
13.6k
    return;
1433
31.4k
  if (!Call.getOriginExpr())
1434
316
    return;
1435
1436
31.1k
  ProgramStateRef State = C.getState();
1437
1438
31.1k
  if (const CheckFn *Callback = FreeingMemFnMap.lookup(Call)) {
1439
531
    (*Callback)(this, Call, C);
1440
531
    return;
1441
531
  }
1442
1443
30.6k
  if (const CheckFn *Callback = AllocatingMemFnMap.lookup(Call)) {
1444
787
    (*Callback)(this, Call, C);
1445
787
    return;
1446
787
  }
1447
1448
29.8k
  if (const CheckFn *Callback = ReallocatingMemFnMap.lookup(Call)) {
1449
106
    (*Callback)(this, Call, C);
1450
106
    return;
1451
106
  }
1452
1453
29.7k
  if (isStandardNewDelete(Call)) {
1454
877
    checkCXXNewOrCXXDelete(Call, C);
1455
877
    return;
1456
877
  }
1457
1458
28.8k
  checkOwnershipAttr(Call, C);
1459
28.8k
}
1460
1461
// Performs a 0-sized allocations check.
1462
ProgramStateRef MallocChecker::ProcessZeroAllocCheck(
1463
    const CallEvent &Call, const unsigned IndexOfSizeArg, ProgramStateRef State,
1464
1.41k
    Optional<SVal> RetVal) {
1465
1.41k
  if (!State)
1466
13
    return nullptr;
1467
1468
1.39k
  if (!RetVal)
1469
907
    RetVal = Call.getReturnValue();
1470
1471
1.39k
  const Expr *Arg = nullptr;
1472
1473
1.39k
  if (const CallExpr *CE = dyn_cast<CallExpr>(Call.getOriginExpr())) {
1474
907
    Arg = CE->getArg(IndexOfSizeArg);
1475
907
  } else 
if (const CXXNewExpr *490
NE490
=
1476
490
                 dyn_cast<CXXNewExpr>(Call.getOriginExpr())) {
1477
490
    if (NE->isArray()) {
1478
83
      Arg = *NE->getArraySize();
1479
407
    } else {
1480
407
      return State;
1481
407
    }
1482
490
  } else
1483
0
    llvm_unreachable("not a CallExpr or CXXNewExpr");
1484
1485
990
  assert(Arg);
1486
1487
0
  auto DefArgVal =
1488
990
      State->getSVal(Arg, Call.getLocationContext()).getAs<DefinedSVal>();
1489
1490
990
  if (!DefArgVal)
1491
0
    return State;
1492
1493
  // Check if the allocation size is 0.
1494
990
  ProgramStateRef TrueState, FalseState;
1495
990
  SValBuilder &SvalBuilder = State->getStateManager().getSValBuilder();
1496
990
  DefinedSVal Zero =
1497
990
      SvalBuilder.makeZeroVal(Arg->getType()).castAs<DefinedSVal>();
1498
1499
990
  std::tie(TrueState, FalseState) =
1500
990
      State->assume(SvalBuilder.evalEQ(State, *DefArgVal, Zero));
1501
1502
990
  if (TrueState && 
!FalseState120
) {
1503
99
    SymbolRef Sym = RetVal->getAsLocSymbol();
1504
99
    if (!Sym)
1505
0
      return State;
1506
1507
99
    const RefState *RS = State->get<RegionState>(Sym);
1508
99
    if (RS) {
1509
80
      if (RS->isAllocated())
1510
80
        return TrueState->set<RegionState>(Sym,
1511
80
                                          RefState::getAllocatedOfSizeZero(RS));
1512
0
      else
1513
0
        return State;
1514
80
    } else {
1515
      // Case of zero-size realloc. Historically 'realloc(ptr, 0)' is treated as
1516
      // 'free(ptr)' and the returned value from 'realloc(ptr, 0)' is not
1517
      // tracked. Add zero-reallocated Sym to the state to catch references
1518
      // to zero-allocated memory.
1519
19
      return TrueState->add<ReallocSizeZeroSymbols>(Sym);
1520
19
    }
1521
99
  }
1522
1523
  // Assume the value is non-zero going forward.
1524
891
  assert(FalseState);
1525
0
  return FalseState;
1526
990
}
1527
1528
4
static QualType getDeepPointeeType(QualType T) {
1529
4
  QualType Result = T, PointeeType = T->getPointeeType();
1530
5
  while (!PointeeType.isNull()) {
1531
1
    Result = PointeeType;
1532
1
    PointeeType = PointeeType->getPointeeType();
1533
1
  }
1534
4
  return Result;
1535
4
}
1536
1537
/// \returns true if the constructor invoked by \p NE has an argument of a
1538
/// pointer/reference to a record type.
1539
70
static bool hasNonTrivialConstructorCall(const CXXNewExpr *NE) {
1540
1541
70
  const CXXConstructExpr *ConstructE = NE->getConstructExpr();
1542
70
  if (!ConstructE)
1543
14
    return false;
1544
1545
56
  if (!NE->getAllocatedType()->getAsCXXRecordDecl())
1546
0
    return false;
1547
1548
56
  const CXXConstructorDecl *CtorD = ConstructE->getConstructor();
1549
1550
  // Iterate over the constructor parameters.
1551
56
  for (const auto *CtorParam : CtorD->parameters()) {
1552
1553
7
    QualType CtorParamPointeeT = CtorParam->getType()->getPointeeType();
1554
7
    if (CtorParamPointeeT.isNull())
1555
3
      continue;
1556
1557
4
    CtorParamPointeeT = getDeepPointeeType(CtorParamPointeeT);
1558
1559
4
    if (CtorParamPointeeT->getAsCXXRecordDecl())
1560
3
      return true;
1561
4
  }
1562
1563
53
  return false;
1564
56
}
1565
1566
ProgramStateRef
1567
MallocChecker::processNewAllocation(const CXXAllocatorCall &Call,
1568
                                    CheckerContext &C,
1569
502
                                    AllocationFamily Family) const {
1570
502
  if (!isStandardNewDelete(Call))
1571
9
    return nullptr;
1572
1573
493
  const CXXNewExpr *NE = Call.getOriginExpr();
1574
493
  const ParentMap &PM = C.getLocationContext()->getParentMap();
1575
493
  ProgramStateRef State = C.getState();
1576
1577
  // Non-trivial constructors have a chance to escape 'this', but marking all
1578
  // invocations of trivial constructors as escaped would cause too great of
1579
  // reduction of true positives, so let's just do that for constructors that
1580
  // have an argument of a pointer-to-record type.
1581
493
  if (!PM.isConsumedExpr(NE) && 
hasNonTrivialConstructorCall(NE)70
)
1582
3
    return State;
1583
1584
  // The return value from operator new is bound to a specified initialization
1585
  // value (if any) and we don't want to loose this value. So we call
1586
  // MallocUpdateRefState() instead of MallocMemAux() which breaks the
1587
  // existing binding.
1588
490
  SVal Target = Call.getObjectUnderConstruction();
1589
490
  State = MallocUpdateRefState(C, NE, State, Family, Target);
1590
490
  State = ProcessZeroAllocCheck(Call, 0, State, Target);
1591
490
  return State;
1592
493
}
1593
1594
void MallocChecker::checkNewAllocator(const CXXAllocatorCall &Call,
1595
610
                                      CheckerContext &C) const {
1596
610
  if (!C.wasInlined) {
1597
502
    ProgramStateRef State = processNewAllocation(
1598
502
        Call, C,
1599
502
        (Call.getOriginExpr()->isArray() ? 
AF_CXXNewArray85
:
AF_CXXNew417
));
1600
502
    C.addTransition(State);
1601
502
  }
1602
610
}
1603
1604
152
static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
1605
  // If the first selector piece is one of the names below, assume that the
1606
  // object takes ownership of the memory, promising to eventually deallocate it
1607
  // with free().
1608
  // Ex:  [NSData dataWithBytesNoCopy:bytes length:10];
1609
  // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
1610
152
  StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
1611
152
  return FirstSlot == "dataWithBytesNoCopy" ||
1612
152
         
FirstSlot == "initWithBytesNoCopy"131
||
1613
152
         
FirstSlot == "initWithCharactersNoCopy"116
;
1614
152
}
1615
1616
58
static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
1617
58
  Selector S = Call.getSelector();
1618
1619
  // FIXME: We should not rely on fully-constrained symbols being folded.
1620
103
  for (unsigned i = 1; i < S.getNumArgs(); 
++i45
)
1621
79
    if (S.getNameForSlot(i).equals("freeWhenDone"))
1622
34
      return !Call.getArgSVal(i).isZeroConstant();
1623
1624
24
  return None;
1625
58
}
1626
1627
void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
1628
97
                                         CheckerContext &C) const {
1629
97
  if (C.wasInlined)
1630
1
    return;
1631
1632
96
  if (!isKnownDeallocObjCMethodName(Call))
1633
63
    return;
1634
1635
33
  if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
1636
30
    if (!*FreeWhenDone)
1637
4
      return;
1638
1639
29
  if (Call.hasNonZeroCallbackArg())
1640
1
    return;
1641
1642
28
  bool IsKnownToBeAllocatedMemory;
1643
28
  ProgramStateRef State =
1644
28
      FreeMemAux(C, Call.getArgExpr(0), Call, C.getState(),
1645
28
                 /*Hold=*/true, IsKnownToBeAllocatedMemory, AF_Malloc,
1646
28
                 /*ReturnsNullOnFailure=*/true);
1647
1648
28
  C.addTransition(State);
1649
28
}
1650
1651
ProgramStateRef
1652
MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallEvent &Call,
1653
                                    const OwnershipAttr *Att,
1654
33
                                    ProgramStateRef State) const {
1655
33
  if (!State)
1656
0
    return nullptr;
1657
1658
33
  if (Att->getModule()->getName() != "malloc")
1659
0
    return nullptr;
1660
1661
33
  OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
1662
33
  if (I != E) {
1663
1
    return MallocMemAux(C, Call, Call.getArgExpr(I->getASTIndex()),
1664
1
                        UndefinedVal(), State, AF_Malloc);
1665
1
  }
1666
32
  return MallocMemAux(C, Call, UnknownVal(), UndefinedVal(), State, AF_Malloc);
1667
33
}
1668
1669
ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1670
                                            const CallEvent &Call,
1671
                                            const Expr *SizeEx, SVal Init,
1672
                                            ProgramStateRef State,
1673
718
                                            AllocationFamily Family) {
1674
718
  if (!State)
1675
0
    return nullptr;
1676
1677
718
  assert(SizeEx);
1678
0
  return MallocMemAux(C, Call, C.getSVal(SizeEx), Init, State, Family);
1679
718
}
1680
1681
ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1682
                                            const CallEvent &Call, SVal Size,
1683
                                            SVal Init, ProgramStateRef State,
1684
864
                                            AllocationFamily Family) {
1685
864
  if (!State)
1686
0
    return nullptr;
1687
1688
864
  const Expr *CE = Call.getOriginExpr();
1689
1690
  // We expect the malloc functions to return a pointer.
1691
864
  if (!Loc::isLocType(CE->getType()))
1692
3
    return nullptr;
1693
1694
  // Bind the return value to the symbolic value from the heap region.
1695
  // TODO: We could rewrite post visit to eval call; 'malloc' does not have
1696
  // side effects other than what we model here.
1697
861
  unsigned Count = C.blockCount();
1698
861
  SValBuilder &svalBuilder = C.getSValBuilder();
1699
861
  const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
1700
861
  DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
1701
861
      .castAs<DefinedSVal>();
1702
861
  State = State->BindExpr(CE, C.getLocationContext(), RetVal);
1703
1704
  // Fill the region with the initialization value.
1705
861
  State = State->bindDefaultInitial(RetVal, Init, LCtx);
1706
1707
  // Set the region's extent.
1708
861
  State = setDynamicExtent(State, RetVal.getAsRegion(),
1709
861
                           Size.castAs<DefinedOrUnknownSVal>(), svalBuilder);
1710
1711
861
  return MallocUpdateRefState(C, CE, State, Family);
1712
864
}
1713
1714
static ProgramStateRef MallocUpdateRefState(CheckerContext &C, const Expr *E,
1715
                                            ProgramStateRef State,
1716
                                            AllocationFamily Family,
1717
1.43k
                                            Optional<SVal> RetVal) {
1718
1.43k
  if (!State)
1719
0
    return nullptr;
1720
1721
  // Get the return value.
1722
1.43k
  if (!RetVal)
1723
949
    RetVal = C.getSVal(E);
1724
1725
  // We expect the malloc functions to return a pointer.
1726
1.43k
  if (!RetVal->getAs<Loc>())
1727
0
    return nullptr;
1728
1729
1.43k
  SymbolRef Sym = RetVal->getAsLocSymbol();
1730
  // This is a return value of a function that was not inlined, such as malloc()
1731
  // or new(). We've checked that in the caller. Therefore, it must be a symbol.
1732
1.43k
  assert(Sym);
1733
1734
  // Set the symbol's state to Allocated.
1735
0
  return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
1736
1.43k
}
1737
1738
ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
1739
                                           const CallEvent &Call,
1740
                                           const OwnershipAttr *Att,
1741
16
                                           ProgramStateRef State) const {
1742
16
  if (!State)
1743
0
    return nullptr;
1744
1745
16
  if (Att->getModule()->getName() != "malloc")
1746
0
    return nullptr;
1747
1748
16
  bool IsKnownToBeAllocated = false;
1749
1750
17
  for (const auto &Arg : Att->args()) {
1751
17
    ProgramStateRef StateI =
1752
17
        FreeMemAux(C, Call, State, Arg.getASTIndex(),
1753
17
                   Att->getOwnKind() == OwnershipAttr::Holds,
1754
17
                   IsKnownToBeAllocated, AF_Malloc);
1755
17
    if (StateI)
1756
10
      State = StateI;
1757
17
  }
1758
16
  return State;
1759
16
}
1760
1761
ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1762
                                          const CallEvent &Call,
1763
                                          ProgramStateRef State, unsigned Num,
1764
                                          bool Hold, bool &IsKnownToBeAllocated,
1765
                                          AllocationFamily Family,
1766
657
                                          bool ReturnsNullOnFailure) const {
1767
657
  if (!State)
1768
0
    return nullptr;
1769
1770
657
  if (Call.getNumArgs() < (Num + 1))
1771
0
    return nullptr;
1772
1773
657
  return FreeMemAux(C, Call.getArgExpr(Num), Call, State, Hold,
1774
657
                    IsKnownToBeAllocated, Family, ReturnsNullOnFailure);
1775
657
}
1776
1777
/// Checks if the previous call to free on the given symbol failed - if free
1778
/// failed, returns true. Also, returns the corresponding return value symbol.
1779
static bool didPreviousFreeFail(ProgramStateRef State,
1780
67
                                SymbolRef Sym, SymbolRef &RetStatusSymbol) {
1781
67
  const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
1782
67
  if (Ret) {
1783
10
    assert(*Ret && "We should not store the null return symbol");
1784
0
    ConstraintManager &CMgr = State->getConstraintManager();
1785
10
    ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
1786
10
    RetStatusSymbol = *Ret;
1787
10
    return FreeFailed.isConstrainedTrue();
1788
10
  }
1789
57
  return false;
1790
67
}
1791
1792
238
static bool printMemFnName(raw_ostream &os, CheckerContext &C, const Expr *E) {
1793
238
  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1794
    // FIXME: This doesn't handle indirect calls.
1795
143
    const FunctionDecl *FD = CE->getDirectCallee();
1796
143
    if (!FD)
1797
0
      return false;
1798
1799
143
    os << *FD;
1800
143
    if (!FD->isOverloadedOperator())
1801
128
      os << "()";
1802
143
    return true;
1803
143
  }
1804
1805
95
  if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
1806
5
    if (Msg->isInstanceMessage())
1807
1
      os << "-";
1808
4
    else
1809
4
      os << "+";
1810
5
    Msg->getSelector().print(os);
1811
5
    return true;
1812
5
  }
1813
1814
90
  if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
1815
31
    os << "'"
1816
31
       << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
1817
31
       << "'";
1818
31
    return true;
1819
31
  }
1820
1821
59
  if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
1822
59
    os << "'"
1823
59
       << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
1824
59
       << "'";
1825
59
    return true;
1826
59
  }
1827
1828
0
  return false;
1829
59
}
1830
1831
85
static void printExpectedAllocName(raw_ostream &os, AllocationFamily Family) {
1832
1833
85
  switch(Family) {
1834
67
    case AF_Malloc: os << "malloc()"; return;
1835
14
    case AF_CXXNew: os << "'new'"; return;
1836
4
    case AF_CXXNewArray: os << "'new[]'"; return;
1837
0
    case AF_IfNameIndex: os << "'if_nameindex()'"; return;
1838
0
    case AF_InnerBuffer: os << "container-specific allocator"; return;
1839
0
    case AF_Alloca:
1840
0
    case AF_None: llvm_unreachable("not a deallocation expression");
1841
85
  }
1842
85
}
1843
1844
55
static void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) {
1845
55
  switch(Family) {
1846
25
    case AF_Malloc: os << "free()"; return;
1847
14
    case AF_CXXNew: os << "'delete'"; return;
1848
16
    case AF_CXXNewArray: os << "'delete[]'"; return;
1849
0
    case AF_IfNameIndex: os << "'if_freenameindex()'"; return;
1850
0
    case AF_InnerBuffer: os << "container-specific deallocator"; return;
1851
0
    case AF_Alloca:
1852
0
    case AF_None: llvm_unreachable("suspicious argument");
1853
55
  }
1854
55
}
1855
1856
ProgramStateRef MallocChecker::FreeMemAux(
1857
    CheckerContext &C, const Expr *ArgExpr, const CallEvent &Call,
1858
    ProgramStateRef State, bool Hold, bool &IsKnownToBeAllocated,
1859
1.06k
    AllocationFamily Family, bool ReturnsNullOnFailure) const {
1860
1861
1.06k
  if (!State)
1862
0
    return nullptr;
1863
1864
1.06k
  SVal ArgVal = C.getSVal(ArgExpr);
1865
1.06k
  if (!ArgVal.getAs<DefinedOrUnknownSVal>())
1866
1
    return nullptr;
1867
1.06k
  DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
1868
1869
  // Check for null dereferences.
1870
1.06k
  if (!location.getAs<Loc>())
1871
6
    return nullptr;
1872
1873
  // The explicit NULL case, no operation is performed.
1874
1.05k
  ProgramStateRef notNullState, nullState;
1875
1.05k
  std::tie(notNullState, nullState) = State->assume(location);
1876
1.05k
  if (nullState && 
!notNullState607
)
1877
34
    return nullptr;
1878
1879
  // Unknown values could easily be okay
1880
  // Undefined values are handled elsewhere
1881
1.02k
  if (ArgVal.isUnknownOrUndef())
1882
0
    return nullptr;
1883
1884
1.02k
  const MemRegion *R = ArgVal.getAsRegion();
1885
1.02k
  const Expr *ParentExpr = Call.getOriginExpr();
1886
1887
  // NOTE: We detected a bug, but the checker under whose name we would emit the
1888
  // error could be disabled. Generally speaking, the MallocChecker family is an
1889
  // integral part of the Static Analyzer, and disabling any part of it should
1890
  // only be done under exceptional circumstances, such as frequent false
1891
  // positives. If this is the case, we can reasonably believe that there are
1892
  // serious faults in our understanding of the source code, and even if we
1893
  // don't emit an warning, we should terminate further analysis with a sink
1894
  // node.
1895
1896
  // Nonlocs can't be freed, of course.
1897
  // Non-region locations (labels and fixed addresses) also shouldn't be freed.
1898
1.02k
  if (!R) {
1899
    // Exception:
1900
    // If the macro ZERO_SIZE_PTR is defined, this could be a kernel source
1901
    // code. In that case, the ZERO_SIZE_PTR defines a special value used for a
1902
    // zero-sized memory block which is allowed to be freed, despite not being a
1903
    // null pointer.
1904
20
    if (Family != AF_Malloc || 
!isArgZERO_SIZE_PTR(State, C, ArgVal)14
)
1905
19
      HandleNonHeapDealloc(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1906
19
                           Family);
1907
20
    return nullptr;
1908
20
  }
1909
1910
1.00k
  R = R->StripCasts();
1911
1912
  // Blocks might show up as heap data, but should not be free()d
1913
1.00k
  if (isa<BlockDataRegion>(R)) {
1914
6
    HandleNonHeapDealloc(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1915
6
                         Family);
1916
6
    return nullptr;
1917
6
  }
1918
1919
996
  const MemSpaceRegion *MS = R->getMemorySpace();
1920
1921
  // Parameters, locals, statics, globals, and memory returned by
1922
  // __builtin_alloca() shouldn't be freed.
1923
996
  if (!isa<UnknownSpaceRegion, HeapSpaceRegion>(MS)) {
1924
    // FIXME: at the time this code was written, malloc() regions were
1925
    // represented by conjured symbols, which are all in UnknownSpaceRegion.
1926
    // This means that there isn't actually anything from HeapSpaceRegion
1927
    // that should be freed, even though we allow it here.
1928
    // Of course, free() can work on memory allocated outside the current
1929
    // function, so UnknownSpaceRegion is always a possibility.
1930
    // False negatives are better than false positives.
1931
1932
85
    if (isa<AllocaRegion>(R))
1933
8
      HandleFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1934
77
    else
1935
77
      HandleNonHeapDealloc(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1936
77
                           Family);
1937
1938
85
    return nullptr;
1939
85
  }
1940
1941
911
  const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
1942
  // Various cases could lead to non-symbol values here.
1943
  // For now, ignore them.
1944
911
  if (!SrBase)
1945
0
    return nullptr;
1946
1947
911
  SymbolRef SymBase = SrBase->getSymbol();
1948
911
  const RefState *RsBase = State->get<RegionState>(SymBase);
1949
911
  SymbolRef PreviousRetStatusSymbol = nullptr;
1950
1951
911
  IsKnownToBeAllocated =
1952
911
      RsBase && 
(720
RsBase->isAllocated()720
||
RsBase->isAllocatedOfSizeZero()188
);
1953
1954
911
  if (RsBase) {
1955
1956
    // Memory returned by alloca() shouldn't be freed.
1957
720
    if (RsBase->getAllocationFamily() == AF_Alloca) {
1958
7
      HandleFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1959
7
      return nullptr;
1960
7
    }
1961
1962
    // Check for double free first.
1963
713
    if ((RsBase->isReleased() || 
RsBase->isRelinquished()658
) &&
1964
713
        
!didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)67
) {
1965
61
      HandleDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1966
61
                       SymBase, PreviousRetStatusSymbol);
1967
61
      return nullptr;
1968
1969
    // If the pointer is allocated or escaped, but we are now trying to free it,
1970
    // check that the call to free is proper.
1971
652
    } else if (RsBase->isAllocated() || 
RsBase->isAllocatedOfSizeZero()127
||
1972
652
               
RsBase->isEscaped()108
) {
1973
1974
      // Check if an expected deallocation function matches the real one.
1975
646
      bool DeallocMatchesAlloc = RsBase->getAllocationFamily() == Family;
1976
646
      if (!DeallocMatchesAlloc) {
1977
69
        HandleMismatchedDealloc(C, ArgExpr->getSourceRange(), ParentExpr,
1978
69
                                RsBase, SymBase, Hold);
1979
69
        return nullptr;
1980
69
      }
1981
1982
      // Check if the memory location being freed is the actual location
1983
      // allocated, or an offset.
1984
577
      RegionOffset Offset = R->getAsOffset();
1985
577
      if (Offset.isValid() &&
1986
577
          !Offset.hasSymbolicOffset() &&
1987
577
          
Offset.getOffset() != 0576
) {
1988
26
        const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
1989
26
        HandleOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1990
26
                         Family, AllocExpr);
1991
26
        return nullptr;
1992
26
      }
1993
577
    }
1994
713
  }
1995
1996
748
  if (SymBase->getType()->isFunctionPointerType()) {
1997
3
    HandleFunctionPtrFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1998
3
                          Family);
1999
3
    return nullptr;
2000
3
  }
2001
2002
  // Clean out the info on previous call to free return info.
2003
745
  State = State->remove<FreeReturnValue>(SymBase);
2004
2005
  // Keep track of the return value. If it is NULL, we will know that free
2006
  // failed.
2007
745
  if (ReturnsNullOnFailure) {
2008
21
    SVal RetVal = C.getSVal(ParentExpr);
2009
21
    SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
2010
21
    if (RetStatusSymbol) {
2011
21
      C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
2012
21
      State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
2013
21
    }
2014
21
  }
2015
2016
  // If we don't know anything about this symbol, a free on it may be totally
2017
  // valid. If this is the case, lets assume that the allocation family of the
2018
  // freeing function is the same as the symbols allocation family, and go with
2019
  // that.
2020
745
  assert(!RsBase || (RsBase && RsBase->getAllocationFamily() == Family));
2021
2022
  // Normal free.
2023
745
  if (Hold)
2024
27
    return State->set<RegionState>(SymBase,
2025
27
                                   RefState::getRelinquished(Family,
2026
27
                                                             ParentExpr));
2027
2028
718
  return State->set<RegionState>(SymBase,
2029
718
                                 RefState::getReleased(Family, ParentExpr));
2030
745
}
2031
2032
Optional<MallocChecker::CheckKind>
2033
MallocChecker::getCheckIfTracked(AllocationFamily Family,
2034
638
                                 bool IsALeakCheck) const {
2035
638
  switch (Family) {
2036
380
  case AF_Malloc:
2037
382
  case AF_Alloca:
2038
382
  case AF_IfNameIndex: {
2039
382
    if (ChecksEnabled[CK_MallocChecker])
2040
362
      return CK_MallocChecker;
2041
20
    return None;
2042
382
  }
2043
185
  case AF_CXXNew:
2044
225
  case AF_CXXNewArray: {
2045
225
    if (IsALeakCheck) {
2046
97
      if (ChecksEnabled[CK_NewDeleteLeaksChecker])
2047
71
        return CK_NewDeleteLeaksChecker;
2048
97
    }
2049
128
    else {
2050
128
      if (ChecksEnabled[CK_NewDeleteChecker])
2051
104
        return CK_NewDeleteChecker;
2052
128
    }
2053
50
    return None;
2054
225
  }
2055
31
  case AF_InnerBuffer: {
2056
31
    if (ChecksEnabled[CK_InnerPointerChecker])
2057
31
      return CK_InnerPointerChecker;
2058
0
    return None;
2059
31
  }
2060
0
  case AF_None: {
2061
0
    llvm_unreachable("no family");
2062
0
  }
2063
638
  }
2064
0
  llvm_unreachable("unhandled family");
2065
0
}
2066
2067
Optional<MallocChecker::CheckKind>
2068
MallocChecker::getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
2069
232
                                 bool IsALeakCheck) const {
2070
232
  if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym))
2071
4
    return CK_MallocChecker;
2072
2073
228
  const RefState *RS = C.getState()->get<RegionState>(Sym);
2074
228
  assert(RS);
2075
0
  return getCheckIfTracked(RS->getAllocationFamily(), IsALeakCheck);
2076
232
}
2077
2078
19
bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
2079
19
  if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
2080
0
    os << "an integer (" << IntVal->getValue() << ")";
2081
19
  else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
2082
13
    os << "a constant address (" << ConstAddr->getValue() << ")";
2083
6
  else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
2084
6
    os << "the address of the label '" << Label->getLabel()->getName() << "'";
2085
0
  else
2086
0
    return false;
2087
2088
19
  return true;
2089
19
}
2090
2091
bool MallocChecker::SummarizeRegion(raw_ostream &os,
2092
66
                                    const MemRegion *MR) {
2093
66
  switch (MR->getKind()) {
2094
13
  case MemRegion::FunctionCodeRegionKind: {
2095
13
    const NamedDecl *FD = cast<FunctionCodeRegion>(MR)->getDecl();
2096
13
    if (FD)
2097
13
      os << "the address of the function '" << *FD << '\'';
2098
0
    else
2099
0
      os << "the address of a function";
2100
13
    return true;
2101
0
  }
2102
0
  case MemRegion::BlockCodeRegionKind:
2103
0
    os << "block text";
2104
0
    return true;
2105
6
  case MemRegion::BlockDataRegionKind:
2106
    // FIXME: where the block came from?
2107
6
    os << "a block";
2108
6
    return true;
2109
47
  default: {
2110
47
    const MemSpaceRegion *MS = MR->getMemorySpace();
2111
2112
47
    if (isa<StackLocalsSpaceRegion>(MS)) {
2113
29
      const VarRegion *VR = dyn_cast<VarRegion>(MR);
2114
29
      const VarDecl *VD;
2115
29
      if (VR)
2116
27
        VD = VR->getDecl();
2117
2
      else
2118
2
        VD = nullptr;
2119
2120
29
      if (VD)
2121
27
        os << "the address of the local variable '" << VD->getName() << "'";
2122
2
      else
2123
2
        os << "the address of a local stack variable";
2124
29
      return true;
2125
29
    }
2126
2127
18
    if (isa<StackArgumentsSpaceRegion>(MS)) {
2128
6
      const VarRegion *VR = dyn_cast<VarRegion>(MR);
2129
6
      const VarDecl *VD;
2130
6
      if (VR)
2131
6
        VD = VR->getDecl();
2132
0
      else
2133
0
        VD = nullptr;
2134
2135
6
      if (VD)
2136
6
        os << "the address of the parameter '" << VD->getName() << "'";
2137
0
      else
2138
0
        os << "the address of a parameter";
2139
6
      return true;
2140
6
    }
2141
2142
12
    if (isa<GlobalsSpaceRegion>(MS)) {
2143
12
      const VarRegion *VR = dyn_cast<VarRegion>(MR);
2144
12
      const VarDecl *VD;
2145
12
      if (VR)
2146
12
        VD = VR->getDecl();
2147
0
      else
2148
0
        VD = nullptr;
2149
2150
12
      if (VD) {
2151
12
        if (VD->isStaticLocal())
2152
6
          os << "the address of the static variable '" << VD->getName() << "'";
2153
6
        else
2154
6
          os << "the address of the global variable '" << VD->getName() << "'";
2155
12
      } else
2156
0
        os << "the address of a global variable";
2157
12
      return true;
2158
12
    }
2159
2160
0
    return false;
2161
12
  }
2162
66
  }
2163
66
}
2164
2165
void MallocChecker::HandleNonHeapDealloc(CheckerContext &C, SVal ArgVal,
2166
                                         SourceRange Range,
2167
                                         const Expr *DeallocExpr,
2168
102
                                         AllocationFamily Family) const {
2169
2170
102
  if (!ChecksEnabled[CK_MallocChecker] && 
!ChecksEnabled[CK_NewDeleteChecker]18
) {
2171
8
    C.addSink();
2172
8
    return;
2173
8
  }
2174
2175
94
  Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
2176
94
  if (!CheckKind.hasValue())
2177
9
    return;
2178
2179
85
  if (ExplodedNode *N = C.generateErrorNode()) {
2180
85
    if (!BT_BadFree[*CheckKind])
2181
23
      BT_BadFree[*CheckKind].reset(new BugType(
2182
23
          CheckNames[*CheckKind], "Bad free", categories::MemoryError));
2183
2184
85
    SmallString<100> buf;
2185
85
    llvm::raw_svector_ostream os(buf);
2186
2187
85
    const MemRegion *MR = ArgVal.getAsRegion();
2188
108
    while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
2189
23
      MR = ER->getSuperRegion();
2190
2191
85
    os << "Argument to ";
2192
85
    if (!printMemFnName(os, C, DeallocExpr))
2193
0
      os << "deallocator";
2194
2195
85
    os << " is ";
2196
85
    bool Summarized = MR ? 
SummarizeRegion(os, MR)66
2197
85
                         : 
SummarizeValue(os, ArgVal)19
;
2198
85
    if (Summarized)
2199
85
      os << ", which is not memory allocated by ";
2200
0
    else
2201
0
      os << "not memory allocated by ";
2202
2203
85
    printExpectedAllocName(os, Family);
2204
2205
85
    auto R = std::make_unique<PathSensitiveBugReport>(*BT_BadFree[*CheckKind],
2206
85
                                                      os.str(), N);
2207
85
    R->markInteresting(MR);
2208
85
    R->addRange(Range);
2209
85
    C.emitReport(std::move(R));
2210
85
  }
2211
85
}
2212
2213
void MallocChecker::HandleFreeAlloca(CheckerContext &C, SVal ArgVal,
2214
15
                                     SourceRange Range) const {
2215
2216
15
  Optional<MallocChecker::CheckKind> CheckKind;
2217
2218
15
  if (ChecksEnabled[CK_MallocChecker])
2219
12
    CheckKind = CK_MallocChecker;
2220
3
  else if (ChecksEnabled[CK_MismatchedDeallocatorChecker])
2221
2
    CheckKind = CK_MismatchedDeallocatorChecker;
2222
1
  else {
2223
1
    C.addSink();
2224
1
    return;
2225
1
  }
2226
2227
14
  if (ExplodedNode *N = C.generateErrorNode()) {
2228
14
    if (!BT_FreeAlloca[*CheckKind])
2229
6
      BT_FreeAlloca[*CheckKind].reset(new BugType(
2230
6
          CheckNames[*CheckKind], "Free alloca()", categories::MemoryError));
2231
2232
14
    auto R = std::make_unique<PathSensitiveBugReport>(
2233
14
        *BT_FreeAlloca[*CheckKind],
2234
14
        "Memory allocated by alloca() should not be deallocated", N);
2235
14
    R->markInteresting(ArgVal.getAsRegion());
2236
14
    R->addRange(Range);
2237
14
    C.emitReport(std::move(R));
2238
14
  }
2239
14
}
2240
2241
void MallocChecker::HandleMismatchedDealloc(CheckerContext &C,
2242
                                            SourceRange Range,
2243
                                            const Expr *DeallocExpr,
2244
                                            const RefState *RS, SymbolRef Sym,
2245
69
                                            bool OwnershipTransferred) const {
2246
2247
69
  if (!ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
2248
10
    C.addSink();
2249
10
    return;
2250
10
  }
2251
2252
59
  if (ExplodedNode *N = C.generateErrorNode()) {
2253
59
    if (!BT_MismatchedDealloc)
2254
12
      BT_MismatchedDealloc.reset(
2255
12
          new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
2256
12
                      "Bad deallocator", categories::MemoryError));
2257
2258
59
    SmallString<100> buf;
2259
59
    llvm::raw_svector_ostream os(buf);
2260
2261
59
    const Expr *AllocExpr = cast<Expr>(RS->getStmt());
2262
59
    SmallString<20> AllocBuf;
2263
59
    llvm::raw_svector_ostream AllocOs(AllocBuf);
2264
59
    SmallString<20> DeallocBuf;
2265
59
    llvm::raw_svector_ostream DeallocOs(DeallocBuf);
2266
2267
59
    if (OwnershipTransferred) {
2268
4
      if (printMemFnName(DeallocOs, C, DeallocExpr))
2269
4
        os << DeallocOs.str() << " cannot";
2270
0
      else
2271
0
        os << "Cannot";
2272
2273
4
      os << " take ownership of memory";
2274
2275
4
      if (printMemFnName(AllocOs, C, AllocExpr))
2276
4
        os << " allocated by " << AllocOs.str();
2277
55
    } else {
2278
55
      os << "Memory";
2279
55
      if (printMemFnName(AllocOs, C, AllocExpr))
2280
55
        os << " allocated by " << AllocOs.str();
2281
2282
55
      os << " should be deallocated by ";
2283
55
        printExpectedDeallocName(os, RS->getAllocationFamily());
2284
2285
55
        if (printMemFnName(DeallocOs, C, DeallocExpr))
2286
55
          os << ", not " << DeallocOs.str();
2287
55
    }
2288
2289
59
    auto R = std::make_unique<PathSensitiveBugReport>(*BT_MismatchedDealloc,
2290
59
                                                      os.str(), N);
2291
59
    R->markInteresting(Sym);
2292
59
    R->addRange(Range);
2293
59
    R->addVisitor<MallocBugVisitor>(Sym);
2294
59
    C.emitReport(std::move(R));
2295
59
  }
2296
59
}
2297
2298
void MallocChecker::HandleOffsetFree(CheckerContext &C, SVal ArgVal,
2299
                                     SourceRange Range, const Expr *DeallocExpr,
2300
                                     AllocationFamily Family,
2301
26
                                     const Expr *AllocExpr) const {
2302
2303
26
  if (!ChecksEnabled[CK_MallocChecker] && 
!ChecksEnabled[CK_NewDeleteChecker]11
) {
2304
4
    C.addSink();
2305
4
    return;
2306
4
  }
2307
2308
22
  Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
2309
22
  if (!CheckKind.hasValue())
2310
6
    return;
2311
2312
16
  ExplodedNode *N = C.generateErrorNode();
2313
16
  if (!N)
2314
0
    return;
2315
2316
16
  if (!BT_OffsetFree[*CheckKind])
2317
10
    BT_OffsetFree[*CheckKind].reset(new BugType(
2318
10
        CheckNames[*CheckKind], "Offset free", categories::MemoryError));
2319
2320
16
  SmallString<100> buf;
2321
16
  llvm::raw_svector_ostream os(buf);
2322
16
  SmallString<20> AllocNameBuf;
2323
16
  llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
2324
2325
16
  const MemRegion *MR = ArgVal.getAsRegion();
2326
16
  assert(MR && "Only MemRegion based symbols can have offset free errors");
2327
2328
0
  RegionOffset Offset = MR->getAsOffset();
2329
16
  assert((Offset.isValid() &&
2330
16
          !Offset.hasSymbolicOffset() &&
2331
16
          Offset.getOffset() != 0) &&
2332
16
         "Only symbols with a valid offset can have offset free errors");
2333
2334
0
  int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
2335
2336
16
  os << "Argument to ";
2337
16
  if (!printMemFnName(os, C, DeallocExpr))
2338
0
    os << "deallocator";
2339
16
  os << " is offset by "
2340
16
     << offsetBytes
2341
16
     << " "
2342
16
     << ((abs(offsetBytes) > 1) ? 
"bytes"14
:
"byte"2
)
2343
16
     << " from the start of ";
2344
16
  if (AllocExpr && printMemFnName(AllocNameOs, C, AllocExpr))
2345
16
    os << "memory allocated by " << AllocNameOs.str();
2346
0
  else
2347
0
    os << "allocated memory";
2348
2349
16
  auto R = std::make_unique<PathSensitiveBugReport>(*BT_OffsetFree[*CheckKind],
2350
16
                                                    os.str(), N);
2351
16
  R->markInteresting(MR->getBaseRegion());
2352
16
  R->addRange(Range);
2353
16
  C.emitReport(std::move(R));
2354
16
}
2355
2356
void MallocChecker::HandleUseAfterFree(CheckerContext &C, SourceRange Range,
2357
179
                                       SymbolRef Sym) const {
2358
2359
179
  if (!ChecksEnabled[CK_MallocChecker] && 
!ChecksEnabled[CK_NewDeleteChecker]122
&&
2360
179
      
!ChecksEnabled[CK_InnerPointerChecker]71
) {
2361
40
    C.addSink();
2362
40
    return;
2363
40
  }
2364
2365
139
  Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
2366
139
  if (!CheckKind.hasValue())
2367
14
    return;
2368
2369
125
  if (ExplodedNode *N = C.generateErrorNode()) {
2370
125
    if (!BT_UseFree[*CheckKind])
2371
29
      BT_UseFree[*CheckKind].reset(new BugType(
2372
29
          CheckNames[*CheckKind], "Use-after-free", categories::MemoryError));
2373
2374
125
    AllocationFamily AF =
2375
125
        C.getState()->get<RegionState>(Sym)->getAllocationFamily();
2376
2377
125
    auto R = std::make_unique<PathSensitiveBugReport>(
2378
125
        *BT_UseFree[*CheckKind],
2379
125
        AF == AF_InnerBuffer
2380
125
            ? 
"Inner pointer of container used after re/deallocation"31
2381
125
            : 
"Use of memory after it is freed"94
,
2382
125
        N);
2383
2384
125
    R->markInteresting(Sym);
2385
125
    R->addRange(Range);
2386
125
    R->addVisitor<MallocBugVisitor>(Sym);
2387
2388
125
    if (AF == AF_InnerBuffer)
2389
31
      R->addVisitor(allocation_state::getInnerPointerBRVisitor(Sym));
2390
2391
125
    C.emitReport(std::move(R));
2392
125
  }
2393
125
}
2394
2395
void MallocChecker::HandleDoubleFree(CheckerContext &C, SourceRange Range,
2396
                                     bool Released, SymbolRef Sym,
2397
61
                                     SymbolRef PrevSym) const {
2398
2399
61
  if (!ChecksEnabled[CK_MallocChecker] && 
!ChecksEnabled[CK_NewDeleteChecker]11
) {
2400
4
    C.addSink();
2401
4
    return;
2402
4
  }
2403
2404
57
  Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
2405
57
  if (!CheckKind.hasValue())
2406
6
    return;
2407
2408
51
  if (ExplodedNode *N = C.generateErrorNode()) {
2409
47
    if (!BT_DoubleFree[*CheckKind])
2410
19
      BT_DoubleFree[*CheckKind].reset(new BugType(
2411
19
          CheckNames[*CheckKind], "Double free", categories::MemoryError));
2412
2413
47
    auto R = std::make_unique<PathSensitiveBugReport>(
2414
47
        *BT_DoubleFree[*CheckKind],
2415
47
        (Released ? 
"Attempt to free released memory"41
2416
47
                  : 
"Attempt to free non-owned memory"6
),
2417
47
        N);
2418
47
    R->addRange(Range);
2419
47
    R->markInteresting(Sym);
2420
47
    if (PrevSym)
2421
4
      R->markInteresting(PrevSym);
2422
47
    R->addVisitor<MallocBugVisitor>(Sym);
2423
47
    C.emitReport(std::move(R));
2424
47
  }
2425
51
}
2426
2427
12
void MallocChecker::HandleDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
2428
2429
12
  if (!ChecksEnabled[CK_NewDeleteChecker]) {
2430
4
    C.addSink();
2431
4
    return;
2432
4
  }
2433
2434
8
  Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
2435
8
  if (!CheckKind.hasValue())
2436
0
    return;
2437
2438
8
  if (ExplodedNode *N = C.generateErrorNode()) {
2439
8
    if (!BT_DoubleDelete)
2440
4
      BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker],
2441
4
                                        "Double delete",
2442
4
                                        categories::MemoryError));
2443
2444
8
    auto R = std::make_unique<PathSensitiveBugReport>(
2445
8
        *BT_DoubleDelete, "Attempt to delete released memory", N);
2446
2447
8
    R->markInteresting(Sym);
2448
8
    R->addVisitor<MallocBugVisitor>(Sym);
2449
8
    C.emitReport(std::move(R));
2450
8
  }
2451
8
}
2452
2453
void MallocChecker::HandleUseZeroAlloc(CheckerContext &C, SourceRange Range,
2454
36
                                       SymbolRef Sym) const {
2455
2456
36
  if (!ChecksEnabled[CK_MallocChecker] && 
!ChecksEnabled[CK_NewDeleteChecker]21
) {
2457
8
    C.addSink();
2458
8
    return;
2459
8
  }
2460
2461
28
  Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
2462
2463
28
  if (!CheckKind.hasValue())
2464
4
    return;
2465
2466
24
  if (ExplodedNode *N = C.generateErrorNode()) {
2467
24
    if (!BT_UseZerroAllocated[*CheckKind])
2468
5
      BT_UseZerroAllocated[*CheckKind].reset(
2469
5
          new BugType(CheckNames[*CheckKind], "Use of zero allocated",
2470
5
                      categories::MemoryError));
2471
2472
24
    auto R = std::make_unique<PathSensitiveBugReport>(
2473
24
        *BT_UseZerroAllocated[*CheckKind],
2474
24
        "Use of memory allocated with size zero", N);
2475
2476
24
    R->addRange(Range);
2477
24
    if (Sym) {
2478
24
      R->markInteresting(Sym);
2479
24
      R->addVisitor<MallocBugVisitor>(Sym);
2480
24
    }
2481
24
    C.emitReport(std::move(R));
2482
24
  }
2483
24
}
2484
2485
void MallocChecker::HandleFunctionPtrFree(CheckerContext &C, SVal ArgVal,
2486
                                          SourceRange Range,
2487
                                          const Expr *FreeExpr,
2488
3
                                          AllocationFamily Family) const {
2489
3
  if (!ChecksEnabled[CK_MallocChecker]) {
2490
0
    C.addSink();
2491
0
    return;
2492
0
  }
2493
2494
3
  Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
2495
3
  if (!CheckKind.hasValue())
2496
0
    return;
2497
2498
3
  if (ExplodedNode *N = C.generateErrorNode()) {
2499
3
    if (!BT_BadFree[*CheckKind])
2500
1
      BT_BadFree[*CheckKind].reset(new BugType(
2501
1
          CheckNames[*CheckKind], "Bad free", categories::MemoryError));
2502
2503
3
    SmallString<100> Buf;
2504
3
    llvm::raw_svector_ostream Os(Buf);
2505
2506
3
    const MemRegion *MR = ArgVal.getAsRegion();
2507
3
    while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
2508
0
      MR = ER->getSuperRegion();
2509
2510
3
    Os << "Argument to ";
2511
3
    if (!printMemFnName(Os, C, FreeExpr))
2512
0
      Os << "deallocator";
2513
2514
3
    Os << " is a function pointer";
2515
2516
3
    auto R = std::make_unique<PathSensitiveBugReport>(*BT_BadFree[*CheckKind],
2517
3
                                                      Os.str(), N);
2518
3
    R->markInteresting(MR);
2519
3
    R->addRange(Range);
2520
3
    C.emitReport(std::move(R));
2521
3
  }
2522
3
}
2523
2524
ProgramStateRef
2525
MallocChecker::ReallocMemAux(CheckerContext &C, const CallEvent &Call,
2526
                             bool ShouldFreeOnFail, ProgramStateRef State,
2527
90
                             AllocationFamily Family, bool SuffixWithN) const {
2528
90
  if (!State)
2529
0
    return nullptr;
2530
2531
90
  const CallExpr *CE = cast<CallExpr>(Call.getOriginExpr());
2532
2533
90
  if (SuffixWithN && 
CE->getNumArgs() < 314
)
2534
0
    return nullptr;
2535
90
  else if (CE->getNumArgs() < 2)
2536
0
    return nullptr;
2537
2538
90
  const Expr *arg0Expr = CE->getArg(0);
2539
90
  SVal Arg0Val = C.getSVal(arg0Expr);
2540
90
  if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
2541
0
    return nullptr;
2542
90
  DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
2543
2544
90
  SValBuilder &svalBuilder = C.getSValBuilder();
2545
2546
90
  DefinedOrUnknownSVal PtrEQ =
2547
90
    svalBuilder.evalEQ(State, arg0Val, svalBuilder.makeNull());
2548
2549
  // Get the size argument.
2550
90
  const Expr *Arg1 = CE->getArg(1);
2551
2552
  // Get the value of the size argument.
2553
90
  SVal TotalSize = C.getSVal(Arg1);
2554
90
  if (SuffixWithN)
2555
14
    TotalSize = evalMulForBufferSize(C, Arg1, CE->getArg(2));
2556
90
  if (!TotalSize.getAs<DefinedOrUnknownSVal>())
2557
0
    return nullptr;
2558
2559
  // Compare the size argument to 0.
2560
90
  DefinedOrUnknownSVal SizeZero =
2561
90
    svalBuilder.evalEQ(State, TotalSize.castAs<DefinedOrUnknownSVal>(),
2562
90
                       svalBuilder.makeIntValWithPtrWidth(0, false));
2563
2564
90
  ProgramStateRef StatePtrIsNull, StatePtrNotNull;
2565
90
  std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ);
2566
90
  ProgramStateRef StateSizeIsZero, StateSizeNotZero;
2567
90
  std::tie(StateSizeIsZero, StateSizeNotZero) = State->assume(SizeZero);
2568
  // We only assume exceptional states if they are definitely true; if the
2569
  // state is under-constrained, assume regular realloc behavior.
2570
90
  bool PrtIsNull = StatePtrIsNull && 
!StatePtrNotNull82
;
2571
90
  bool SizeIsZero = StateSizeIsZero && 
!StateSizeNotZero24
;
2572
2573
  // If the ptr is NULL and the size is not 0, the call is equivalent to
2574
  // malloc(size).
2575
90
  if (PrtIsNull && 
!SizeIsZero9
) {
2576
5
    ProgramStateRef stateMalloc = MallocMemAux(
2577
5
        C, Call, TotalSize, UndefinedVal(), StatePtrIsNull, Family);
2578
5
    return stateMalloc;
2579
5
  }
2580
2581
85
  if (PrtIsNull && 
SizeIsZero4
)
2582
4
    return State;
2583
2584
81
  assert(!PrtIsNull);
2585
2586
0
  bool IsKnownToBeAllocated = false;
2587
2588
  // If the size is 0, free the memory.
2589
81
  if (SizeIsZero)
2590
    // The semantics of the return value are:
2591
    // If size was equal to 0, either NULL or a pointer suitable to be passed
2592
    // to free() is returned. We just free the input pointer and do not add
2593
    // any constrains on the output pointer.
2594
17
    if (ProgramStateRef stateFree = FreeMemAux(
2595
17
            C, Call, StateSizeIsZero, 0, false, IsKnownToBeAllocated, Family))
2596
15
      return stateFree;
2597
2598
  // Default behavior.
2599
66
  if (ProgramStateRef stateFree =
2600
66
          FreeMemAux(C, Call, State, 0, false, IsKnownToBeAllocated, Family)) {
2601
2602
56
    ProgramStateRef stateRealloc =
2603
56
        MallocMemAux(C, Call, TotalSize, UnknownVal(), stateFree, Family);
2604
56
    if (!stateRealloc)
2605
0
      return nullptr;
2606
2607
56
    OwnershipAfterReallocKind Kind = OAR_ToBeFreedAfterFailure;
2608
56
    if (ShouldFreeOnFail)
2609
3
      Kind = OAR_FreeOnFailure;
2610
53
    else if (!IsKnownToBeAllocated)
2611
7
      Kind = OAR_DoNotTrackAfterFailure;
2612
2613
    // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
2614
56
    SymbolRef FromPtr = arg0Val.getLocSymbolInBase();
2615
56
    SVal RetVal = C.getSVal(CE);
2616
56
    SymbolRef ToPtr = RetVal.getAsSymbol();
2617
56
    assert(FromPtr && ToPtr &&
2618
56
           "By this point, FreeMemAux and MallocMemAux should have checked "
2619
56
           "whether the argument or the return value is symbolic!");
2620
2621
    // Record the info about the reallocated symbol so that we could properly
2622
    // process failed reallocation.
2623
0
    stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
2624
56
                                                   ReallocPair(FromPtr, Kind));
2625
    // The reallocated symbol should stay alive for as long as the new symbol.
2626
56
    C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
2627
56
    return stateRealloc;
2628
56
  }
2629
10
  return nullptr;
2630
66
}
2631
2632
ProgramStateRef MallocChecker::CallocMem(CheckerContext &C,
2633
                                         const CallEvent &Call,
2634
25
                                         ProgramStateRef State) {
2635
25
  if (!State)
2636
0
    return nullptr;
2637
2638
25
  if (Call.getNumArgs() < 2)
2639
0
    return nullptr;
2640
2641
25
  SValBuilder &svalBuilder = C.getSValBuilder();
2642
25
  SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
2643
25
  SVal TotalSize =
2644
25
      evalMulForBufferSize(C, Call.getArgExpr(0), Call.getArgExpr(1));
2645
2646
25
  return MallocMemAux(C, Call, TotalSize, zeroVal, State, AF_Malloc);
2647
25
}
2648
2649
MallocChecker::LeakInfo MallocChecker::getAllocationSite(const ExplodedNode *N,
2650
                                                         SymbolRef Sym,
2651
260
                                                         CheckerContext &C) {
2652
260
  const LocationContext *LeakContext = N->getLocationContext();
2653
  // Walk the ExplodedGraph backwards and find the first node that referred to
2654
  // the tracked symbol.
2655
260
  const ExplodedNode *AllocNode = N;
2656
260
  const MemRegion *ReferenceRegion = nullptr;
2657
2658
8.49k
  while (N) {
2659
8.49k
    ProgramStateRef State = N->getState();
2660
8.49k
    if (!State->get<RegionState>(Sym))
2661
260
      break;
2662
2663
    // Find the most recent expression bound to the symbol in the current
2664
    // context.
2665
8.23k
    if (!ReferenceRegion) {
2666
6.81k
      if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
2667
355
        SVal Val = State->getSVal(MR);
2668
355
        if (Val.getAsLocSymbol() == Sym) {
2669
242
          const VarRegion *VR = MR->getBaseRegion()->getAs<VarRegion>();
2670
          // Do not show local variables belonging to a function other than
2671
          // where the error is reported.
2672
242
          if (!VR || (VR->getStackFrame() == LeakContext->getStackFrame()))
2673
235
            ReferenceRegion = MR;
2674
242
        }
2675
355
      }
2676
6.81k
    }
2677
2678
    // Allocation node, is the last node in the current or parent context in
2679
    // which the symbol was tracked.
2680
8.23k
    const LocationContext *NContext = N->getLocationContext();
2681
8.23k
    if (NContext == LeakContext ||
2682
8.23k
        
NContext->isParentOf(LeakContext)811
)
2683
7.44k
      AllocNode = N;
2684
8.23k
    N = N->pred_empty() ? 
nullptr0
: *(N->pred_begin());
2685
8.23k
  }
2686
2687
260
  return LeakInfo(AllocNode, ReferenceRegion);
2688
260
}
2689
2690
void MallocChecker::HandleLeak(SymbolRef Sym, ExplodedNode *N,
2691
348
                               CheckerContext &C) const {
2692
2693
348
  if (!ChecksEnabled[CK_MallocChecker] &&
2694
348
      
!ChecksEnabled[CK_NewDeleteLeaksChecker]82
)
2695
19
    return;
2696
2697
329
  const RefState *RS = C.getState()->get<RegionState>(Sym);
2698
329
  assert(RS && "cannot leak an untracked symbol");
2699
0
  AllocationFamily Family = RS->getAllocationFamily();
2700
2701
329
  if (Family == AF_Alloca)
2702
38
    return;
2703
2704
291
  Optional<MallocChecker::CheckKind>
2705
291
      CheckKind = getCheckIfTracked(Family, true);
2706
2707
291
  if (!CheckKind.hasValue())
2708
31
    return;
2709
2710
260
  assert(N);
2711
260
  if (!BT_Leak[*CheckKind]) {
2712
    // Leaks should not be reported if they are post-dominated by a sink:
2713
    // (1) Sinks are higher importance bugs.
2714
    // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
2715
    //     with __noreturn functions such as assert() or exit(). We choose not
2716
    //     to report leaks on such paths.
2717
62
    BT_Leak[*CheckKind].reset(new BugType(CheckNames[*CheckKind], "Memory leak",
2718
62
                                          categories::MemoryError,
2719
62
                                          /*SuppressOnSink=*/true));
2720
62
  }
2721
2722
  // Most bug reports are cached at the location where they occurred.
2723
  // With leaks, we want to unique them by the location where they were
2724
  // allocated, and only report a single path.
2725
260
  PathDiagnosticLocation LocUsedForUniqueing;
2726
260
  const ExplodedNode *AllocNode = nullptr;
2727
260
  const MemRegion *Region = nullptr;
2728
260
  std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
2729
2730
260
  const Stmt *AllocationStmt = AllocNode->getStmtForDiagnostics();
2731
260
  if (AllocationStmt)
2732
260
    LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
2733
260
                                              C.getSourceManager(),
2734
260
                                              AllocNode->getLocationContext());
2735
2736
260
  SmallString<200> buf;
2737
260
  llvm::raw_svector_ostream os(buf);
2738
260
  if (Region && 
Region->canPrintPretty()235
) {
2739
231
    os << "Potential leak of memory pointed to by ";
2740
231
    Region->printPretty(os);
2741
231
  } else {
2742
29
    os << "Potential memory leak";
2743
29
  }
2744
2745
260
  auto R = std::make_unique<PathSensitiveBugReport>(
2746
260
      *BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
2747
260
      AllocNode->getLocationContext()->getDecl());
2748
260
  R->markInteresting(Sym);
2749
260
  R->addVisitor<MallocBugVisitor>(Sym, true);
2750
260
  if (ShouldRegisterNoOwnershipChangeVisitor)
2751
253
    R->addVisitor<NoOwnershipChangeVisitor>(Sym);
2752
260
  C.emitReport(std::move(R));
2753
260
}
2754
2755
void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
2756
                                     CheckerContext &C) const
2757
133k
{
2758
133k
  ProgramStateRef state = C.getState();
2759
133k
  RegionStateTy OldRS = state->get<RegionState>();
2760
133k
  RegionStateTy::Factory &F = state->get_context<RegionState>();
2761
2762
133k
  RegionStateTy RS = OldRS;
2763
133k
  SmallVector<SymbolRef, 2> Errors;
2764
145k
  for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; 
++I11.6k
) {
2765
11.6k
    if (SymReaper.isDead(I->first)) {
2766
1.17k
      if (I->second.isAllocated() || 
I->second.isAllocatedOfSizeZero()854
)
2767
348
        Errors.push_back(I->first);
2768
      // Remove the dead symbol from the map.
2769
1.17k
      RS = F.remove(RS, I->first);
2770
1.17k
    }
2771
11.6k
  }
2772
2773
133k
  if (RS == OldRS) {
2774
    // We shouldn't have touched other maps yet.
2775
132k
    assert(state->get<ReallocPairs>() ==
2776
132k
           C.getState()->get<ReallocPairs>());
2777
0
    assert(state->get<FreeReturnValue>() ==
2778
132k
           C.getState()->get<FreeReturnValue>());
2779
0
    return;
2780
132k
  }
2781
2782
  // Cleanup the Realloc Pairs Map.
2783
1.06k
  ReallocPairsTy RP = state->get<ReallocPairs>();
2784
1.19k
  for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; 
++I127
) {
2785
127
    if (SymReaper.isDead(I->first) ||
2786
127
        
SymReaper.isDead(I->second.ReallocatedSym)79
) {
2787
48
      state = state->remove<ReallocPairs>(I->first);
2788
48
    }
2789
127
  }
2790
2791
  // Cleanup the FreeReturnValue Map.
2792
1.06k
  FreeReturnValueTy FR = state->get<FreeReturnValue>();
2793
1.08k
  for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; 
++I18
) {
2794
18
    if (SymReaper.isDead(I->first) ||
2795
18
        
SymReaper.isDead(I->second)0
) {
2796
18
      state = state->remove<FreeReturnValue>(I->first);
2797
18
    }
2798
18
  }
2799
2800
  // Generate leak node.
2801
1.06k
  ExplodedNode *N = C.getPredecessor();
2802
1.06k
  if (!Errors.empty()) {
2803
344
    static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
2804
344
    N = C.generateNonFatalErrorNode(C.getState(), &Tag);
2805
344
    if (N) {
2806
344
      for (SmallVectorImpl<SymbolRef>::iterator
2807
692
           I = Errors.begin(), E = Errors.end(); I != E; 
++I348
) {
2808
348
        HandleLeak(*I, N, C);
2809
348
      }
2810
344
    }
2811
344
  }
2812
2813
1.06k
  C.addTransition(state->set<RegionState>(RS), N);
2814
1.06k
}
2815
2816
void MallocChecker::checkPreCall(const CallEvent &Call,
2817
41.9k
                                 CheckerContext &C) const {
2818
2819
41.9k
  if (const auto *DC = dyn_cast<CXXDeallocatorCall>(&Call)) {
2820
378
    const CXXDeleteExpr *DE = DC->getOriginExpr();
2821
2822
378
    if (!ChecksEnabled[CK_NewDeleteChecker])
2823
170
      if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
2824
132
        checkUseAfterFree(Sym, C, DE->getArgument());
2825
2826
378
    if (!isStandardNewDelete(DC->getDecl()))
2827
0
      return;
2828
2829
378
    ProgramStateRef State = C.getState();
2830
378
    bool IsKnownToBeAllocated;
2831
378
    State = FreeMemAux(C, DE->getArgument(), Call, State,
2832
378
                       /*Hold*/ false, IsKnownToBeAllocated,
2833
378
                       (DE->isArrayForm() ? 
AF_CXXNewArray64
:
AF_CXXNew314
));
2834
2835
378
    C.addTransition(State);
2836
378
    return;
2837
378
  }
2838
2839
41.6k
  if (const auto *DC = dyn_cast<CXXDestructorCall>(&Call)) {
2840
775
    SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
2841
775
    if (!Sym || 
checkDoubleDelete(Sym, C)64
)
2842
723
      return;
2843
775
  }
2844
2845
  // We will check for double free in the post visit.
2846
40.8k
  if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
2847
40.7k
    const FunctionDecl *FD = FC->getDecl();
2848
40.7k
    if (!FD)
2849
9
      return;
2850
2851
40.7k
    if (ChecksEnabled[CK_MallocChecker] && 
isFreeingCall(Call)9.16k
)
2852
671
      return;
2853
40.7k
  }
2854
2855
  // Check if the callee of a method is deleted.
2856
40.1k
  if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
2857
5.39k
    SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
2858
5.39k
    if (!Sym || 
checkUseAfterFree(Sym, C, CC->getCXXThisExpr())3.40k
)
2859
1.99k
      return;
2860
5.39k
  }
2861
2862
  // Check arguments for being used after free.
2863
74.8k
  
for (unsigned I = 0, E = Call.getNumArgs(); 38.2k
I != E;
++I36.6k
) {
2864
36.8k
    SVal ArgSVal = Call.getArgSVal(I);
2865
36.8k
    if (ArgSVal.getAs<Loc>()) {
2866
20.7k
      SymbolRef Sym = ArgSVal.getAsSymbol();
2867
20.7k
      if (!Sym)
2868
15.1k
        continue;
2869
5.61k
      if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
2870
109
        return;
2871
5.61k
    }
2872
36.8k
  }
2873
38.2k
}
2874
2875
void MallocChecker::checkPreStmt(const ReturnStmt *S,
2876
7.01k
                                 CheckerContext &C) const {
2877
7.01k
  checkEscapeOnReturn(S, C);
2878
7.01k
}
2879
2880
// In the CFG, automatic destructors come after the return statement.
2881
// This callback checks for returning memory that is freed by automatic
2882
// destructors, as those cannot be reached in checkPreStmt().
2883
void MallocChecker::checkEndFunction(const ReturnStmt *S,
2884
22.2k
                                     CheckerContext &C) const {
2885
22.2k
  checkEscapeOnReturn(S, C);
2886
22.2k
}
2887
2888
void MallocChecker::checkEscapeOnReturn(const ReturnStmt *S,
2889
29.2k
                                        CheckerContext &C) const {
2890
29.2k
  if (!S)
2891
15.2k
    return;
2892
2893
13.9k
  const Expr *E = S->getRetValue();
2894
13.9k
  if (!E)
2895
249
    return;
2896
2897
  // Check if we are returning a symbol.
2898
13.7k
  ProgramStateRef State = C.getState();
2899
13.7k
  SVal RetVal = C.getSVal(E);
2900
13.7k
  SymbolRef Sym = RetVal.getAsSymbol();
2901
13.7k
  if (!Sym)
2902
    // If we are returning a field of the allocated struct or an array element,
2903
    // the callee could still free the memory.
2904
    // TODO: This logic should be a part of generic symbol escape callback.
2905
12.8k
    if (const MemRegion *MR = RetVal.getAsRegion())
2906
742
      if (isa<FieldRegion, ElementRegion>(MR))
2907
294
        if (const SymbolicRegion *BMR =
2908
294
              dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
2909
70
          Sym = BMR->getSymbol();
2910
2911
  // Check if we are returning freed memory.
2912
13.7k
  if (Sym)
2913
973
    checkUseAfterFree(Sym, C, E);
2914
13.7k
}
2915
2916
// TODO: Blocks should be either inlined or should call invalidate regions
2917
// upon invocation. After that's in place, special casing here will not be
2918
// needed.
2919
void MallocChecker::checkPostStmt(const BlockExpr *BE,
2920
56
                                  CheckerContext &C) const {
2921
2922
  // Scan the BlockDecRefExprs for any object the retain count checker
2923
  // may be tracking.
2924
56
  if (!BE->getBlockDecl()->hasCaptures())
2925
51
    return;
2926
2927
5
  ProgramStateRef state = C.getState();
2928
5
  const BlockDataRegion *R =
2929
5
    cast<BlockDataRegion>(C.getSVal(BE).getAsRegion());
2930
2931
5
  BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2932
5
                                            E = R->referenced_vars_end();
2933
2934
5
  if (I == E)
2935
0
    return;
2936
2937
5
  SmallVector<const MemRegion*, 10> Regions;
2938
5
  const LocationContext *LC = C.getLocationContext();
2939
5
  MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2940
2941
10
  for ( ; I != E; 
++I5
) {
2942
5
    const VarRegion *VR = I.getCapturedRegion();
2943
5
    if (VR->getSuperRegion() == R) {
2944
1
      VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2945
1
    }
2946
5
    Regions.push_back(VR);
2947
5
  }
2948
2949
5
  state =
2950
5
    state->scanReachableSymbols<StopTrackingCallback>(Regions).getState();
2951
5
  C.addTransition(state);
2952
5
}
2953
2954
23.8k
static bool isReleased(SymbolRef Sym, CheckerContext &C) {
2955
23.8k
  assert(Sym);
2956
0
  const RefState *RS = C.getState()->get<RegionState>(Sym);
2957
23.8k
  return (RS && 
RS->isReleased()2.12k
);
2958
23.8k
}
2959
2960
bool MallocChecker::suppressDeallocationsInSuspiciousContexts(
2961
531
    const CallEvent &Call, CheckerContext &C) const {
2962
531
  if (Call.getNumArgs() == 0)
2963
0
    return false;
2964
2965
531
  StringRef FunctionStr = "";
2966
531
  if (const auto *FD = dyn_cast<FunctionDecl>(C.getStackFrame()->getDecl()))
2967
528
    if (const Stmt *Body = FD->getBody())
2968
528
      if (Body->getBeginLoc().isValid())
2969
528
        FunctionStr =
2970
528
            Lexer::getSourceText(CharSourceRange::getTokenRange(
2971
528
                                     {FD->getBeginLoc(), Body->getBeginLoc()}),
2972
528
                                 C.getSourceManager(), C.getLangOpts());
2973
2974
  // We do not model the Integer Set Library's retain-count based allocation.
2975
531
  if (!FunctionStr.contains("__isl_"))
2976
530
    return false;
2977
2978
1
  ProgramStateRef State = C.getState();
2979
2980
1
  for (const Expr *Arg : cast<CallExpr>(Call.getOriginExpr())->arguments())
2981
1
    if (SymbolRef Sym = C.getSVal(Arg).getAsSymbol())
2982
1
      if (const RefState *RS = State->get<RegionState>(Sym))
2983
0
        State = State->set<RegionState>(Sym, RefState::getEscaped(RS));
2984
2985
1
  C.addTransition(State);
2986
1
  return true;
2987
531
}
2988
2989
bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
2990
23.7k
                                      const Stmt *S) const {
2991
2992
23.7k
  if (isReleased(Sym, C)) {
2993
179
    HandleUseAfterFree(C, S->getSourceRange(), Sym);
2994
179
    return true;
2995
179
  }
2996
2997
23.5k
  return false;
2998
23.7k
}
2999
3000
void MallocChecker::checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
3001
13.6k
                                          const Stmt *S) const {
3002
13.6k
  assert(Sym);
3003
3004
13.6k
  if (const RefState *RS = C.getState()->get<RegionState>(Sym)) {
3005
630
    if (RS->isAllocatedOfSizeZero())
3006
32
      HandleUseZeroAlloc(C, RS->getStmt()->getSourceRange(), Sym);
3007
630
  }
3008
13.0k
  else if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym)) {
3009
4
    HandleUseZeroAlloc(C, S->getSourceRange(), Sym);
3010
4
  }
3011
13.6k
}
3012
3013
64
bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
3014
3015
64
  if (isReleased(Sym, C)) {
3016
12
    HandleDoubleDelete(C, Sym);
3017
12
    return true;
3018
12
  }
3019
52
  return false;
3020
64
}
3021
3022
// Check if the location is a freed symbolic region.
3023
void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
3024
75.8k
                                  CheckerContext &C) const {
3025
75.8k
  SymbolRef Sym = l.getLocSymbolInBase();
3026
75.8k
  if (Sym) {
3027
13.6k
    checkUseAfterFree(Sym, C, S);
3028
13.6k
    checkUseZeroAllocated(Sym, C, S);
3029
13.6k
  }
3030
75.8k
}
3031
3032
// If a symbolic region is assumed to NULL (or another constant), stop tracking
3033
// it - assuming that allocation failed on this path.
3034
ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
3035
                                              SVal Cond,
3036
174k
                                              bool Assumption) const {
3037
174k
  RegionStateTy RS = state->get<RegionState>();
3038
187k
  for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; 
++I13.1k
) {
3039
    // If the symbol is assumed to be NULL, remove it from consideration.
3040
13.1k
    ConstraintManager &CMgr = state->getConstraintManager();
3041
13.1k
    ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
3042
13.1k
    if (AllocFailed.isConstrainedTrue())
3043
714
      state = state->remove<RegionState>(I.getKey());
3044
13.1k
  }
3045
3046
  // Realloc returns 0 when reallocation fails, which means that we should
3047
  // restore the state of the pointer being reallocated.
3048
174k
  ReallocPairsTy RP = state->get<ReallocPairs>();
3049
175k
  for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; 
++I835
) {
3050
    // If the symbol is assumed to be NULL, remove it from consideration.
3051
835
    ConstraintManager &CMgr = state->getConstraintManager();
3052
835
    ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
3053
835
    if (!AllocFailed.isConstrainedTrue())
3054
796
      continue;
3055
3056
39
    SymbolRef ReallocSym = I.getData().ReallocatedSym;
3057
39
    if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
3058
39
      if (RS->isReleased()) {
3059
39
        switch (I.getData().Kind) {
3060
32
        case OAR_ToBeFreedAfterFailure:
3061
32
          state = state->set<RegionState>(ReallocSym,
3062
32
              RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
3063
32
          break;
3064
5
        case OAR_DoNotTrackAfterFailure:
3065
5
          state = state->remove<RegionState>(ReallocSym);
3066
5
          break;
3067
2
        default:
3068
2
          assert(I.getData().Kind == OAR_FreeOnFailure);
3069
39
        }
3070
39
      }
3071
39
    }
3072
39
    state = state->remove<ReallocPairs>(I.getKey());
3073
39
  }
3074
3075
174k
  return state;
3076
174k
}
3077
3078
bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
3079
                                              const CallEvent *Call,
3080
                                              ProgramStateRef State,
3081
2.86k
                                              SymbolRef &EscapingSymbol) const {
3082
2.86k
  assert(Call);
3083
0
  EscapingSymbol = nullptr;
3084
3085
  // For now, assume that any C++ or block call can free memory.
3086
  // TODO: If we want to be more optimistic here, we'll need to make sure that
3087
  // regions escape to C++ containers. They seem to do that even now, but for
3088
  // mysterious reasons.
3089
2.86k
  if (!isa<SimpleFunctionCall, ObjCMethodCall>(Call))
3090
1.79k
    return true;
3091
3092
  // Check Objective-C messages by selector name.
3093
1.07k
  if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
3094
    // If it's not a framework call, or if it takes a callback, assume it
3095
    // can free memory.
3096
69
    if (!Call->isInSystemHeader() || 
Call->argumentsMayEscape()58
)
3097
13
      return true;
3098
3099
    // If it's a method we know about, handle it explicitly post-call.
3100
    // This should happen before the "freeWhenDone" check below.
3101
56
    if (isKnownDeallocObjCMethodName(*Msg))
3102
31
      return false;
3103
3104
    // If there's a "freeWhenDone" parameter, but the method isn't one we know
3105
    // about, we can't be sure that the object will use free() to deallocate the
3106
    // memory, so we can't model it explicitly. The best we can do is use it to
3107
    // decide whether the pointer escapes.
3108
25
    if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
3109
4
      return *FreeWhenDone;
3110
3111
    // If the first selector piece ends with "NoCopy", and there is no
3112
    // "freeWhenDone" parameter set to zero, we know ownership is being
3113
    // transferred. Again, though, we can't be sure that the object will use
3114
    // free() to deallocate the memory, so we can't model it explicitly.
3115
21
    StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
3116
21
    if (FirstSlot.endswith("NoCopy"))
3117
1
      return true;
3118
3119
    // If the first selector starts with addPointer, insertPointer,
3120
    // or replacePointer, assume we are dealing with NSPointerArray or similar.
3121
    // This is similar to C++ containers (vector); we still might want to check
3122
    // that the pointers get freed by following the container itself.
3123
20
    if (FirstSlot.startswith("addPointer") ||
3124
20
        
FirstSlot.startswith("insertPointer")19
||
3125
20
        
FirstSlot.startswith("replacePointer")17
||
3126
20
        
FirstSlot.equals("valueWithPointer")14
) {
3127
6
      return true;
3128
6
    }
3129
3130
    // We should escape receiver on call to 'init'. This is especially relevant
3131
    // to the receiver, as the corresponding symbol is usually not referenced
3132
    // after the call.
3133
14
    if (Msg->getMethodFamily() == OMF_init) {
3134
8
      EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
3135
8
      return true;
3136
8
    }
3137
3138
    // Otherwise, assume that the method does not free memory.
3139
    // Most framework methods do not free memory.
3140
6
    return false;
3141
14
  }
3142
3143
  // At this point the only thing left to handle is straight function calls.
3144
1.00k
  const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
3145
1.00k
  if (!FD)
3146
0
    return true;
3147
3148
  // If it's one of the allocation functions we can reason about, we model
3149
  // its behavior explicitly.
3150
1.00k
  if (isMemCall(*Call))
3151
556
    return false;
3152
3153
  // If it's not a system call, assume it frees memory.
3154
446
  if (!Call->isInSystemHeader())
3155
383
    return true;
3156
3157
  // White list the system functions whose arguments escape.
3158
63
  const IdentifierInfo *II = FD->getIdentifier();
3159
63
  if (!II)
3160
25
    return true;
3161
38
  StringRef FName = II->getName();
3162
3163
  // White list the 'XXXNoCopy' CoreFoundation functions.
3164
  // We specifically check these before
3165
38
  if (FName.endswith("NoCopy")) {
3166
    // Look for the deallocator argument. We know that the memory ownership
3167
    // is not transferred only if the deallocator argument is
3168
    // 'kCFAllocatorNull'.
3169
8
    for (unsigned i = 1; i < Call->getNumArgs(); 
++i6
) {
3170
7
      const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
3171
7
      if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
3172
4
        StringRef DeallocatorName = DE->getFoundDecl()->getName();
3173
4
        if (DeallocatorName == "kCFAllocatorNull")
3174
1
          return false;
3175
4
      }
3176
7
    }
3177
1
    return true;
3178
2
  }
3179
3180
  // Associating streams with malloced buffers. The pointer can escape if
3181
  // 'closefn' is specified (and if that function does free memory),
3182
  // but it will not if closefn is not specified.
3183
  // Currently, we do not inspect the 'closefn' function (PR12101).
3184
36
  if (FName == "funopen")
3185
3
    if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
3186
2
      return false;
3187
3188
  // Do not warn on pointers passed to 'setbuf' when used with std streams,
3189
  // these leaks might be intentional when setting the buffer for stdio.
3190
  // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
3191
34
  if (FName == "setbuf" || 
FName =="setbuffer"33
||
3192
34
      
FName == "setlinebuf"33
||
FName == "setvbuf"33
) {
3193
3
    if (Call->getNumArgs() >= 1) {
3194
3
      const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
3195
3
      if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
3196
3
        if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
3197
3
          if (D->getCanonicalDecl()->getName().contains("std"))
3198
2
            return true;
3199
3
    }
3200
3
  }
3201
3202
  // A bunch of other functions which either take ownership of a pointer or
3203
  // wrap the result up in a struct or object, meaning it can be freed later.
3204
  // (See RetainCountChecker.) Not all the parameters here are invalidated,
3205
  // but the Malloc checker cannot differentiate between them. The right way
3206
  // of doing this would be to implement a pointer escapes callback.
3207
32
  if (FName == "CGBitmapContextCreate" ||
3208
32
      
FName == "CGBitmapContextCreateWithData"30
||
3209
32
      
FName == "CVPixelBufferCreateWithBytes"30
||
3210
32
      
FName == "CVPixelBufferCreateWithPlanarBytes"30
||
3211
32
      
FName == "OSAtomicEnqueue"30
) {
3212
2
    return true;
3213
2
  }
3214
3215
30
  if (FName == "postEvent" &&
3216
30
      
FD->getQualifiedNameAsString() == "QCoreApplication::postEvent"4
) {
3217
4
    return true;
3218
4
  }
3219
3220
26
  if (FName == "connectImpl" &&
3221
26
      
FD->getQualifiedNameAsString() == "QObject::connectImpl"1
) {
3222
1
    return true;
3223
1
  }
3224
3225
  // Handle cases where we know a buffer's /address/ can escape.
3226
  // Note that the above checks handle some special cases where we know that
3227
  // even though the address escapes, it's still our responsibility to free the
3228
  // buffer.
3229
25
  if (Call->argumentsMayEscape())
3230
15
    return true;
3231
3232
  // Otherwise, assume that the function does not free memory.
3233
  // Most system calls do not free the memory.
3234
10
  return false;
3235
25
}
3236
3237
ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
3238
                                             const InvalidatedSymbols &Escaped,
3239
                                             const CallEvent *Call,
3240
13.9k
                                             PointerEscapeKind Kind) const {
3241
13.9k
  return checkPointerEscapeAux(State, Escaped, Call, Kind,
3242
13.9k
                               /*IsConstPointerEscape*/ false);
3243
13.9k
}
3244
3245
ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
3246
                                              const InvalidatedSymbols &Escaped,
3247
                                              const CallEvent *Call,
3248
1.33k
                                              PointerEscapeKind Kind) const {
3249
  // If a const pointer escapes, it may not be freed(), but it could be deleted.
3250
1.33k
  return checkPointerEscapeAux(State, Escaped, Call, Kind,
3251
1.33k
                               /*IsConstPointerEscape*/ true);
3252
1.33k
}
3253
3254
44
static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
3255
44
  return (RS->getAllocationFamily() == AF_CXXNewArray ||
3256
44
          
RS->getAllocationFamily() == AF_CXXNew43
);
3257
44
}
3258
3259
ProgramStateRef MallocChecker::checkPointerEscapeAux(
3260
    ProgramStateRef State, const InvalidatedSymbols &Escaped,
3261
    const CallEvent *Call, PointerEscapeKind Kind,
3262
15.2k
    bool IsConstPointerEscape) const {
3263
  // If we know that the call does not free memory, or we want to process the
3264
  // call later, keep tracking the top level arguments.
3265
15.2k
  SymbolRef EscapingSymbol = nullptr;
3266
15.2k
  if (Kind == PSK_DirectEscapeOnCall &&
3267
15.2k
      !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
3268
2.86k
                                                    EscapingSymbol) &&
3269
15.2k
      
!EscapingSymbol608
) {
3270
608
    return State;
3271
608
  }
3272
3273
14.6k
  for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
3274
14.6k
       E = Escaped.end();
3275
46.4k
       I != E; 
++I31.7k
) {
3276
31.7k
    SymbolRef sym = *I;
3277
3278
31.7k
    if (EscapingSymbol && 
EscapingSymbol != sym9
)
3279
1
      continue;
3280
3281
31.7k
    if (const RefState *RS = State->get<RegionState>(sym))
3282
549
      if (RS->isAllocated() || 
RS->isAllocatedOfSizeZero()116
)
3283
435
        if (!IsConstPointerEscape || 
checkIfNewOrNewArrayFamily(RS)44
)
3284
420
          State = State->set<RegionState>(sym, RefState::getEscaped(RS));
3285
31.7k
  }
3286
14.6k
  return State;
3287
15.2k
}
3288
3289
bool MallocChecker::isArgZERO_SIZE_PTR(ProgramStateRef State, CheckerContext &C,
3290
14
                                       SVal ArgVal) const {
3291
14
  if (!KernelZeroSizePtrValue)
3292
5
    KernelZeroSizePtrValue =
3293
5
        tryExpandAsInteger("ZERO_SIZE_PTR", C.getPreprocessor());
3294
3295
14
  const llvm::APSInt *ArgValKnown =
3296
14
      C.getSValBuilder().getKnownValue(State, ArgVal);
3297
14
  return ArgValKnown && 
*KernelZeroSizePtrValue8
&&
3298
14
         
ArgValKnown->getSExtValue() == **KernelZeroSizePtrValue2
;
3299
14
}
3300
3301
static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
3302
6
                                         ProgramStateRef prevState) {
3303
6
  ReallocPairsTy currMap = currState->get<ReallocPairs>();
3304
6
  ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
3305
3306
6
  for (const ReallocPairsTy::value_type &Pair : prevMap) {
3307
6
    SymbolRef sym = Pair.first;
3308
6
    if (!currMap.lookup(sym))
3309
6
      return sym;
3310
6
  }
3311
3312
0
  return nullptr;
3313
6
}
3314
3315
25
static bool isReferenceCountingPointerDestructor(const CXXDestructorDecl *DD) {
3316
25
  if (const IdentifierInfo *II = DD->getParent()->getIdentifier()) {
3317
25
    StringRef N = II->getName();
3318
25
    if (N.contains_insensitive("ptr") || 
N.contains_insensitive("pointer")17
) {
3319
16
      if (N.contains_insensitive("ref") || N.contains_insensitive("cnt") ||
3320
16
          N.contains_insensitive("intrusive") ||
3321
16
          
N.contains_insensitive("shared")8
) {
3322
8
        return true;
3323
8
      }
3324
16
    }
3325
25
  }
3326
17
  return false;
3327
25
}
3328
3329
PathDiagnosticPieceRef MallocBugVisitor::VisitNode(const ExplodedNode *N,
3330
                                                   BugReporterContext &BRC,
3331
25.4k
                                                   PathSensitiveBugReport &BR) {
3332
25.4k
  ProgramStateRef state = N->getState();
3333
25.4k
  ProgramStateRef statePrev = N->getFirstPred()->getState();
3334
3335
25.4k
  const RefState *RSCurr = state->get<RegionState>(Sym);
3336
25.4k
  const RefState *RSPrev = statePrev->get<RegionState>(Sym);
3337
3338
25.4k
  const Stmt *S = N->getStmtForDiagnostics();
3339
  // When dealing with containers, we sometimes want to give a note
3340
  // even if the statement is missing.
3341
25.4k
  if (!S && 
(1.69k
!RSCurr1.69k
||
RSCurr->getAllocationFamily() != AF_InnerBuffer825
))
3342
1.67k
    return nullptr;
3343
3344
23.8k
  const LocationContext *CurrentLC = N->getLocationContext();
3345
3346
  // If we find an atomic fetch_add or fetch_sub within the destructor in which
3347
  // the pointer was released (before the release), this is likely a destructor
3348
  // of a shared pointer.
3349
  // Because we don't model atomics, and also because we don't know that the
3350
  // original reference count is positive, we should not report use-after-frees
3351
  // on objects deleted in such destructors. This can probably be improved
3352
  // through better shared pointer modeling.
3353
23.8k
  if (ReleaseDestructorLC) {
3354
835
    if (const auto *AE = dyn_cast<AtomicExpr>(S)) {
3355
0
      AtomicExpr::AtomicOp Op = AE->getOp();
3356
0
      if (Op == AtomicExpr::AO__c11_atomic_fetch_add ||
3357
0
          Op == AtomicExpr::AO__c11_atomic_fetch_sub) {
3358
0
        if (ReleaseDestructorLC == CurrentLC ||
3359
0
            ReleaseDestructorLC->isParentOf(CurrentLC)) {
3360
0
          BR.markInvalid(getTag(), S);
3361
0
        }
3362
0
      }
3363
0
    }
3364
835
  }
3365
3366
  // FIXME: We will eventually need to handle non-statement-based events
3367
  // (__attribute__((cleanup))).
3368
3369
  // Find out if this is an interesting point and what is the kind.
3370
23.8k
  StringRef Msg;
3371
23.8k
  std::unique_ptr<StackHintGeneratorForSymbol> StackHint = nullptr;
3372
23.8k
  SmallString<256> Buf;
3373
23.8k
  llvm::raw_svector_ostream OS(Buf);
3374
3375
23.8k
  if (Mode == Normal) {
3376
23.7k
    if (isAllocated(RSCurr, RSPrev, S)) {
3377
416
      Msg = "Memory is allocated";
3378
416
      StackHint = std::make_unique<StackHintGeneratorForSymbol>(
3379
416
          Sym, "Returned allocated memory");
3380
23.3k
    } else if (isReleased(RSCurr, RSPrev, S)) {
3381
172
      const auto Family = RSCurr->getAllocationFamily();
3382
172
      switch (Family) {
3383
0
        case AF_Alloca:
3384
73
        case AF_Malloc:
3385
140
        case AF_CXXNew:
3386
141
        case AF_CXXNewArray:
3387
141
        case AF_IfNameIndex:
3388
141
          Msg = "Memory is released";
3389
141
          StackHint = std::make_unique<StackHintGeneratorForSymbol>(
3390
141
              Sym, "Returning; memory was released");
3391
141
          break;
3392
31
        case AF_InnerBuffer: {
3393
31
          const MemRegion *ObjRegion =
3394
31
              allocation_state::getContainerObjRegion(statePrev, Sym);
3395
31
          const auto *TypedRegion = cast<TypedValueRegion>(ObjRegion);
3396
31
          QualType ObjTy = TypedRegion->getValueType();
3397
31
          OS << "Inner buffer of '" << ObjTy.getAsString() << "' ";
3398
3399
31
          if (N->getLocation().getKind() == ProgramPoint::PostImplicitCallKind) {
3400
12
            OS << "deallocated by call to destructor";
3401
12
            StackHint = std::make_unique<StackHintGeneratorForSymbol>(
3402
12
                Sym, "Returning; inner buffer was deallocated");
3403
19
          } else {
3404
19
            OS << "reallocated by call to '";
3405
19
            const Stmt *S = RSCurr->getStmt();
3406
19
            if (const auto *MemCallE = dyn_cast<CXXMemberCallExpr>(S)) {
3407
14
              OS << MemCallE->getMethodDecl()->getDeclName();
3408
14
            } else 
if (const auto *5
OpCallE5
= dyn_cast<CXXOperatorCallExpr>(S)) {
3409
2
              OS << OpCallE->getDirectCallee()->getDeclName();
3410
3
            } else if (const auto *CallE = dyn_cast<CallExpr>(S)) {
3411
3
              auto &CEMgr = BRC.getStateManager().getCallEventManager();
3412
3
              CallEventRef<> Call = CEMgr.getSimpleCall(CallE, state, CurrentLC);
3413
3
              if (const auto *D = dyn_cast_or_null<NamedDecl>(Call->getDecl()))
3414
3
                OS << D->getDeclName();
3415
0
              else
3416
0
                OS << "unknown";
3417
3
            }
3418
19
            OS << "'";
3419
19
            StackHint = std::make_unique<StackHintGeneratorForSymbol>(
3420
19
                Sym, "Returning; inner buffer was reallocated");
3421
19
          }
3422
31
          Msg = OS.str();
3423
31
          break;
3424
141
        }
3425
0
        case AF_None:
3426
0
          llvm_unreachable("Unhandled allocation family!");
3427
172
      }
3428
3429
      // See if we're releasing memory while inlining a destructor
3430
      // (or one of its callees). This turns on various common
3431
      // false positive suppressions.
3432
172
      bool FoundAnyDestructor = false;
3433
383
      for (const LocationContext *LC = CurrentLC; LC; 
LC = LC->getParent()211
) {
3434
211
        if (const auto *DD = dyn_cast<CXXDestructorDecl>(LC->getDecl())) {
3435
25
          if (isReferenceCountingPointerDestructor(DD)) {
3436
            // This immediately looks like a reference-counting destructor.
3437
            // We're bad at guessing the original reference count of the object,
3438
            // so suppress the report for now.
3439
8
            BR.markInvalid(getTag(), DD);
3440
17
          } else if (!FoundAnyDestructor) {
3441
11
            assert(!ReleaseDestructorLC &&
3442
11
                   "There can be only one release point!");
3443
            // Suspect that it's a reference counting pointer destructor.
3444
            // On one of the next nodes might find out that it has atomic
3445
            // reference counting operations within it (see the code above),
3446
            // and if so, we'd conclude that it likely is a reference counting
3447
            // pointer destructor.
3448
0
            ReleaseDestructorLC = LC->getStackFrame();
3449
            // It is unlikely that releasing memory is delegated to a destructor
3450
            // inside a destructor of a shared pointer, because it's fairly hard
3451
            // to pass the information that the pointer indeed needs to be
3452
            // released into it. So we're only interested in the innermost
3453
            // destructor.
3454
11
            FoundAnyDestructor = true;
3455
11
          }
3456
25
        }
3457
211
      }
3458
23.1k
    } else if (isRelinquished(RSCurr, RSPrev, S)) {
3459
6
      Msg = "Memory ownership is transferred";
3460
6
      StackHint = std::make_unique<StackHintGeneratorForSymbol>(Sym, "");
3461
23.1k
    } else if (hasReallocFailed(RSCurr, RSPrev, S)) {
3462
6
      Mode = ReallocationFailed;
3463
6
      Msg = "Reallocation failed";
3464
6
      StackHint = std::make_unique<StackHintGeneratorForReallocationFailed>(
3465
6
          Sym, "Reallocation failed");
3466
3467
6
      if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
3468
        // Is it possible to fail two reallocs WITHOUT testing in between?
3469
6
        assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
3470
6
          "We only support one failed realloc at a time.");
3471
0
        BR.markInteresting(sym);
3472
6
        FailedReallocSymbol = sym;
3473
6
      }
3474
6
    }
3475
3476
  // We are in a special mode if a reallocation failed later in the path.
3477
23.7k
  } else 
if (73
Mode == ReallocationFailed73
) {
3478
73
    assert(FailedReallocSymbol && "No symbol to look for.");
3479
3480
    // Is this is the first appearance of the reallocated symbol?
3481
73
    if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
3482
      // We're at the reallocation point.
3483
6
      Msg = "Attempt to reallocate memory";
3484
6
      StackHint = std::make_unique<StackHintGeneratorForSymbol>(
3485
6
          Sym, "Returned reallocated memory");
3486
6
      FailedReallocSymbol = nullptr;
3487
6
      Mode = Normal;
3488
6
    }
3489
73
  }
3490
3491
23.8k
  if (Msg.empty()) {
3492
23.1k
    assert(!StackHint);
3493
0
    return nullptr;
3494
23.1k
  }
3495
3496
606
  assert(StackHint);
3497
3498
  // Generate the extra diagnostic.
3499
0
  PathDiagnosticLocation Pos;
3500
606
  if (!S) {
3501
12
    assert(RSCurr->getAllocationFamily() == AF_InnerBuffer);
3502
0
    auto PostImplCall = N->getLocation().getAs<PostImplicitCall>();
3503
12
    if (!PostImplCall)
3504
0
      return nullptr;
3505
12
    Pos = PathDiagnosticLocation(PostImplCall->getLocation(),
3506
12
                                 BRC.getSourceManager());
3507
594
  } else {
3508
594
    Pos = PathDiagnosticLocation(S, BRC.getSourceManager(),
3509
594
                                 N->getLocationContext());
3510
594
  }
3511
3512
606
  auto P = std::make_shared<PathDiagnosticEventPiece>(Pos, Msg, true);
3513
606
  BR.addCallStackHint(P, std::move(StackHint));
3514
606
  return P;
3515
606
}
3516
3517
void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
3518
36
                               const char *NL, const char *Sep) const {
3519
3520
36
  RegionStateTy RS = State->get<RegionState>();
3521
3522
36
  if (!RS.isEmpty()) {
3523
0
    Out << Sep << "MallocChecker :" << NL;
3524
0
    for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
3525
0
      const RefState *RefS = State->get<RegionState>(I.getKey());
3526
0
      AllocationFamily Family = RefS->getAllocationFamily();
3527
0
      Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
3528
0
      if (!CheckKind.hasValue())
3529
0
         CheckKind = getCheckIfTracked(Family, true);
3530
3531
0
      I.getKey()->dumpToStream(Out);
3532
0
      Out << " : ";
3533
0
      I.getData().dump(Out);
3534
0
      if (CheckKind.hasValue())
3535
0
        Out << " (" << CheckNames[*CheckKind].getName() << ")";
3536
0
      Out << NL;
3537
0
    }
3538
0
  }
3539
36
}
3540
3541
namespace clang {
3542
namespace ento {
3543
namespace allocation_state {
3544
3545
ProgramStateRef
3546
39
markReleased(ProgramStateRef State, SymbolRef Sym, const Expr *Origin) {
3547
39
  AllocationFamily Family = AF_InnerBuffer;
3548
39
  return State->set<RegionState>(Sym, RefState::getReleased(Family, Origin));
3549
39
}
3550
3551
} // end namespace allocation_state
3552
} // end namespace ento
3553
} // end namespace clang
3554
3555
// Intended to be used in InnerPointerChecker to register the part of
3556
// MallocChecker connected to it.
3557
66
void ento::registerInnerPointerCheckerAux(CheckerManager &mgr) {
3558
66
  MallocChecker *checker = mgr.getChecker<MallocChecker>();
3559
66
  checker->ChecksEnabled[MallocChecker::CK_InnerPointerChecker] = true;
3560
66
  checker->CheckNames[MallocChecker::CK_InnerPointerChecker] =
3561
66
      mgr.getCurrentCheckerName();
3562
66
}
3563
3564
239
void ento::registerDynamicMemoryModeling(CheckerManager &mgr) {
3565
239
  auto *checker = mgr.registerChecker<MallocChecker>();
3566
239
  checker->ShouldIncludeOwnershipAnnotatedFunctions =
3567
239
      mgr.getAnalyzerOptions().getCheckerBooleanOption(checker, "Optimistic");
3568
239
  checker->ShouldRegisterNoOwnershipChangeVisitor =
3569
239
      mgr.getAnalyzerOptions().getCheckerBooleanOption(
3570
239
          checker, "AddNoOwnershipChangeNotes");
3571
239
}
3572
3573
1.24k
bool ento::shouldRegisterDynamicMemoryModeling(const CheckerManager &mgr) {
3574
1.24k
  return true;
3575
1.24k
}
3576
3577
#define REGISTER_CHECKER(name)                                                 \
3578
419
  void ento::register##name(CheckerManager &mgr) {                             \
3579
419
    MallocChecker *checker = mgr.getChecker<MallocChecker>();                  \
3580
419
    checker->ChecksEnabled[MallocChecker::CK_##name] = true;                   \
3581
419
    checker->CheckNames[MallocChecker::CK_##name] =                            \
3582
419
        mgr.getCurrentCheckerName();                                           \
3583
419
  }                                                                            \
clang::ento::registerMallocChecker(clang::ento::CheckerManager&)
Line
Count
Source
3578
154
  void ento::register##name(CheckerManager &mgr) {                             \
3579
154
    MallocChecker *checker = mgr.getChecker<MallocChecker>();                  \
3580
154
    checker->ChecksEnabled[MallocChecker::CK_##name] = true;                   \
3581
154
    checker->CheckNames[MallocChecker::CK_##name] =                            \
3582
154
        mgr.getCurrentCheckerName();                                           \
3583
154
  }                                                                            \
clang::ento::registerNewDeleteChecker(clang::ento::CheckerManager&)
Line
Count
Source
3578
103
  void ento::register##name(CheckerManager &mgr) {                             \
3579
103
    MallocChecker *checker = mgr.getChecker<MallocChecker>();                  \
3580
103
    checker->ChecksEnabled[MallocChecker::CK_##name] = true;                   \
3581
103
    checker->CheckNames[MallocChecker::CK_##name] =                            \
3582
103
        mgr.getCurrentCheckerName();                                           \
3583
103
  }                                                                            \
clang::ento::registerNewDeleteLeaksChecker(clang::ento::CheckerManager&)
Line
Count
Source
3578
87
  void ento::register##name(CheckerManager &mgr) {                             \
3579
87
    MallocChecker *checker = mgr.getChecker<MallocChecker>();                  \
3580
87
    checker->ChecksEnabled[MallocChecker::CK_##name] = true;                   \
3581
87
    checker->CheckNames[MallocChecker::CK_##name] =                            \
3582
87
        mgr.getCurrentCheckerName();                                           \
3583
87
  }                                                                            \
clang::ento::registerMismatchedDeallocatorChecker(clang::ento::CheckerManager&)
Line
Count
Source
3578
75
  void ento::register##name(CheckerManager &mgr) {                             \
3579
75
    MallocChecker *checker = mgr.getChecker<MallocChecker>();                  \
3580
75
    checker->ChecksEnabled[MallocChecker::CK_##name] = true;                   \
3581
75
    checker->CheckNames[MallocChecker::CK_##name] =                            \
3582
75
        mgr.getCurrentCheckerName();                                           \
3583
75
  }                                                                            \
3584
                                                                               \
3585
846
  bool ento::shouldRegister##name(const CheckerManager &mgr) { return true; }
clang::ento::shouldRegisterMallocChecker(clang::ento::CheckerManager const&)
Line
Count
Source
3585
312
  bool ento::shouldRegister##name(const CheckerManager &mgr) { return true; }
clang::ento::shouldRegisterNewDeleteChecker(clang::ento::CheckerManager const&)
Line
Count
Source
3585
206
  bool ento::shouldRegister##name(const CheckerManager &mgr) { return true; }
clang::ento::shouldRegisterNewDeleteLeaksChecker(clang::ento::CheckerManager const&)
Line
Count
Source
3585
174
  bool ento::shouldRegister##name(const CheckerManager &mgr) { return true; }
clang::ento::shouldRegisterMismatchedDeallocatorChecker(clang::ento::CheckerManager const&)
Line
Count
Source
3585
154
  bool ento::shouldRegister##name(const CheckerManager &mgr) { return true; }
3586
3587
REGISTER_CHECKER(MallocChecker)
3588
REGISTER_CHECKER(NewDeleteChecker)
3589
REGISTER_CHECKER(NewDeleteLeaksChecker)
3590
REGISTER_CHECKER(MismatchedDeallocatorChecker)