1// Copyright 2020 the V8 project authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef V8_HEAP_CPPGC_PREFINALIZER_HANDLER_H_
6#define V8_HEAP_CPPGC_PREFINALIZER_HANDLER_H_
7
8#include <utility>
9#include <vector>
10
11#include "include/cppgc/prefinalizer.h"
12
13namespace cppgc {
14namespace internal {
15
16class HeapBase;
17
18struct PreFinalizer final {
19  using Callback = PrefinalizerRegistration::Callback;
20
21  void* object;
22  Callback callback;
23
24  bool operator==(const PreFinalizer& other) const;
25};
26
27class PreFinalizerHandler final {
28 public:
29  explicit PreFinalizerHandler(HeapBase& heap);
30
31  void RegisterPrefinalizer(PreFinalizer pre_finalizer);
32
33  void InvokePreFinalizers();
34
35  bool IsInvokingPreFinalizers() const { return is_invoking_; }
36
37  void NotifyAllocationInPrefinalizer(size_t);
38  size_t ExtractBytesAllocatedInPrefinalizers() {
39    return std::exchange(bytes_allocated_in_prefinalizers, 0);
40  }
41
42 private:
43  // Checks that the current thread is the thread that created the heap.
44  bool CurrentThreadIsCreationThread();
45
46  // Pre-finalizers are called in the reverse order in which they are
47  // registered by the constructors (including constructors of Mixin
48  // objects) for an object, by processing the ordered_pre_finalizers_
49  // back-to-front.
50  std::vector<PreFinalizer> ordered_pre_finalizers_;
51  std::vector<PreFinalizer>* current_ordered_pre_finalizers_;
52
53  HeapBase& heap_;
54  bool is_invoking_ = false;
55#ifdef DEBUG
56  int creation_thread_id_;
57#endif
58
59  // Counter of bytes allocated during prefinalizers.
60  size_t bytes_allocated_in_prefinalizers = 0u;
61};
62
63}  // namespace internal
64}  // namespace cppgc
65
66#endif  // V8_HEAP_CPPGC_PREFINALIZER_HANDLER_H_
67