1515
1616namespace v8_inspector {
1717
18+ class InspectedContext ::WeakCallbackData {
19+ public:
20+ WeakCallbackData (InspectedContext* context, V8InspectorImpl* inspector,
21+ int groupId, int contextId)
22+ : m_context(context),
23+ m_inspector (inspector),
24+ m_groupId(groupId),
25+ m_contextId(contextId) {}
26+
27+ static void resetContext (const v8::WeakCallbackInfo<WeakCallbackData>& data) {
28+ // InspectedContext is alive here because weak handler is still alive.
29+ data.GetParameter ()->m_context ->m_weakCallbackData = nullptr ;
30+ data.GetParameter ()->m_context ->m_context .Reset ();
31+ data.SetSecondPassCallback (&callContextCollected);
32+ }
33+
34+ static void callContextCollected (
35+ const v8::WeakCallbackInfo<WeakCallbackData>& data) {
36+ // InspectedContext can be dead here since anything can happen between first
37+ // and second pass callback.
38+ WeakCallbackData* callbackData = data.GetParameter ();
39+ callbackData->m_inspector ->contextCollected (callbackData->m_groupId ,
40+ callbackData->m_contextId );
41+ delete callbackData;
42+ }
43+
44+ private:
45+ InspectedContext* m_context;
46+ V8InspectorImpl* m_inspector;
47+ int m_groupId;
48+ int m_contextId;
49+ };
50+
1851InspectedContext::InspectedContext (V8InspectorImpl* inspector,
1952 const V8ContextInfo& info, int contextId)
2053 : m_inspector(inspector),
@@ -25,6 +58,11 @@ InspectedContext::InspectedContext(V8InspectorImpl* inspector,
2558 m_humanReadableName(toString16(info.humanReadableName)),
2659 m_auxData(toString16(info.auxData)) {
2760 v8::debug::SetContextId (info.context , contextId);
61+ m_weakCallbackData =
62+ new WeakCallbackData (this , m_inspector, m_contextGroupId, m_contextId);
63+ m_context.SetWeak (m_weakCallbackData,
64+ &InspectedContext::WeakCallbackData::resetContext,
65+ v8::WeakCallbackType::kParameter );
2866 if (!info.hasMemoryOnConsole ) return ;
2967 v8::Context::Scope contextScope (info.context );
3068 v8::Local<v8::Object> global = info.context ->Global ();
@@ -38,6 +76,9 @@ InspectedContext::InspectedContext(V8InspectorImpl* inspector,
3876}
3977
4078InspectedContext::~InspectedContext () {
79+ // If we destory InspectedContext before weak callback is invoked then we need
80+ // to delete data here.
81+ if (!m_context.IsEmpty ()) delete m_weakCallbackData;
4182}
4283
4384// static
0 commit comments