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),
@@ -26,6 +59,11 @@ InspectedContext::InspectedContext(V8InspectorImpl* inspector,
2659 m_auxData(toString16(info.auxData)),
2760 m_reported(false ) {
2861 v8::debug::SetContextId (info.context , contextId);
62+ m_weakCallbackData =
63+ new WeakCallbackData (this , m_inspector, m_contextGroupId, m_contextId);
64+ m_context.SetWeak (m_weakCallbackData,
65+ &InspectedContext::WeakCallbackData::resetContext,
66+ v8::WeakCallbackType::kParameter );
2967 if (!info.hasMemoryOnConsole ) return ;
3068 v8::Context::Scope contextScope (info.context );
3169 v8::Local<v8::Object> global = info.context ->Global ();
@@ -39,6 +77,9 @@ InspectedContext::InspectedContext(V8InspectorImpl* inspector,
3977}
4078
4179InspectedContext::~InspectedContext () {
80+ // If we destory InspectedContext before weak callback is invoked then we need
81+ // to delete data here.
82+ if (!m_context.IsEmpty ()) delete m_weakCallbackData;
4283}
4384
4485// static
0 commit comments