1 // Copyright 2021 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_OBJECTS_MANAGED_INL_H_
6 #define V8_OBJECTS_MANAGED_INL_H_
7 
8 #include "src/handles/global-handles-inl.h"
9 #include "src/objects/managed.h"
10 
11 namespace v8 {
12 namespace internal {
13 
14 // static
15 template <class CppType>
16 template <typename... Args>
Allocate(Isolate * isolate,size_t estimated_size,Args &&...args)17 Handle<Managed<CppType>> Managed<CppType>::Allocate(Isolate* isolate,
18                                                     size_t estimated_size,
19                                                     Args&&... args) {
20   return FromSharedPtr(isolate, estimated_size,
21                        std::make_shared<CppType>(std::forward<Args>(args)...));
22 }
23 
24 // static
25 template <class CppType>
FromRawPtr(Isolate * isolate,size_t estimated_size,CppType * ptr)26 Handle<Managed<CppType>> Managed<CppType>::FromRawPtr(Isolate* isolate,
27                                                       size_t estimated_size,
28                                                       CppType* ptr) {
29   return FromSharedPtr(isolate, estimated_size, std::shared_ptr<CppType>{ptr});
30 }
31 
32 // static
33 template <class CppType>
FromUniquePtr(Isolate * isolate,size_t estimated_size,std::unique_ptr<CppType> unique_ptr)34 Handle<Managed<CppType>> Managed<CppType>::FromUniquePtr(
35     Isolate* isolate, size_t estimated_size,
36     std::unique_ptr<CppType> unique_ptr) {
37   return FromSharedPtr(isolate, estimated_size, std::move(unique_ptr));
38 }
39 
40 // static
41 template <class CppType>
FromSharedPtr(Isolate * isolate,size_t estimated_size,std::shared_ptr<CppType> shared_ptr)42 Handle<Managed<CppType>> Managed<CppType>::FromSharedPtr(
43     Isolate* isolate, size_t estimated_size,
44     std::shared_ptr<CppType> shared_ptr) {
45   reinterpret_cast<v8::Isolate*>(isolate)
46       ->AdjustAmountOfExternalAllocatedMemory(estimated_size);
47   auto destructor = new ManagedPtrDestructor(
48       estimated_size, new std::shared_ptr<CppType>{std::move(shared_ptr)},
49       Destructor);
50   Handle<Managed<CppType>> handle = Handle<Managed<CppType>>::cast(
51       isolate->factory()->NewForeign(reinterpret_cast<Address>(destructor)));
52   Handle<Object> global_handle = isolate->global_handles()->Create(*handle);
53   destructor->global_handle_location_ = global_handle.location();
54   GlobalHandles::MakeWeak(destructor->global_handle_location_, destructor,
55                           &ManagedObjectFinalizer,
56                           v8::WeakCallbackType::kParameter);
57   isolate->RegisterManagedPtrDestructor(destructor);
58   return handle;
59 }
60 
61 }  // namespace internal
62 }  // namespace v8
63 
64 #endif  // V8_OBJECTS_MANAGED_INL_H_
65