Kaido Kert | f309f9a | 2021-04-30 12:09:15 -0700 | [diff] [blame] | 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 | #include "src/heap/cppgc/prefinalizer-handler.h" |
| 6 | |
| 7 | #include <algorithm> |
| 8 | #include <memory> |
| 9 | |
| 10 | #include "src/base/platform/platform.h" |
| 11 | #include "src/heap/cppgc/heap-page.h" |
| 12 | #include "src/heap/cppgc/heap.h" |
| 13 | #include "src/heap/cppgc/liveness-broker.h" |
| 14 | |
| 15 | namespace cppgc { |
| 16 | namespace internal { |
| 17 | |
| 18 | // static |
| 19 | void PreFinalizerRegistrationDispatcher::RegisterPrefinalizer( |
| 20 | PreFinalizer pre_finalizer) { |
| 21 | BasePage::FromPayload(pre_finalizer.object) |
| 22 | ->heap() |
| 23 | ->prefinalizer_handler() |
| 24 | ->RegisterPrefinalizer(pre_finalizer); |
| 25 | } |
| 26 | |
| 27 | bool PreFinalizerRegistrationDispatcher::PreFinalizer::operator==( |
| 28 | const PreFinalizer& other) const { |
| 29 | return (object == other.object) && (callback == other.callback); |
| 30 | } |
| 31 | |
| 32 | PreFinalizerHandler::PreFinalizerHandler() |
| 33 | #ifdef DEBUG |
| 34 | : creation_thread_id_(v8::base::OS::GetCurrentThreadId()) |
| 35 | #endif |
| 36 | { |
| 37 | } |
| 38 | |
| 39 | void PreFinalizerHandler::RegisterPrefinalizer(PreFinalizer pre_finalizer) { |
| 40 | DCHECK(CurrentThreadIsCreationThread()); |
| 41 | DCHECK_EQ(ordered_pre_finalizers_.end(), |
| 42 | std::find(ordered_pre_finalizers_.begin(), |
| 43 | ordered_pre_finalizers_.end(), pre_finalizer)); |
| 44 | ordered_pre_finalizers_.push_back(pre_finalizer); |
| 45 | } |
| 46 | |
| 47 | void PreFinalizerHandler::InvokePreFinalizers() { |
| 48 | DCHECK(CurrentThreadIsCreationThread()); |
| 49 | LivenessBroker liveness_broker = LivenessBrokerFactory::Create(); |
| 50 | ordered_pre_finalizers_.erase( |
| 51 | ordered_pre_finalizers_.begin(), |
| 52 | std::remove_if(ordered_pre_finalizers_.rbegin(), |
| 53 | ordered_pre_finalizers_.rend(), |
| 54 | [liveness_broker](const PreFinalizer& pf) { |
| 55 | return (pf.callback)(liveness_broker, pf.object); |
| 56 | }) |
| 57 | .base()); |
| 58 | ordered_pre_finalizers_.shrink_to_fit(); |
| 59 | } |
| 60 | |
| 61 | bool PreFinalizerHandler::CurrentThreadIsCreationThread() { |
| 62 | #ifdef DEBUG |
| 63 | return creation_thread_id_ == v8::base::OS::GetCurrentThreadId(); |
| 64 | #else |
| 65 | return true; |
| 66 | #endif |
| 67 | } |
| 68 | |
| 69 | } // namespace internal |
| 70 | } // namespace cppgc |