1
    2
    3
    4
    5
    6
    7
    8
    9
   10
   11
   12
   13
   14
   15
   16
   17
   18
   19
   20
   21
   22
   23
   24
   25
   26
   27
   28
   29
   30
   31
   32
   33
   34
   35
   36
   37
   38
   39
   40
   41
   42
   43
   44
   45
   46
   47
   48
   49
   50
   51
   52
   53
   54
   55
   56
   57
   58
   59
   60
   61

media / base / use_after_free_checker.h [blame]

// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef MEDIA_BASE_USE_AFTER_FREE_CHECKER_H_
#define MEDIA_BASE_USE_AFTER_FREE_CHECKER_H_

#include "base/debug/crash_logging.h"
#include "base/debug/dump_without_crashing.h"
#include "base/notreached.h"
#include "media/base/media_export.h"

namespace {

static base::debug::CrashKeyString* crash_key_string() {
  static base::debug::CrashKeyString* string = nullptr;
  if (!string) {
    string = base::debug::AllocateCrashKeyString(
        "use_after_free_checker", base::debug::CrashKeySize::Size32);
  }

  return string;
}

}  // namespace

namespace media {

// Maintains a guard value from ctor => dtor, and causes a crash if it's ever
// found to be in an incorrect state.  Includes a crash key that identifies
// whether itse use-after-free or corruption.
class MEDIA_EXPORT UseAfterFreeChecker {
 public:
  inline ~UseAfterFreeChecker() {
    check();
    state_ = State::kDestructed;
  }

  void check() const {
    if (state_ != State::kConstructed) {
      base::debug::ScopedCrashKeyString scoped(
          crash_key_string(),
          state_ == State::kDestructed ? "destructed" : "corrupt");
      NOTREACHED();
    }
  }

 private:
  enum State : uint64_t {
    kConstructed = 0x80C0FFEE,
    kDestructed = 0xDEADC0DE,
  };

  // Declare this as an int rather than State, to avoid undefinedness if it gets
  // overwritten with an arbitrary value.
  uint64_t state_ = State::kConstructed;
};

}  // namespace media

#endif  // MEDIA_BASE_USE_AFTER_FREE_CHECKER_H_