Skip to content

Commit 5177b10

Browse files
avivkellerv8-scoped@luci-project-accounts.iam.gserviceaccount.com
authored andcommitted
fix(inspector): hold on to promises
Keep `m_evaluationResult` strong for evaluations until the promise settles or the request is cancelled. Bug: 536271637 Change-Id: If21cc4aa0ba6bb2e2722d5ee73eb7744a0ead207 Reviewed-on: https://chromium-review.googlesource.com/c/v8/v8/+/8123081 Commit-Queue: Simon Zünd <[email protected]> Reviewed-by: Simon Zünd <[email protected]> Reviewed-by: Kim-Anh Tran <[email protected]> Cr-Commit-Position: refs/heads/main@{#108874}
1 parent 241f63a commit 5177b10

7 files changed

Lines changed: 217 additions & 6 deletions

File tree

‎AUTHORS‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ Artem Kobzar <[email protected]>
7878
Arthur Islamov <[email protected]>
7979
Asuka Shikina <[email protected]>
8080
Aurèle Barrière <[email protected]>
81+
Aviv Keller <[email protected]>
8182
Ayako Hayasaka <[email protected]>
8283
Bala Avulapati <[email protected]>
8384
Bangfu Tao <[email protected]>

‎src/inspector/injected-script.cc‎

Lines changed: 37 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -204,8 +204,7 @@ class InjectedScript::ProtocolPromiseHandler {
204204
PromiseHandlerTracker::DiscardReason::kFulfilled);
205205
}
206206

207-
ProtocolPromiseHandler(PromiseHandlerTracker::Id id,
208-
V8InspectorSessionImpl* session,
207+
ProtocolPromiseHandler(V8InspectorSessionImpl* session,
209208
int executionContextId, const String16& objectGroup,
210209
std::unique_ptr<WrapOptions> wrapOptions,
211210
bool replMode, bool throwOnSideEffect,
@@ -220,7 +219,13 @@ class InjectedScript::ProtocolPromiseHandler {
220219
m_replMode(replMode),
221220
m_throwOnSideEffect(throwOnSideEffect),
222221
m_callback(std::move(callback)),
223-
m_evaluationResult(m_inspector->isolate(), evaluationResult) {
222+
m_evaluationResult(m_inspector->isolate(), evaluationResult) {}
223+
224+
void makeWeak(PromiseHandlerTracker::Id id) {
225+
if (m_isActive || m_evaluationResult.IsEmpty() ||
226+
m_evaluationResult.IsWeak()) {
227+
return;
228+
}
224229
m_evaluationResult.SetWeak(reinterpret_cast<PromiseHandlerTracker::Id*>(id),
225230
cleanup, v8::WeakCallbackType::kParameter);
226231
}
@@ -238,6 +243,7 @@ class InjectedScript::ProtocolPromiseHandler {
238243
}
239244

240245
void thenCallback(v8::Local<v8::Value> value) {
246+
m_isActive = true;
241247
// We don't need the m_evaluationResult in the `thenCallback`, but we also
242248
// don't want `cleanup` running in case we re-enter JS.
243249
m_evaluationResult.Reset();
@@ -286,9 +292,10 @@ class InjectedScript::ProtocolPromiseHandler {
286292
}
287293

288294
void catchCallback(v8::Local<v8::Value> result) {
295+
m_isActive = true;
289296
// Hold strongly onto m_evaluationResult now to prevent `cleanup` from
290297
// running in case any code below triggers GC.
291-
m_evaluationResult.ClearWeak<void>();
298+
if (m_evaluationResult.IsWeak()) m_evaluationResult.ClearWeak<void>();
292299
V8InspectorSessionImpl* session =
293300
m_inspector->sessionById(m_contextGroupId, m_sessionId);
294301
if (!session) return;
@@ -397,6 +404,7 @@ class InjectedScript::ProtocolPromiseHandler {
397404
std::unique_ptr<WrapOptions> m_wrapOptions;
398405
bool m_replMode;
399406
bool m_throwOnSideEffect;
407+
bool m_isActive = false;
400408
std::weak_ptr<EvaluateCallback> m_callback;
401409
v8::Global<v8::Promise> m_evaluationResult;
402410
};
@@ -1206,8 +1214,7 @@ template <typename... Args>
12061214
PromiseHandlerTracker::Id PromiseHandlerTracker::create(Args&&... args) {
12071215
Id id = m_lastUsedId++;
12081216
InjectedScript::ProtocolPromiseHandler* handler =
1209-
new InjectedScript::ProtocolPromiseHandler(id,
1210-
std::forward<Args>(args)...);
1217+
new InjectedScript::ProtocolPromiseHandler(std::forward<Args>(args)...);
12111218
m_promiseHandlers.emplace(id, handler);
12121219
return id;
12131220
}
@@ -1241,6 +1248,30 @@ InjectedScript::ProtocolPromiseHandler* PromiseHandlerTracker::get(
12411248
return iter->second.get();
12421249
}
12431250

1251+
void PromiseHandlerTracker::makeWeakForContext(int executionContextId) {
1252+
for (auto& [id, handler] : m_promiseHandlers) {
1253+
if (handler->m_executionContextId == executionContextId) {
1254+
handler->makeWeak(id);
1255+
}
1256+
}
1257+
}
1258+
1259+
void PromiseHandlerTracker::makeWeakForObjectGroup(
1260+
int sessionId, const String16& objectGroup) {
1261+
for (auto& [id, handler] : m_promiseHandlers) {
1262+
if (handler->m_sessionId == sessionId &&
1263+
handler->m_objectGroup == objectGroup) {
1264+
handler->makeWeak(id);
1265+
}
1266+
}
1267+
}
1268+
1269+
void PromiseHandlerTracker::makeWeakForSession(int sessionId) {
1270+
for (auto& [id, handler] : m_promiseHandlers) {
1271+
if (handler->m_sessionId == sessionId) handler->makeWeak(id);
1272+
}
1273+
}
1274+
12441275
void PromiseHandlerTracker::sendFailure(
12451276
InjectedScript::ProtocolPromiseHandler* handler,
12461277
const protocol::DispatchResponse& response) const {

‎src/inspector/injected-script.h‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,9 @@ class PromiseHandlerTracker {
308308
Id create(Args&&... args);
309309
void discard(Id id, DiscardReason reason);
310310
InjectedScript::ProtocolPromiseHandler* get(Id id) const;
311+
void makeWeakForContext(int executionContextId);
312+
void makeWeakForObjectGroup(int sessionId, const String16& objectGroup);
313+
void makeWeakForSession(int sessionId);
311314

312315
private:
313316
void sendFailure(InjectedScript::ProtocolPromiseHandler* handler,

‎src/inspector/v8-inspector-impl.cc‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,7 @@ void V8InspectorImpl::contextCollected(int groupId, int contextId) {
345345
inspectedContext.get());
346346
});
347347
discardInspectedContext(groupId, contextId);
348+
m_promiseHandlerTracker.makeWeakForContext(contextId);
348349
}
349350

350351
void V8InspectorImpl::resetContextGroup(int contextGroupId) {

‎src/inspector/v8-inspector-session-impl.cc‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,7 @@ void V8InspectorSessionImpl::discardInjectedScripts() {
221221
[&sessionId](InspectedContext* context) {
222222
context->discardInjectedScript(sessionId);
223223
});
224+
m_inspector->promiseHandlerTracker().makeWeakForSession(sessionId);
224225
}
225226

226227
Response V8InspectorSessionImpl::findInjectedScript(
@@ -264,6 +265,10 @@ void V8InspectorSessionImpl::releaseObjectGroup(const String16& objectGroup) {
264265
InjectedScript* injectedScript = context->getInjectedScript(sessionId);
265266
if (injectedScript) injectedScript->releaseObjectGroup(objectGroup);
266267
});
268+
if (!objectGroup.isEmpty()) {
269+
m_inspector->promiseHandlerTracker().makeWeakForObjectGroup(m_sessionId,
270+
objectGroup);
271+
}
267272
}
268273

269274
bool V8InspectorSessionImpl::unwrapObject(
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
Tests the lifetime of pending Runtime.evaluate requests.
2+
3+
Running test: testPromiseIsKeptAlive
4+
Using replMode:
5+
{
6+
id : <messageId>
7+
result : {
8+
result : {
9+
description : 42
10+
type : number
11+
value : 42
12+
}
13+
}
14+
}
15+
Using awaitPromise:
16+
{
17+
id : <messageId>
18+
result : {
19+
result : {
20+
description : 42
21+
type : number
22+
value : 42
23+
}
24+
}
25+
}
26+
27+
Running test: testObjectGroupReleaseMakesPromiseCollectible
28+
Using replMode:
29+
{
30+
error : {
31+
code : -32000
32+
message : Promise was collected
33+
}
34+
id : <messageId>
35+
}
36+
Using awaitPromise:
37+
{
38+
error : {
39+
code : -32000
40+
message : Promise was collected
41+
}
42+
id : <messageId>
43+
}
44+
45+
Running test: testContextDestructionDiscardsPromise
46+
Using replMode:
47+
{
48+
error : {
49+
code : -32000
50+
message : Execution context was destroyed.
51+
}
52+
id : <messageId>
53+
}
54+
Using awaitPromise:
55+
{
56+
error : {
57+
code : -32000
58+
message : Execution context was destroyed.
59+
}
60+
id : <messageId>
61+
}
62+
63+
Running test: testSessionDestructionMakesPromiseCollectible
64+
Promise is alive before disconnect: true
65+
Promise is alive after disconnect: false
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
// Copyright 2026 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+
// Flags: --no-stress-incremental-marking
6+
7+
let {Protocol} = InspectorTest.start(
8+
'Tests the lifetime of pending Runtime.evaluate requests.');
9+
10+
const evaluationModes = [
11+
{
12+
name: 'replMode',
13+
arguments: {replMode: true},
14+
expression:
15+
'await new Promise(resolve => globalThis.resolve = resolve); 42',
16+
resolveExpression: 'resolve()',
17+
pendingExpression: 'await new Promise(() => {})',
18+
},
19+
{
20+
name: 'awaitPromise',
21+
arguments: {awaitPromise: true},
22+
expression: `(() => {
23+
let resolve;
24+
const promise = new Promise(r => resolve = r);
25+
promise.resolve = resolve;
26+
globalThis.weak = new WeakRef(promise);
27+
return promise;
28+
})()`,
29+
resolveExpression: 'weak.deref().resolve(42)',
30+
pendingExpression: 'new Promise(() => {})',
31+
},
32+
];
33+
34+
function evaluate(Protocol, mode, expression, extraArguments = {}) {
35+
return Protocol.Runtime.evaluate(
36+
{...mode.arguments, ...extraArguments, expression});
37+
}
38+
39+
InspectorTest.runAsyncTestSuite([
40+
async function testPromiseIsKeptAlive() {
41+
for (const mode of evaluationModes) {
42+
InspectorTest.log(`Using ${mode.name}:`);
43+
const evaluation = evaluate(Protocol, mode, mode.expression);
44+
45+
await Protocol.HeapProfiler.collectGarbage();
46+
await Protocol.Runtime.evaluate({expression: mode.resolveExpression});
47+
48+
InspectorTest.logMessage(await evaluation);
49+
}
50+
},
51+
52+
async function testObjectGroupReleaseMakesPromiseCollectible() {
53+
for (const mode of evaluationModes) {
54+
InspectorTest.log(`Using ${mode.name}:`);
55+
const evaluation = evaluate(
56+
Protocol, mode, mode.pendingExpression,
57+
{objectGroup: 'evaluation'});
58+
59+
await Protocol.Runtime.releaseObjectGroup({objectGroup: 'evaluation'});
60+
await Protocol.HeapProfiler.collectGarbage();
61+
62+
InspectorTest.logMessage(await evaluation);
63+
}
64+
},
65+
66+
async function testContextDestructionDiscardsPromise() {
67+
for (const mode of evaluationModes) {
68+
InspectorTest.log(`Using ${mode.name}:`);
69+
const contextGroup = new InspectorTest.ContextGroup();
70+
const session = contextGroup.connect();
71+
const evaluation = evaluate(
72+
session.Protocol, mode, mode.pendingExpression);
73+
74+
await session.Protocol.Runtime.evaluate(
75+
{expression: 'inspector.fireContextDestroyed()'});
76+
77+
InspectorTest.logMessage(await evaluation);
78+
session.disconnect();
79+
}
80+
},
81+
82+
async function testSessionDestructionMakesPromiseCollectible() {
83+
const contextGroup = new InspectorTest.ContextGroup();
84+
const session1 = contextGroup.connect();
85+
const session2 = contextGroup.connect();
86+
session1.Protocol.Runtime.evaluate({
87+
expression: evaluationModes[1].expression,
88+
awaitPromise: true,
89+
});
90+
91+
await session2.Protocol.HeapProfiler.collectGarbage();
92+
let result = await session2.Protocol.Runtime.evaluate(
93+
{expression: 'weak.deref() !== undefined'});
94+
InspectorTest.log(
95+
`Promise is alive before disconnect: ${result.result.result.value}`);
96+
97+
session1.disconnect();
98+
await session2.Protocol.HeapProfiler.collectGarbage();
99+
result = await session2.Protocol.Runtime.evaluate(
100+
{expression: 'weak.deref() !== undefined'});
101+
InspectorTest.log(
102+
`Promise is alive after disconnect: ${result.result.result.value}`);
103+
session2.disconnect();
104+
},
105+
]);

0 commit comments

Comments
 (0)