1 // Copyright 2013 The Chromium 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.
5 #include "gin/wrappable.h"
7 #include "base/logging.h"
8 #include "gin/object_template_builder.h"
9 #include "gin/per_isolate_data.h"
13 WrappableBase::WrappableBase() {
16 WrappableBase::~WrappableBase() {
20 ObjectTemplateBuilder
WrappableBase::GetObjectTemplateBuilder(
21 v8::Isolate
* isolate
) {
22 return ObjectTemplateBuilder(isolate
);
25 void WrappableBase::FirstWeakCallback(
26 const v8::WeakCallbackInfo
<WrappableBase
>& data
) {
27 WrappableBase
* wrappable
= data
.GetParameter();
28 wrappable
->wrapper_
.Reset();
29 data
.SetSecondPassCallback(SecondWeakCallback
);
32 void WrappableBase::SecondWeakCallback(
33 const v8::WeakCallbackInfo
<WrappableBase
>& data
) {
34 WrappableBase
* wrappable
= data
.GetParameter();
38 v8::Local
<v8::Object
> WrappableBase::GetWrapperImpl(v8::Isolate
* isolate
,
40 if (!wrapper_
.IsEmpty()) {
41 return v8::Local
<v8::Object
>::New(isolate
, wrapper_
);
44 PerIsolateData
* data
= PerIsolateData::From(isolate
);
45 v8::Local
<v8::ObjectTemplate
> templ
= data
->GetObjectTemplate(info
);
46 if (templ
.IsEmpty()) {
47 templ
= GetObjectTemplateBuilder(isolate
).Build();
48 CHECK(!templ
.IsEmpty());
49 data
->SetObjectTemplate(info
, templ
);
51 CHECK_EQ(kNumberOfInternalFields
, templ
->InternalFieldCount());
52 v8::Local
<v8::Object
> wrapper
= templ
->NewInstance();
53 // |wrapper| may be empty in some extreme cases, e.g., when
54 // Object.prototype.constructor is overwritten.
55 if (wrapper
.IsEmpty()) {
56 // The current wrappable object will be no longer managed by V8. Delete this
61 wrapper
->SetAlignedPointerInInternalField(kWrapperInfoIndex
, info
);
62 wrapper
->SetAlignedPointerInInternalField(kEncodedValueIndex
, this);
63 wrapper_
.Reset(isolate
, wrapper
);
64 wrapper_
.SetWeak(this, FirstWeakCallback
, v8::WeakCallbackType::kParameter
);
70 void* FromV8Impl(v8::Isolate
* isolate
, v8::Local
<v8::Value
> val
,
71 WrapperInfo
* wrapper_info
) {
74 v8::Local
<v8::Object
> obj
= v8::Local
<v8::Object
>::Cast(val
);
75 WrapperInfo
* info
= WrapperInfo::From(obj
);
77 // If this fails, the object is not managed by Gin. It is either a normal JS
78 // object that's not wrapping any external C++ object, or it is wrapping some
79 // C++ object, but that object isn't managed by Gin (maybe Blink).
83 // If this fails, the object is managed by Gin, but it's not wrapping an
84 // instance of the C++ class associated with wrapper_info.
85 if (info
!= wrapper_info
)
88 return obj
->GetAlignedPointerFromInternalField(kEncodedValueIndex
);
91 } // namespace internal