Commit 7c534bf

Browse files
avivkelleraduh95
authored andcommitted
deps: V8: backport 5177b10891e6
Original commit message: 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 <szuend@chromium.org> Reviewed-by: Simon ZΓΌnd <szuend@chromium.org> Reviewed-by: Kim-Anh Tran <kimanh@chromium.org> Cr-Commit-Position: refs/heads/main@{#108874} Refs: v8/v8@5177b10 Co-authored-by: avivkeller <me@aviv.sh> PR-URL: #64631 Reviewed-By: Daeyeon Jeong <daeyeon.dev@gmail.com> Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
1 parent 8aba475 commit 7c534bf

8 files changed

Lines changed: 218 additions & 7 deletions

File tree

β€Žcommon.gypiβ€Ž

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141

4242
# Reset this number to 0 on major V8 upgrades.
4343
# Increment by one for each non-official patch applied to deps/v8.
44-
'v8_embedder_string': '-node.51',
44+
'v8_embedder_string': '-node.52',
4545

4646
##### V8 defaults for Node.js #####
4747

β€Ždeps/v8/AUTHORSβ€Ž

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ Artem Kobzar <artem.kobzar@jetbrains.com>
7676
Arthur Islamov <arthur@islamov.ai>
7777
Asuka Shikina <shikina.asuka@gmail.com>
7878
Aurèle Barrière <aurele.barriere@gmail.com>
79+
Aviv Keller <me@aviv.sh>
7980
Bala Avulapati <bavulapati@gmail.com>
8081
Bangfu Tao <bangfu.tao@samsung.com>
8182
Ben Coe <bencoe@gmail.com>

β€Ždeps/v8/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+
voidmakeWeak(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
voidthenCallback(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();
@@ -285,9 +291,10 @@ class InjectedScript::ProtocolPromiseHandler {
285291
}
286292

287293
voidcatchCallback(v8::Local<v8::Value> result) {
294+
m_isActive = true;
288295
// Hold strongly onto m_evaluationResult now to prevent `cleanup` from
289296
// running in case any code below triggers GC.
290-
m_evaluationResult.ClearWeak();
297+
if (m_evaluationResult.IsWeak()) m_evaluationResult.ClearWeak();
291298
V8InspectorSessionImpl* session =
292299
m_inspector->sessionById(m_contextGroupId, m_sessionId);
293300
if (!session) return;
@@ -393,6 +400,7 @@ class InjectedScript::ProtocolPromiseHandler {
393400
std::unique_ptr<WrapOptions> m_wrapOptions;
394401
bool m_replMode;
395402
bool m_throwOnSideEffect;
403+
bool m_isActive = false;
396404
std::weak_ptr<EvaluateCallback> m_callback;
397405
v8::Global<v8::Promise> m_evaluationResult;
398406
};
@@ -1190,8 +1198,7 @@ template <typename... Args>
11901198
PromiseHandlerTracker::Id PromiseHandlerTracker::create(Args&&... args) {
11911199
Id id = m_lastUsedId++;
11921200
InjectedScript::ProtocolPromiseHandler* handler =
1193-
newInjectedScript::ProtocolPromiseHandler(id,
1194-
std::forward<Args>(args)...);
1201+
newInjectedScript::ProtocolPromiseHandler(std::forward<Args>(args)...);
11951202
m_promiseHandlers.emplace(id, handler);
11961203
return id;
11971204
}
@@ -1225,6 +1232,30 @@ InjectedScript::ProtocolPromiseHandler* PromiseHandlerTracker::get(
12251232
return iter->second.get();
12261233
}
12271234

1235+
voidPromiseHandlerTracker::makeWeakForContext(int executionContextId) {
1236+
for (auto& [id, handler] : m_promiseHandlers) {
1237+
if (handler->m_executionContextId == executionContextId) {
1238+
handler->makeWeak(id);
1239+
}
1240+
}
1241+
}
1242+
1243+
voidPromiseHandlerTracker::makeWeakForObjectGroup(
1244+
int sessionId, const String16& objectGroup) {
1245+
for (auto& [id, handler] : m_promiseHandlers) {
1246+
if (handler->m_sessionId == sessionId &&
1247+
handler->m_objectGroup == objectGroup) {
1248+
handler->makeWeak(id);
1249+
}
1250+
}
1251+
}
1252+
1253+
voidPromiseHandlerTracker::makeWeakForSession(int sessionId) {
1254+
for (auto& [id, handler] : m_promiseHandlers) {
1255+
if (handler->m_sessionId == sessionId) handler->makeWeak(id);
1256+
}
1257+
}
1258+
12281259
voidPromiseHandlerTracker::sendFailure(
12291260
InjectedScript::ProtocolPromiseHandler* handler,
12301261
const protocol::DispatchResponse& response) const {

β€Ždeps/v8/src/inspector/injected-script.hβ€Ž

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -298,6 +298,9 @@ class PromiseHandlerTracker {
298298
Id create(Args&&... args);
299299
voiddiscard(Id id, DiscardReason reason);
300300
InjectedScript::ProtocolPromiseHandler* get(Id id) const;
301+
voidmakeWeakForContext(int executionContextId);
302+
voidmakeWeakForObjectGroup(int sessionId, const String16& objectGroup);
303+
voidmakeWeakForSession(int sessionId);
301304

302305
private:
303306
voidsendFailure(InjectedScript::ProtocolPromiseHandler* handler,

β€Ždeps/v8/src/inspector/v8-inspector-impl.ccβ€Ž

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,7 @@ void V8InspectorImpl::contextCollected(int groupId, int contextId) {
261261
session->runtimeAgent()->reportExecutionContextDestroyed(inspectedContext);
262262
});
263263
discardInspectedContext(groupId, contextId);
264+
m_promiseHandlerTracker.makeWeakForContext(contextId);
264265
}
265266

266267
voidV8InspectorImpl::resetContextGroup(int contextGroupId) {

β€Ždeps/v8/src/inspector/v8-inspector-session-impl.ccβ€Ž

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,7 @@ void V8InspectorSessionImpl::discardInjectedScripts() {
233233
[&sessionId](InspectedContext* context) {
234234
context->discardInjectedScript(sessionId);
235235
});
236+
m_inspector->promiseHandlerTracker().makeWeakForSession(sessionId);
236237
}
237238

238239
Response V8InspectorSessionImpl::findInjectedScript(
@@ -269,6 +270,10 @@ void V8InspectorSessionImpl::releaseObjectGroup(const String16& objectGroup) {
269270
InjectedScript* injectedScript = context->getInjectedScript(sessionId);
270271
if (injectedScript) injectedScript->releaseObjectGroup(objectGroup);
271272
});
273+
if (!objectGroup.isEmpty()) {
274+
m_inspector->promiseHandlerTracker().makeWeakForObjectGroup(m_sessionId,
275+
objectGroup);
276+
}
272277
}
273278

274279
boolV8InspectorSessionImpl::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+
constevaluationModes=[
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+
functionevaluate(Protocol,mode,expression,extraArguments={}){
35+
returnProtocol.Runtime.evaluate(
36+
{...mode.arguments, ...extraArguments, expression});
37+
}
38+
39+
InspectorTest.runAsyncTestSuite([
40+
asyncfunctiontestPromiseIsKeptAlive(){
41+
for(constmodeofevaluationModes){
42+
InspectorTest.log(`Using ${mode.name}:`);
43+
constevaluation=evaluate(Protocol,mode,mode.expression);
44+
45+
awaitProtocol.HeapProfiler.collectGarbage();
46+
awaitProtocol.Runtime.evaluate({expression: mode.resolveExpression});
47+
48+
InspectorTest.logMessage(awaitevaluation);
49+
}
50+
},
51+
52+
asyncfunctiontestObjectGroupReleaseMakesPromiseCollectible(){
53+
for(constmodeofevaluationModes){
54+
InspectorTest.log(`Using ${mode.name}:`);
55+
constevaluation=evaluate(
56+
Protocol,mode,mode.pendingExpression,
57+
{objectGroup: 'evaluation'});
58+
59+
awaitProtocol.Runtime.releaseObjectGroup({objectGroup: 'evaluation'});
60+
awaitProtocol.HeapProfiler.collectGarbage();
61+
62+
InspectorTest.logMessage(awaitevaluation);
63+
}
64+
},
65+
66+
asyncfunctiontestContextDestructionDiscardsPromise(){
67+
for(constmodeofevaluationModes){
68+
InspectorTest.log(`Using ${mode.name}:`);
69+
constcontextGroup=newInspectorTest.ContextGroup();
70+
constsession=contextGroup.connect();
71+
constevaluation=evaluate(
72+
session.Protocol,mode,mode.pendingExpression);
73+
74+
awaitsession.Protocol.Runtime.evaluate(
75+
{expression: 'inspector.fireContextDestroyed()'});
76+
77+
InspectorTest.logMessage(awaitevaluation);
78+
session.disconnect();
79+
}
80+
},
81+
82+
asyncfunctiontestSessionDestructionMakesPromiseCollectible(){
83+
constcontextGroup=newInspectorTest.ContextGroup();
84+
constsession1=contextGroup.connect();
85+
constsession2=contextGroup.connect();
86+
session1.Protocol.Runtime.evaluate({
87+
expression: evaluationModes[1].expression,
88+
awaitPromise: true,
89+
});
90+
91+
awaitsession2.Protocol.HeapProfiler.collectGarbage();
92+
letresult=awaitsession2.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+
awaitsession2.Protocol.HeapProfiler.collectGarbage();
99+
result=awaitsession2.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)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Commit 7c534bf

Browse files
avivkelleraduh95
authored andcommitted
deps: V8: backport 5177b10891e6
Original commit message: 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 <szuend@chromium.org> Reviewed-by: Simon ZΓΌnd <szuend@chromium.org> Reviewed-by: Kim-Anh Tran <kimanh@chromium.org> Cr-Commit-Position: refs/heads/main@{#108874} Refs: v8/v8@5177b10 Co-authored-by: avivkeller <me@aviv.sh> PR-URL: #64631 Reviewed-By: Daeyeon Jeong <daeyeon.dev@gmail.com> Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
1 parent 8aba475 commit 7c534bf

8 files changed

Lines changed: 218 additions & 7 deletions

File tree

β€Žcommon.gypiβ€Ž

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141

4242
# Reset this number to 0 on major V8 upgrades.
4343
# Increment by one for each non-official patch applied to deps/v8.
44-
'v8_embedder_string': '-node.51',
44+
'v8_embedder_string': '-node.52',
4545

4646
##### V8 defaults for Node.js #####
4747

β€Ždeps/v8/AUTHORSβ€Ž

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ Artem Kobzar <artem.kobzar@jetbrains.com>
7676
Arthur Islamov <arthur@islamov.ai>
7777
Asuka Shikina <shikina.asuka@gmail.com>
7878
Aurèle Barrière <aurele.barriere@gmail.com>
79+
Aviv Keller <me@aviv.sh>
7980
Bala Avulapati <bavulapati@gmail.com>
8081
Bangfu Tao <bangfu.tao@samsung.com>
8182
Ben Coe <bencoe@gmail.com>

β€Ždeps/v8/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+
voidmakeWeak(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
voidthenCallback(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();
@@ -285,9 +291,10 @@ class InjectedScript::ProtocolPromiseHandler {
285291
}
286292

287293
voidcatchCallback(v8::Local<v8::Value> result) {
294+
m_isActive = true;
288295
// Hold strongly onto m_evaluationResult now to prevent `cleanup` from
289296
// running in case any code below triggers GC.
290-
m_evaluationResult.ClearWeak();
297+
if (m_evaluationResult.IsWeak()) m_evaluationResult.ClearWeak();
291298
V8InspectorSessionImpl* session =
292299
m_inspector->sessionById(m_contextGroupId, m_sessionId);
293300
if (!session) return;
@@ -393,6 +400,7 @@ class InjectedScript::ProtocolPromiseHandler {
393400
std::unique_ptr<WrapOptions> m_wrapOptions;
394401
bool m_replMode;
395402
bool m_throwOnSideEffect;
403+
bool m_isActive = false;
396404
std::weak_ptr<EvaluateCallback> m_callback;
397405
v8::Global<v8::Promise> m_evaluationResult;
398406
};
@@ -1190,8 +1198,7 @@ template <typename... Args>
11901198
PromiseHandlerTracker::Id PromiseHandlerTracker::create(Args&&... args) {
11911199
Id id = m_lastUsedId++;
11921200
InjectedScript::ProtocolPromiseHandler* handler =
1193-
newInjectedScript::ProtocolPromiseHandler(id,
1194-
std::forward<Args>(args)...);
1201+
newInjectedScript::ProtocolPromiseHandler(std::forward<Args>(args)...);
11951202
m_promiseHandlers.emplace(id, handler);
11961203
return id;
11971204
}
@@ -1225,6 +1232,30 @@ InjectedScript::ProtocolPromiseHandler* PromiseHandlerTracker::get(
12251232
return iter->second.get();
12261233
}
12271234

1235+
voidPromiseHandlerTracker::makeWeakForContext(int executionContextId) {
1236+
for (auto& [id, handler] : m_promiseHandlers) {
1237+
if (handler->m_executionContextId == executionContextId) {
1238+
handler->makeWeak(id);
1239+
}
1240+
}
1241+
}
1242+
1243+
voidPromiseHandlerTracker::makeWeakForObjectGroup(
1244+
int sessionId, const String16& objectGroup) {
1245+
for (auto& [id, handler] : m_promiseHandlers) {
1246+
if (handler->m_sessionId == sessionId &&
1247+
handler->m_objectGroup == objectGroup) {
1248+
handler->makeWeak(id);
1249+
}
1250+
}
1251+
}
1252+
1253+
voidPromiseHandlerTracker::makeWeakForSession(int sessionId) {
1254+
for (auto& [id, handler] : m_promiseHandlers) {
1255+
if (handler->m_sessionId == sessionId) handler->makeWeak(id);
1256+
}
1257+
}
1258+
12281259
voidPromiseHandlerTracker::sendFailure(
12291260
InjectedScript::ProtocolPromiseHandler* handler,
12301261
const protocol::DispatchResponse& response) const {

β€Ždeps/v8/src/inspector/injected-script.hβ€Ž

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -298,6 +298,9 @@ class PromiseHandlerTracker {
298298
Id create(Args&&... args);
299299
voiddiscard(Id id, DiscardReason reason);
300300
InjectedScript::ProtocolPromiseHandler* get(Id id) const;
301+
voidmakeWeakForContext(int executionContextId);
302+
voidmakeWeakForObjectGroup(int sessionId, const String16& objectGroup);
303+
voidmakeWeakForSession(int sessionId);
301304

302305
private:
303306
voidsendFailure(InjectedScript::ProtocolPromiseHandler* handler,

β€Ždeps/v8/src/inspector/v8-inspector-impl.ccβ€Ž

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,7 @@ void V8InspectorImpl::contextCollected(int groupId, int contextId) {
261261
session->runtimeAgent()->reportExecutionContextDestroyed(inspectedContext);
262262
});
263263
discardInspectedContext(groupId, contextId);
264+
m_promiseHandlerTracker.makeWeakForContext(contextId);
264265
}
265266

266267
voidV8InspectorImpl::resetContextGroup(int contextGroupId) {

β€Ždeps/v8/src/inspector/v8-inspector-session-impl.ccβ€Ž

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,7 @@ void V8InspectorSessionImpl::discardInjectedScripts() {
233233
[&sessionId](InspectedContext* context) {
234234
context->discardInjectedScript(sessionId);
235235
});
236+
m_inspector->promiseHandlerTracker().makeWeakForSession(sessionId);
236237
}
237238

238239
Response V8InspectorSessionImpl::findInjectedScript(
@@ -269,6 +270,10 @@ void V8InspectorSessionImpl::releaseObjectGroup(const String16& objectGroup) {
269270
InjectedScript* injectedScript = context->getInjectedScript(sessionId);
270271
if (injectedScript) injectedScript->releaseObjectGroup(objectGroup);
271272
});
273+
if (!objectGroup.isEmpty()) {
274+
m_inspector->promiseHandlerTracker().makeWeakForObjectGroup(m_sessionId,
275+
objectGroup);
276+
}
272277
}
273278

274279
boolV8InspectorSessionImpl::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+
constevaluationModes=[
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+
functionevaluate(Protocol,mode,expression,extraArguments={}){
35+
returnProtocol.Runtime.evaluate(
36+
{...mode.arguments, ...extraArguments, expression});
37+
}
38+
39+
InspectorTest.runAsyncTestSuite([
40+
asyncfunctiontestPromiseIsKeptAlive(){
41+
for(constmodeofevaluationModes){
42+
InspectorTest.log(`Using ${mode.name}:`);
43+
constevaluation=evaluate(Protocol,mode,mode.expression);
44+
45+
awaitProtocol.HeapProfiler.collectGarbage();
46+
awaitProtocol.Runtime.evaluate({expression: mode.resolveExpression});
47+
48+
InspectorTest.logMessage(awaitevaluation);
49+
}
50+
},
51+
52+
asyncfunctiontestObjectGroupReleaseMakesPromiseCollectible(){
53+
for(constmodeofevaluationModes){
54+
InspectorTest.log(`Using ${mode.name}:`);
55+
constevaluation=evaluate(
56+
Protocol,mode,mode.pendingExpression,
57+
{objectGroup: 'evaluation'});
58+
59+
awaitProtocol.Runtime.releaseObjectGroup({objectGroup: 'evaluation'});
60+
awaitProtocol.HeapProfiler.collectGarbage();
61+
62+
InspectorTest.logMessage(awaitevaluation);
63+
}
64+
},
65+
66+
asyncfunctiontestContextDestructionDiscardsPromise(){
67+
for(constmodeofevaluationModes){
68+
InspectorTest.log(`Using ${mode.name}:`);
69+
constcontextGroup=newInspectorTest.ContextGroup();
70+
constsession=contextGroup.connect();
71+
constevaluation=evaluate(
72+
session.Protocol,mode,mode.pendingExpression);
73+
74+
awaitsession.Protocol.Runtime.evaluate(
75+
{expression: 'inspector.fireContextDestroyed()'});
76+
77+
InspectorTest.logMessage(awaitevaluation);
78+
session.disconnect();
79+
}
80+
},
81+
82+
asyncfunctiontestSessionDestructionMakesPromiseCollectible(){
83+
constcontextGroup=newInspectorTest.ContextGroup();
84+
constsession1=contextGroup.connect();
85+
constsession2=contextGroup.connect();
86+
session1.Protocol.Runtime.evaluate({
87+
expression: evaluationModes[1].expression,
88+
awaitPromise: true,
89+
});
90+
91+
awaitsession2.Protocol.HeapProfiler.collectGarbage();
92+
letresult=awaitsession2.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+
awaitsession2.Protocol.HeapProfiler.collectGarbage();
99+
result=awaitsession2.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)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 7c534bf

Browse files
avivkelleraduh95
authored andcommitted
deps: V8: backport 5177b10891e6
Original commit message: 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 <szuend@chromium.org> Reviewed-by: Simon ZΓΌnd <szuend@chromium.org> Reviewed-by: Kim-Anh Tran <kimanh@chromium.org> Cr-Commit-Position: refs/heads/main@{#108874} Refs: v8/v8@5177b10 Co-authored-by: avivkeller <me@aviv.sh> PR-URL: #64631 Reviewed-By: Daeyeon Jeong <daeyeon.dev@gmail.com> Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
1 parent 8aba475 commit 7c534bf

8 files changed

Lines changed: 218 additions & 7 deletions

File tree

β€Žcommon.gypiβ€Ž

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141

4242
# Reset this number to 0 on major V8 upgrades.
4343
# Increment by one for each non-official patch applied to deps/v8.
44-
'v8_embedder_string': '-node.51',
44+
'v8_embedder_string': '-node.52',
4545

4646
##### V8 defaults for Node.js #####
4747

β€Ždeps/v8/AUTHORSβ€Ž

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ Artem Kobzar <artem.kobzar@jetbrains.com>
7676
Arthur Islamov <arthur@islamov.ai>
7777
Asuka Shikina <shikina.asuka@gmail.com>
7878
Aurèle Barrière <aurele.barriere@gmail.com>
79+
Aviv Keller <me@aviv.sh>
7980
Bala Avulapati <bavulapati@gmail.com>
8081
Bangfu Tao <bangfu.tao@samsung.com>
8182
Ben Coe <bencoe@gmail.com>

β€Ždeps/v8/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+
voidmakeWeak(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
voidthenCallback(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();
@@ -285,9 +291,10 @@ class InjectedScript::ProtocolPromiseHandler {
285291
}
286292

287293
voidcatchCallback(v8::Local<v8::Value> result) {
294+
m_isActive = true;
288295
// Hold strongly onto m_evaluationResult now to prevent `cleanup` from
289296
// running in case any code below triggers GC.
290-
m_evaluationResult.ClearWeak();
297+
if (m_evaluationResult.IsWeak()) m_evaluationResult.ClearWeak();
291298
V8InspectorSessionImpl* session =
292299
m_inspector->sessionById(m_contextGroupId, m_sessionId);
293300
if (!session) return;
@@ -393,6 +400,7 @@ class InjectedScript::ProtocolPromiseHandler {
393400
std::unique_ptr<WrapOptions> m_wrapOptions;
394401
bool m_replMode;
395402
bool m_throwOnSideEffect;
403+
bool m_isActive = false;
396404
std::weak_ptr<EvaluateCallback> m_callback;
397405
v8::Global<v8::Promise> m_evaluationResult;
398406
};
@@ -1190,8 +1198,7 @@ template <typename... Args>
11901198
PromiseHandlerTracker::Id PromiseHandlerTracker::create(Args&&... args) {
11911199
Id id = m_lastUsedId++;
11921200
InjectedScript::ProtocolPromiseHandler* handler =
1193-
newInjectedScript::ProtocolPromiseHandler(id,
1194-
std::forward<Args>(args)...);
1201+
newInjectedScript::ProtocolPromiseHandler(std::forward<Args>(args)...);
11951202
m_promiseHandlers.emplace(id, handler);
11961203
return id;
11971204
}
@@ -1225,6 +1232,30 @@ InjectedScript::ProtocolPromiseHandler* PromiseHandlerTracker::get(
12251232
return iter->second.get();
12261233
}
12271234

1235+
voidPromiseHandlerTracker::makeWeakForContext(int executionContextId) {
1236+
for (auto& [id, handler] : m_promiseHandlers) {
1237+
if (handler->m_executionContextId == executionContextId) {
1238+
handler->makeWeak(id);
1239+
}
1240+
}
1241+
}
1242+
1243+
voidPromiseHandlerTracker::makeWeakForObjectGroup(
1244+
int sessionId, const String16& objectGroup) {
1245+
for (auto& [id, handler] : m_promiseHandlers) {
1246+
if (handler->m_sessionId == sessionId &&
1247+
handler->m_objectGroup == objectGroup) {
1248+
handler->makeWeak(id);
1249+
}
1250+
}
1251+
}
1252+
1253+
voidPromiseHandlerTracker::makeWeakForSession(int sessionId) {
1254+
for (auto& [id, handler] : m_promiseHandlers) {
1255+
if (handler->m_sessionId == sessionId) handler->makeWeak(id);
1256+
}
1257+
}
1258+
12281259
voidPromiseHandlerTracker::sendFailure(
12291260
InjectedScript::ProtocolPromiseHandler* handler,
12301261
const protocol::DispatchResponse& response) const {

β€Ždeps/v8/src/inspector/injected-script.hβ€Ž

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -298,6 +298,9 @@ class PromiseHandlerTracker {
298298
Id create(Args&&... args);
299299
voiddiscard(Id id, DiscardReason reason);
300300
InjectedScript::ProtocolPromiseHandler* get(Id id) const;
301+
voidmakeWeakForContext(int executionContextId);
302+
voidmakeWeakForObjectGroup(int sessionId, const String16& objectGroup);
303+
voidmakeWeakForSession(int sessionId);
301304

302305
private:
303306
voidsendFailure(InjectedScript::ProtocolPromiseHandler* handler,

β€Ždeps/v8/src/inspector/v8-inspector-impl.ccβ€Ž

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,7 @@ void V8InspectorImpl::contextCollected(int groupId, int contextId) {
261261
session->runtimeAgent()->reportExecutionContextDestroyed(inspectedContext);
262262
});
263263
discardInspectedContext(groupId, contextId);
264+
m_promiseHandlerTracker.makeWeakForContext(contextId);
264265
}
265266

266267
voidV8InspectorImpl::resetContextGroup(int contextGroupId) {

β€Ždeps/v8/src/inspector/v8-inspector-session-impl.ccβ€Ž

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,7 @@ void V8InspectorSessionImpl::discardInjectedScripts() {
233233
[&sessionId](InspectedContext* context) {
234234
context->discardInjectedScript(sessionId);
235235
});
236+
m_inspector->promiseHandlerTracker().makeWeakForSession(sessionId);
236237
}
237238

238239
Response V8InspectorSessionImpl::findInjectedScript(
@@ -269,6 +270,10 @@ void V8InspectorSessionImpl::releaseObjectGroup(const String16& objectGroup) {
269270
InjectedScript* injectedScript = context->getInjectedScript(sessionId);
270271
if (injectedScript) injectedScript->releaseObjectGroup(objectGroup);
271272
});
273+
if (!objectGroup.isEmpty()) {
274+
m_inspector->promiseHandlerTracker().makeWeakForObjectGroup(m_sessionId,
275+
objectGroup);
276+
}
272277
}
273278

274279
boolV8InspectorSessionImpl::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+
constevaluationModes=[
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+
functionevaluate(Protocol,mode,expression,extraArguments={}){
35+
returnProtocol.Runtime.evaluate(
36+
{...mode.arguments, ...extraArguments, expression});
37+
}
38+
39+
InspectorTest.runAsyncTestSuite([
40+
asyncfunctiontestPromiseIsKeptAlive(){
41+
for(constmodeofevaluationModes){
42+
InspectorTest.log(`Using ${mode.name}:`);
43+
constevaluation=evaluate(Protocol,mode,mode.expression);
44+
45+
awaitProtocol.HeapProfiler.collectGarbage();
46+
awaitProtocol.Runtime.evaluate({expression: mode.resolveExpression});
47+
48+
InspectorTest.logMessage(awaitevaluation);
49+
}
50+
},
51+
52+
asyncfunctiontestObjectGroupReleaseMakesPromiseCollectible(){
53+
for(constmodeofevaluationModes){
54+
InspectorTest.log(`Using ${mode.name}:`);
55+
constevaluation=evaluate(
56+
Protocol,mode,mode.pendingExpression,
57+
{objectGroup: 'evaluation'});
58+
59+
awaitProtocol.Runtime.releaseObjectGroup({objectGroup: 'evaluation'});
60+
awaitProtocol.HeapProfiler.collectGarbage();
61+
62+
InspectorTest.logMessage(awaitevaluation);
63+
}
64+
},
65+
66+
asyncfunctiontestContextDestructionDiscardsPromise(){
67+
for(constmodeofevaluationModes){
68+
InspectorTest.log(`Using ${mode.name}:`);
69+
constcontextGroup=newInspectorTest.ContextGroup();
70+
constsession=contextGroup.connect();
71+
constevaluation=evaluate(
72+
session.Protocol,mode,mode.pendingExpression);
73+
74+
awaitsession.Protocol.Runtime.evaluate(
75+
{expression: 'inspector.fireContextDestroyed()'});
76+
77+
InspectorTest.logMessage(awaitevaluation);
78+
session.disconnect();
79+
}
80+
},
81+
82+
asyncfunctiontestSessionDestructionMakesPromiseCollectible(){
83+
constcontextGroup=newInspectorTest.ContextGroup();
84+
constsession1=contextGroup.connect();
85+
constsession2=contextGroup.connect();
86+
session1.Protocol.Runtime.evaluate({
87+
expression: evaluationModes[1].expression,
88+
awaitPromise: true,
89+
});
90+
91+
awaitsession2.Protocol.HeapProfiler.collectGarbage();
92+
letresult=awaitsession2.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+
awaitsession2.Protocol.HeapProfiler.collectGarbage();
99+
result=awaitsession2.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)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 7c534bf

Browse files
avivkelleraduh95
authored andcommitted
deps: V8: backport 5177b10891e6
Original commit message: 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 <szuend@chromium.org> Reviewed-by: Simon ZΓΌnd <szuend@chromium.org> Reviewed-by: Kim-Anh Tran <kimanh@chromium.org> Cr-Commit-Position: refs/heads/main@{#108874} Refs: v8/v8@5177b10 Co-authored-by: avivkeller <me@aviv.sh> PR-URL: #64631 Reviewed-By: Daeyeon Jeong <daeyeon.dev@gmail.com> Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
1 parent 8aba475 commit 7c534bf

8 files changed

Lines changed: 218 additions & 7 deletions

File tree

β€Žcommon.gypiβ€Ž

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141

4242
# Reset this number to 0 on major V8 upgrades.
4343
# Increment by one for each non-official patch applied to deps/v8.
44-
'v8_embedder_string': '-node.51',
44+
'v8_embedder_string': '-node.52',
4545

4646
##### V8 defaults for Node.js #####
4747

β€Ždeps/v8/AUTHORSβ€Ž

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ Artem Kobzar <artem.kobzar@jetbrains.com>
7676
Arthur Islamov <arthur@islamov.ai>
7777
Asuka Shikina <shikina.asuka@gmail.com>
7878
Aurèle Barrière <aurele.barriere@gmail.com>
79+
Aviv Keller <me@aviv.sh>
7980
Bala Avulapati <bavulapati@gmail.com>
8081
Bangfu Tao <bangfu.tao@samsung.com>
8182
Ben Coe <bencoe@gmail.com>

β€Ždeps/v8/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+
voidmakeWeak(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
voidthenCallback(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();
@@ -285,9 +291,10 @@ class InjectedScript::ProtocolPromiseHandler {
285291
}
286292

287293
voidcatchCallback(v8::Local<v8::Value> result) {
294+
m_isActive = true;
288295
// Hold strongly onto m_evaluationResult now to prevent `cleanup` from
289296
// running in case any code below triggers GC.
290-
m_evaluationResult.ClearWeak();
297+
if (m_evaluationResult.IsWeak()) m_evaluationResult.ClearWeak();
291298
V8InspectorSessionImpl* session =
292299
m_inspector->sessionById(m_contextGroupId, m_sessionId);
293300
if (!session) return;
@@ -393,6 +400,7 @@ class InjectedScript::ProtocolPromiseHandler {
393400
std::unique_ptr<WrapOptions> m_wrapOptions;
394401
bool m_replMode;
395402
bool m_throwOnSideEffect;
403+
bool m_isActive = false;
396404
std::weak_ptr<EvaluateCallback> m_callback;
397405
v8::Global<v8::Promise> m_evaluationResult;
398406
};
@@ -1190,8 +1198,7 @@ template <typename... Args>
11901198
PromiseHandlerTracker::Id PromiseHandlerTracker::create(Args&&... args) {
11911199
Id id = m_lastUsedId++;
11921200
InjectedScript::ProtocolPromiseHandler* handler =
1193-
newInjectedScript::ProtocolPromiseHandler(id,
1194-
std::forward<Args>(args)...);
1201+
newInjectedScript::ProtocolPromiseHandler(std::forward<Args>(args)...);
11951202
m_promiseHandlers.emplace(id, handler);
11961203
return id;
11971204
}
@@ -1225,6 +1232,30 @@ InjectedScript::ProtocolPromiseHandler* PromiseHandlerTracker::get(
12251232
return iter->second.get();
12261233
}
12271234

1235+
voidPromiseHandlerTracker::makeWeakForContext(int executionContextId) {
1236+
for (auto& [id, handler] : m_promiseHandlers) {
1237+
if (handler->m_executionContextId == executionContextId) {
1238+
handler->makeWeak(id);
1239+
}
1240+
}
1241+
}
1242+
1243+
voidPromiseHandlerTracker::makeWeakForObjectGroup(
1244+
int sessionId, const String16& objectGroup) {
1245+
for (auto& [id, handler] : m_promiseHandlers) {
1246+
if (handler->m_sessionId == sessionId &&
1247+
handler->m_objectGroup == objectGroup) {
1248+
handler->makeWeak(id);
1249+
}
1250+
}
1251+
}
1252+
1253+
voidPromiseHandlerTracker::makeWeakForSession(int sessionId) {
1254+
for (auto& [id, handler] : m_promiseHandlers) {
1255+
if (handler->m_sessionId == sessionId) handler->makeWeak(id);
1256+
}
1257+
}
1258+
12281259
voidPromiseHandlerTracker::sendFailure(
12291260
InjectedScript::ProtocolPromiseHandler* handler,
12301261
const protocol::DispatchResponse& response) const {

β€Ždeps/v8/src/inspector/injected-script.hβ€Ž

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -298,6 +298,9 @@ class PromiseHandlerTracker {
298298
Id create(Args&&... args);
299299
voiddiscard(Id id, DiscardReason reason);
300300
InjectedScript::ProtocolPromiseHandler* get(Id id) const;
301+
voidmakeWeakForContext(int executionContextId);
302+
voidmakeWeakForObjectGroup(int sessionId, const String16& objectGroup);
303+
voidmakeWeakForSession(int sessionId);
301304

302305
private:
303306
voidsendFailure(InjectedScript::ProtocolPromiseHandler* handler,

β€Ždeps/v8/src/inspector/v8-inspector-impl.ccβ€Ž

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,7 @@ void V8InspectorImpl::contextCollected(int groupId, int contextId) {
261261
session->runtimeAgent()->reportExecutionContextDestroyed(inspectedContext);
262262
});
263263
discardInspectedContext(groupId, contextId);
264+
m_promiseHandlerTracker.makeWeakForContext(contextId);
264265
}
265266

266267
voidV8InspectorImpl::resetContextGroup(int contextGroupId) {

β€Ždeps/v8/src/inspector/v8-inspector-session-impl.ccβ€Ž

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,7 @@ void V8InspectorSessionImpl::discardInjectedScripts() {
233233
[&sessionId](InspectedContext* context) {
234234
context->discardInjectedScript(sessionId);
235235
});
236+
m_inspector->promiseHandlerTracker().makeWeakForSession(sessionId);
236237
}
237238

238239
Response V8InspectorSessionImpl::findInjectedScript(
@@ -269,6 +270,10 @@ void V8InspectorSessionImpl::releaseObjectGroup(const String16& objectGroup) {
269270
InjectedScript* injectedScript = context->getInjectedScript(sessionId);
270271
if (injectedScript) injectedScript->releaseObjectGroup(objectGroup);
271272
});
273+
if (!objectGroup.isEmpty()) {
274+
m_inspector->promiseHandlerTracker().makeWeakForObjectGroup(m_sessionId,
275+
objectGroup);
276+
}
272277
}
273278

274279
boolV8InspectorSessionImpl::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+
constevaluationModes=[
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+
functionevaluate(Protocol,mode,expression,extraArguments={}){
35+
returnProtocol.Runtime.evaluate(
36+
{...mode.arguments, ...extraArguments, expression});
37+
}
38+
39+
InspectorTest.runAsyncTestSuite([
40+
asyncfunctiontestPromiseIsKeptAlive(){
41+
for(constmodeofevaluationModes){
42+
InspectorTest.log(`Using ${mode.name}:`);
43+
constevaluation=evaluate(Protocol,mode,mode.expression);
44+
45+
awaitProtocol.HeapProfiler.collectGarbage();
46+
awaitProtocol.Runtime.evaluate({expression: mode.resolveExpression});
47+
48+
InspectorTest.logMessage(awaitevaluation);
49+
}
50+
},
51+
52+
asyncfunctiontestObjectGroupReleaseMakesPromiseCollectible(){
53+
for(constmodeofevaluationModes){
54+
InspectorTest.log(`Using ${mode.name}:`);
55+
constevaluation=evaluate(
56+
Protocol,mode,mode.pendingExpression,
57+
{objectGroup: 'evaluation'});
58+
59+
awaitProtocol.Runtime.releaseObjectGroup({objectGroup: 'evaluation'});
60+
awaitProtocol.HeapProfiler.collectGarbage();
61+
62+
InspectorTest.logMessage(awaitevaluation);
63+
}
64+
},
65+
66+
asyncfunctiontestContextDestructionDiscardsPromise(){
67+
for(constmodeofevaluationModes){
68+
InspectorTest.log(`Using ${mode.name}:`);
69+
constcontextGroup=newInspectorTest.ContextGroup();
70+
constsession=contextGroup.connect();
71+
constevaluation=evaluate(
72+
session.Protocol,mode,mode.pendingExpression);
73+
74+
awaitsession.Protocol.Runtime.evaluate(
75+
{expression: 'inspector.fireContextDestroyed()'});
76+
77+
InspectorTest.logMessage(awaitevaluation);
78+
session.disconnect();
79+
}
80+
},
81+
82+
asyncfunctiontestSessionDestructionMakesPromiseCollectible(){
83+
constcontextGroup=newInspectorTest.ContextGroup();
84+
constsession1=contextGroup.connect();
85+
constsession2=contextGroup.connect();
86+
session1.Protocol.Runtime.evaluate({
87+
expression: evaluationModes[1].expression,
88+
awaitPromise: true,
89+
});
90+
91+
awaitsession2.Protocol.HeapProfiler.collectGarbage();
92+
letresult=awaitsession2.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+
awaitsession2.Protocol.HeapProfiler.collectGarbage();
99+
result=awaitsession2.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)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Commit 7c534bf

Browse files
avivkelleraduh95
authored andcommitted
deps: V8: backport 5177b10891e6
Original commit message: 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 <szuend@chromium.org> Reviewed-by: Simon ZΓΌnd <szuend@chromium.org> Reviewed-by: Kim-Anh Tran <kimanh@chromium.org> Cr-Commit-Position: refs/heads/main@{#108874} Refs: v8/v8@5177b10 Co-authored-by: avivkeller <me@aviv.sh> PR-URL: #64631 Reviewed-By: Daeyeon Jeong <daeyeon.dev@gmail.com> Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
1 parent 8aba475 commit 7c534bf

8 files changed

Lines changed: 218 additions & 7 deletions

File tree

β€Žcommon.gypiβ€Ž

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141

4242
# Reset this number to 0 on major V8 upgrades.
4343
# Increment by one for each non-official patch applied to deps/v8.
44-
'v8_embedder_string': '-node.51',
44+
'v8_embedder_string': '-node.52',
4545

4646
##### V8 defaults for Node.js #####
4747

β€Ždeps/v8/AUTHORSβ€Ž

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ Artem Kobzar <artem.kobzar@jetbrains.com>
7676
Arthur Islamov <arthur@islamov.ai>
7777
Asuka Shikina <shikina.asuka@gmail.com>
7878
Aurèle Barrière <aurele.barriere@gmail.com>
79+
Aviv Keller <me@aviv.sh>
7980
Bala Avulapati <bavulapati@gmail.com>
8081
Bangfu Tao <bangfu.tao@samsung.com>
8182
Ben Coe <bencoe@gmail.com>

β€Ždeps/v8/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+
voidmakeWeak(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
voidthenCallback(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();
@@ -285,9 +291,10 @@ class InjectedScript::ProtocolPromiseHandler {
285291
}
286292

287293
voidcatchCallback(v8::Local<v8::Value> result) {
294+
m_isActive = true;
288295
// Hold strongly onto m_evaluationResult now to prevent `cleanup` from
289296
// running in case any code below triggers GC.
290-
m_evaluationResult.ClearWeak();
297+
if (m_evaluationResult.IsWeak()) m_evaluationResult.ClearWeak();
291298
V8InspectorSessionImpl* session =
292299
m_inspector->sessionById(m_contextGroupId, m_sessionId);
293300
if (!session) return;
@@ -393,6 +400,7 @@ class InjectedScript::ProtocolPromiseHandler {
393400
std::unique_ptr<WrapOptions> m_wrapOptions;
394401
bool m_replMode;
395402
bool m_throwOnSideEffect;
403+
bool m_isActive = false;
396404
std::weak_ptr<EvaluateCallback> m_callback;
397405
v8::Global<v8::Promise> m_evaluationResult;
398406
};
@@ -1190,8 +1198,7 @@ template <typename... Args>
11901198
PromiseHandlerTracker::Id PromiseHandlerTracker::create(Args&&... args) {
11911199
Id id = m_lastUsedId++;
11921200
InjectedScript::ProtocolPromiseHandler* handler =
1193-
newInjectedScript::ProtocolPromiseHandler(id,
1194-
std::forward<Args>(args)...);
1201+
newInjectedScript::ProtocolPromiseHandler(std::forward<Args>(args)...);
11951202
m_promiseHandlers.emplace(id, handler);
11961203
return id;
11971204
}
@@ -1225,6 +1232,30 @@ InjectedScript::ProtocolPromiseHandler* PromiseHandlerTracker::get(
12251232
return iter->second.get();
12261233
}
12271234

1235+
voidPromiseHandlerTracker::makeWeakForContext(int executionContextId) {
1236+
for (auto& [id, handler] : m_promiseHandlers) {
1237+
if (handler->m_executionContextId == executionContextId) {
1238+
handler->makeWeak(id);
1239+
}
1240+
}
1241+
}
1242+
1243+
voidPromiseHandlerTracker::makeWeakForObjectGroup(
1244+
int sessionId, const String16& objectGroup) {
1245+
for (auto& [id, handler] : m_promiseHandlers) {
1246+
if (handler->m_sessionId == sessionId &&
1247+
handler->m_objectGroup == objectGroup) {
1248+
handler->makeWeak(id);
1249+
}
1250+
}
1251+
}
1252+
1253+
voidPromiseHandlerTracker::makeWeakForSession(int sessionId) {
1254+
for (auto& [id, handler] : m_promiseHandlers) {
1255+
if (handler->m_sessionId == sessionId) handler->makeWeak(id);
1256+
}
1257+
}
1258+
12281259
voidPromiseHandlerTracker::sendFailure(
12291260
InjectedScript::ProtocolPromiseHandler* handler,
12301261
const protocol::DispatchResponse& response) const {

β€Ždeps/v8/src/inspector/injected-script.hβ€Ž

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -298,6 +298,9 @@ class PromiseHandlerTracker {
298298
Id create(Args&&... args);
299299
voiddiscard(Id id, DiscardReason reason);
300300
InjectedScript::ProtocolPromiseHandler* get(Id id) const;
301+
voidmakeWeakForContext(int executionContextId);
302+
voidmakeWeakForObjectGroup(int sessionId, const String16& objectGroup);
303+
voidmakeWeakForSession(int sessionId);
301304

302305
private:
303306
voidsendFailure(InjectedScript::ProtocolPromiseHandler* handler,

β€Ždeps/v8/src/inspector/v8-inspector-impl.ccβ€Ž

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,7 @@ void V8InspectorImpl::contextCollected(int groupId, int contextId) {
261261
session->runtimeAgent()->reportExecutionContextDestroyed(inspectedContext);
262262
});
263263
discardInspectedContext(groupId, contextId);
264+
m_promiseHandlerTracker.makeWeakForContext(contextId);
264265
}
265266

266267
voidV8InspectorImpl::resetContextGroup(int contextGroupId) {

β€Ždeps/v8/src/inspector/v8-inspector-session-impl.ccβ€Ž

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,7 @@ void V8InspectorSessionImpl::discardInjectedScripts() {
233233
[&sessionId](InspectedContext* context) {
234234
context->discardInjectedScript(sessionId);
235235
});
236+
m_inspector->promiseHandlerTracker().makeWeakForSession(sessionId);
236237
}
237238

238239
Response V8InspectorSessionImpl::findInjectedScript(
@@ -269,6 +270,10 @@ void V8InspectorSessionImpl::releaseObjectGroup(const String16& objectGroup) {
269270
InjectedScript* injectedScript = context->getInjectedScript(sessionId);
270271
if (injectedScript) injectedScript->releaseObjectGroup(objectGroup);
271272
});
273+
if (!objectGroup.isEmpty()) {
274+
m_inspector->promiseHandlerTracker().makeWeakForObjectGroup(m_sessionId,
275+
objectGroup);
276+
}
272277
}
273278

274279
boolV8InspectorSessionImpl::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+
constevaluationModes=[
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+
functionevaluate(Protocol,mode,expression,extraArguments={}){
35+
returnProtocol.Runtime.evaluate(
36+
{...mode.arguments, ...extraArguments, expression});
37+
}
38+
39+
InspectorTest.runAsyncTestSuite([
40+
asyncfunctiontestPromiseIsKeptAlive(){
41+
for(constmodeofevaluationModes){
42+
InspectorTest.log(`Using ${mode.name}:`);
43+
constevaluation=evaluate(Protocol,mode,mode.expression);
44+
45+
awaitProtocol.HeapProfiler.collectGarbage();
46+
awaitProtocol.Runtime.evaluate({expression: mode.resolveExpression});
47+
48+
InspectorTest.logMessage(awaitevaluation);
49+
}
50+
},
51+
52+
asyncfunctiontestObjectGroupReleaseMakesPromiseCollectible(){
53+
for(constmodeofevaluationModes){
54+
InspectorTest.log(`Using ${mode.name}:`);
55+
constevaluation=evaluate(
56+
Protocol,mode,mode.pendingExpression,
57+
{objectGroup: 'evaluation'});
58+
59+
awaitProtocol.Runtime.releaseObjectGroup({objectGroup: 'evaluation'});
60+
awaitProtocol.HeapProfiler.collectGarbage();
61+
62+
InspectorTest.logMessage(awaitevaluation);
63+
}
64+
},
65+
66+
asyncfunctiontestContextDestructionDiscardsPromise(){
67+
for(constmodeofevaluationModes){
68+
InspectorTest.log(`Using ${mode.name}:`);
69+
constcontextGroup=newInspectorTest.ContextGroup();
70+
constsession=contextGroup.connect();
71+
constevaluation=evaluate(
72+
session.Protocol,mode,mode.pendingExpression);
73+
74+
awaitsession.Protocol.Runtime.evaluate(
75+
{expression: 'inspector.fireContextDestroyed()'});
76+
77+
InspectorTest.logMessage(awaitevaluation);
78+
session.disconnect();
79+
}
80+
},
81+
82+
asyncfunctiontestSessionDestructionMakesPromiseCollectible(){
83+
constcontextGroup=newInspectorTest.ContextGroup();
84+
constsession1=contextGroup.connect();
85+
constsession2=contextGroup.connect();
86+
session1.Protocol.Runtime.evaluate({
87+
expression: evaluationModes[1].expression,
88+
awaitPromise: true,
89+
});
90+
91+
awaitsession2.Protocol.HeapProfiler.collectGarbage();
92+
letresult=awaitsession2.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+
awaitsession2.Protocol.HeapProfiler.collectGarbage();
99+
result=awaitsession2.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)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 7c534bf

Browse files
avivkelleraduh95
authored andcommitted
deps: V8: backport 5177b10891e6
Original commit message: 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 <szuend@chromium.org> Reviewed-by: Simon ZΓΌnd <szuend@chromium.org> Reviewed-by: Kim-Anh Tran <kimanh@chromium.org> Cr-Commit-Position: refs/heads/main@{#108874} Refs: v8/v8@5177b10 Co-authored-by: avivkeller <me@aviv.sh> PR-URL: #64631 Reviewed-By: Daeyeon Jeong <daeyeon.dev@gmail.com> Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
1 parent 8aba475 commit 7c534bf

8 files changed

Lines changed: 218 additions & 7 deletions

File tree

β€Žcommon.gypiβ€Ž

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141

4242
# Reset this number to 0 on major V8 upgrades.
4343
# Increment by one for each non-official patch applied to deps/v8.
44-
'v8_embedder_string': '-node.51',
44+
'v8_embedder_string': '-node.52',
4545

4646
##### V8 defaults for Node.js #####
4747

β€Ždeps/v8/AUTHORSβ€Ž

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ Artem Kobzar <artem.kobzar@jetbrains.com>
7676
Arthur Islamov <arthur@islamov.ai>
7777
Asuka Shikina <shikina.asuka@gmail.com>
7878
Aurèle Barrière <aurele.barriere@gmail.com>
79+
Aviv Keller <me@aviv.sh>
7980
Bala Avulapati <bavulapati@gmail.com>
8081
Bangfu Tao <bangfu.tao@samsung.com>
8182
Ben Coe <bencoe@gmail.com>

β€Ždeps/v8/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+
voidmakeWeak(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
voidthenCallback(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();
@@ -285,9 +291,10 @@ class InjectedScript::ProtocolPromiseHandler {
285291
}
286292

287293
voidcatchCallback(v8::Local<v8::Value> result) {
294+
m_isActive = true;
288295
// Hold strongly onto m_evaluationResult now to prevent `cleanup` from
289296
// running in case any code below triggers GC.
290-
m_evaluationResult.ClearWeak();
297+
if (m_evaluationResult.IsWeak()) m_evaluationResult.ClearWeak();
291298
V8InspectorSessionImpl* session =
292299
m_inspector->sessionById(m_contextGroupId, m_sessionId);
293300
if (!session) return;
@@ -393,6 +400,7 @@ class InjectedScript::ProtocolPromiseHandler {
393400
std::unique_ptr<WrapOptions> m_wrapOptions;
394401
bool m_replMode;
395402
bool m_throwOnSideEffect;
403+
bool m_isActive = false;
396404
std::weak_ptr<EvaluateCallback> m_callback;
397405
v8::Global<v8::Promise> m_evaluationResult;
398406
};
@@ -1190,8 +1198,7 @@ template <typename... Args>
11901198
PromiseHandlerTracker::Id PromiseHandlerTracker::create(Args&&... args) {
11911199
Id id = m_lastUsedId++;
11921200
InjectedScript::ProtocolPromiseHandler* handler =
1193-
newInjectedScript::ProtocolPromiseHandler(id,
1194-
std::forward<Args>(args)...);
1201+
newInjectedScript::ProtocolPromiseHandler(std::forward<Args>(args)...);
11951202
m_promiseHandlers.emplace(id, handler);
11961203
return id;
11971204
}
@@ -1225,6 +1232,30 @@ InjectedScript::ProtocolPromiseHandler* PromiseHandlerTracker::get(
12251232
return iter->second.get();
12261233
}
12271234

1235+
voidPromiseHandlerTracker::makeWeakForContext(int executionContextId) {
1236+
for (auto& [id, handler] : m_promiseHandlers) {
1237+
if (handler->m_executionContextId == executionContextId) {
1238+
handler->makeWeak(id);
1239+
}
1240+
}
1241+
}
1242+
1243+
voidPromiseHandlerTracker::makeWeakForObjectGroup(
1244+
int sessionId, const String16& objectGroup) {
1245+
for (auto& [id, handler] : m_promiseHandlers) {
1246+
if (handler->m_sessionId == sessionId &&
1247+
handler->m_objectGroup == objectGroup) {
1248+
handler->makeWeak(id);
1249+
}
1250+
}
1251+
}
1252+
1253+
voidPromiseHandlerTracker::makeWeakForSession(int sessionId) {
1254+
for (auto& [id, handler] : m_promiseHandlers) {
1255+
if (handler->m_sessionId == sessionId) handler->makeWeak(id);
1256+
}
1257+
}
1258+
12281259
voidPromiseHandlerTracker::sendFailure(
12291260
InjectedScript::ProtocolPromiseHandler* handler,
12301261
const protocol::DispatchResponse& response) const {

β€Ždeps/v8/src/inspector/injected-script.hβ€Ž

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -298,6 +298,9 @@ class PromiseHandlerTracker {
298298
Id create(Args&&... args);
299299
voiddiscard(Id id, DiscardReason reason);
300300
InjectedScript::ProtocolPromiseHandler* get(Id id) const;
301+
voidmakeWeakForContext(int executionContextId);
302+
voidmakeWeakForObjectGroup(int sessionId, const String16& objectGroup);
303+
voidmakeWeakForSession(int sessionId);
301304

302305
private:
303306
voidsendFailure(InjectedScript::ProtocolPromiseHandler* handler,

β€Ždeps/v8/src/inspector/v8-inspector-impl.ccβ€Ž

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,7 @@ void V8InspectorImpl::contextCollected(int groupId, int contextId) {
261261
session->runtimeAgent()->reportExecutionContextDestroyed(inspectedContext);
262262
});
263263
discardInspectedContext(groupId, contextId);
264+
m_promiseHandlerTracker.makeWeakForContext(contextId);
264265
}
265266

266267
voidV8InspectorImpl::resetContextGroup(int contextGroupId) {

β€Ždeps/v8/src/inspector/v8-inspector-session-impl.ccβ€Ž

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,7 @@ void V8InspectorSessionImpl::discardInjectedScripts() {
233233
[&sessionId](InspectedContext* context) {
234234
context->discardInjectedScript(sessionId);
235235
});
236+
m_inspector->promiseHandlerTracker().makeWeakForSession(sessionId);
236237
}
237238

238239
Response V8InspectorSessionImpl::findInjectedScript(
@@ -269,6 +270,10 @@ void V8InspectorSessionImpl::releaseObjectGroup(const String16& objectGroup) {
269270
InjectedScript* injectedScript = context->getInjectedScript(sessionId);
270271
if (injectedScript) injectedScript->releaseObjectGroup(objectGroup);
271272
});
273+
if (!objectGroup.isEmpty()) {
274+
m_inspector->promiseHandlerTracker().makeWeakForObjectGroup(m_sessionId,
275+
objectGroup);
276+
}
272277
}
273278

274279
boolV8InspectorSessionImpl::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+
constevaluationModes=[
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+
functionevaluate(Protocol,mode,expression,extraArguments={}){
35+
returnProtocol.Runtime.evaluate(
36+
{...mode.arguments, ...extraArguments, expression});
37+
}
38+
39+
InspectorTest.runAsyncTestSuite([
40+
asyncfunctiontestPromiseIsKeptAlive(){
41+
for(constmodeofevaluationModes){
42+
InspectorTest.log(`Using ${mode.name}:`);
43+
constevaluation=evaluate(Protocol,mode,mode.expression);
44+
45+
awaitProtocol.HeapProfiler.collectGarbage();
46+
awaitProtocol.Runtime.evaluate({expression: mode.resolveExpression});
47+
48+
InspectorTest.logMessage(awaitevaluation);
49+
}
50+
},
51+
52+
asyncfunctiontestObjectGroupReleaseMakesPromiseCollectible(){
53+
for(constmodeofevaluationModes){
54+
InspectorTest.log(`Using ${mode.name}:`);
55+
constevaluation=evaluate(
56+
Protocol,mode,mode.pendingExpression,
57+
{objectGroup: 'evaluation'});
58+
59+
awaitProtocol.Runtime.releaseObjectGroup({objectGroup: 'evaluation'});
60+
awaitProtocol.HeapProfiler.collectGarbage();
61+
62+
InspectorTest.logMessage(awaitevaluation);
63+
}
64+
},
65+
66+
asyncfunctiontestContextDestructionDiscardsPromise(){
67+
for(constmodeofevaluationModes){
68+
InspectorTest.log(`Using ${mode.name}:`);
69+
constcontextGroup=newInspectorTest.ContextGroup();
70+
constsession=contextGroup.connect();
71+
constevaluation=evaluate(
72+
session.Protocol,mode,mode.pendingExpression);
73+
74+
awaitsession.Protocol.Runtime.evaluate(
75+
{expression: 'inspector.fireContextDestroyed()'});
76+
77+
InspectorTest.logMessage(awaitevaluation);
78+
session.disconnect();
79+
}
80+
},
81+
82+
asyncfunctiontestSessionDestructionMakesPromiseCollectible(){
83+
constcontextGroup=newInspectorTest.ContextGroup();
84+
constsession1=contextGroup.connect();
85+
constsession2=contextGroup.connect();
86+
session1.Protocol.Runtime.evaluate({
87+
expression: evaluationModes[1].expression,
88+
awaitPromise: true,
89+
});
90+
91+
awaitsession2.Protocol.HeapProfiler.collectGarbage();
92+
letresult=awaitsession2.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+
awaitsession2.Protocol.HeapProfiler.collectGarbage();
99+
result=awaitsession2.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)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 7c534bf

Browse files
avivkelleraduh95
authored andcommitted
deps: V8: backport 5177b10891e6
Original commit message: 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 <szuend@chromium.org> Reviewed-by: Simon ZΓΌnd <szuend@chromium.org> Reviewed-by: Kim-Anh Tran <kimanh@chromium.org> Cr-Commit-Position: refs/heads/main@{#108874} Refs: v8/v8@5177b10 Co-authored-by: avivkeller <me@aviv.sh> PR-URL: #64631 Reviewed-By: Daeyeon Jeong <daeyeon.dev@gmail.com> Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
1 parent 8aba475 commit 7c534bf

8 files changed

Lines changed: 218 additions & 7 deletions

File tree

β€Žcommon.gypiβ€Ž

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141

4242
# Reset this number to 0 on major V8 upgrades.
4343
# Increment by one for each non-official patch applied to deps/v8.
44-
'v8_embedder_string': '-node.51',
44+
'v8_embedder_string': '-node.52',
4545

4646
##### V8 defaults for Node.js #####
4747

β€Ždeps/v8/AUTHORSβ€Ž

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ Artem Kobzar <artem.kobzar@jetbrains.com>
7676
Arthur Islamov <arthur@islamov.ai>
7777
Asuka Shikina <shikina.asuka@gmail.com>
7878
Aurèle Barrière <aurele.barriere@gmail.com>
79+
Aviv Keller <me@aviv.sh>
7980
Bala Avulapati <bavulapati@gmail.com>
8081
Bangfu Tao <bangfu.tao@samsung.com>
8182
Ben Coe <bencoe@gmail.com>

β€Ždeps/v8/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+
voidmakeWeak(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
voidthenCallback(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();
@@ -285,9 +291,10 @@ class InjectedScript::ProtocolPromiseHandler {
285291
}
286292

287293
voidcatchCallback(v8::Local<v8::Value> result) {
294+
m_isActive = true;
288295
// Hold strongly onto m_evaluationResult now to prevent `cleanup` from
289296
// running in case any code below triggers GC.
290-
m_evaluationResult.ClearWeak();
297+
if (m_evaluationResult.IsWeak()) m_evaluationResult.ClearWeak();
291298
V8InspectorSessionImpl* session =
292299
m_inspector->sessionById(m_contextGroupId, m_sessionId);
293300
if (!session) return;
@@ -393,6 +400,7 @@ class InjectedScript::ProtocolPromiseHandler {
393400
std::unique_ptr<WrapOptions> m_wrapOptions;
394401
bool m_replMode;
395402
bool m_throwOnSideEffect;
403+
bool m_isActive = false;
396404
std::weak_ptr<EvaluateCallback> m_callback;
397405
v8::Global<v8::Promise> m_evaluationResult;
398406
};
@@ -1190,8 +1198,7 @@ template <typename... Args>
11901198
PromiseHandlerTracker::Id PromiseHandlerTracker::create(Args&&... args) {
11911199
Id id = m_lastUsedId++;
11921200
InjectedScript::ProtocolPromiseHandler* handler =
1193-
newInjectedScript::ProtocolPromiseHandler(id,
1194-
std::forward<Args>(args)...);
1201+
newInjectedScript::ProtocolPromiseHandler(std::forward<Args>(args)...);
11951202
m_promiseHandlers.emplace(id, handler);
11961203
return id;
11971204
}
@@ -1225,6 +1232,30 @@ InjectedScript::ProtocolPromiseHandler* PromiseHandlerTracker::get(
12251232
return iter->second.get();
12261233
}
12271234

1235+
voidPromiseHandlerTracker::makeWeakForContext(int executionContextId) {
1236+
for (auto& [id, handler] : m_promiseHandlers) {
1237+
if (handler->m_executionContextId == executionContextId) {
1238+
handler->makeWeak(id);
1239+
}
1240+
}
1241+
}
1242+
1243+
voidPromiseHandlerTracker::makeWeakForObjectGroup(
1244+
int sessionId, const String16& objectGroup) {
1245+
for (auto& [id, handler] : m_promiseHandlers) {
1246+
if (handler->m_sessionId == sessionId &&
1247+
handler->m_objectGroup == objectGroup) {
1248+
handler->makeWeak(id);
1249+
}
1250+
}
1251+
}
1252+
1253+
voidPromiseHandlerTracker::makeWeakForSession(int sessionId) {
1254+
for (auto& [id, handler] : m_promiseHandlers) {
1255+
if (handler->m_sessionId == sessionId) handler->makeWeak(id);
1256+
}
1257+
}
1258+
12281259
voidPromiseHandlerTracker::sendFailure(
12291260
InjectedScript::ProtocolPromiseHandler* handler,
12301261
const protocol::DispatchResponse& response) const {

β€Ždeps/v8/src/inspector/injected-script.hβ€Ž

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -298,6 +298,9 @@ class PromiseHandlerTracker {
298298
Id create(Args&&... args);
299299
voiddiscard(Id id, DiscardReason reason);
300300
InjectedScript::ProtocolPromiseHandler* get(Id id) const;
301+
voidmakeWeakForContext(int executionContextId);
302+
voidmakeWeakForObjectGroup(int sessionId, const String16& objectGroup);
303+
voidmakeWeakForSession(int sessionId);
301304

302305
private:
303306
voidsendFailure(InjectedScript::ProtocolPromiseHandler* handler,

β€Ždeps/v8/src/inspector/v8-inspector-impl.ccβ€Ž

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,7 @@ void V8InspectorImpl::contextCollected(int groupId, int contextId) {
261261
session->runtimeAgent()->reportExecutionContextDestroyed(inspectedContext);
262262
});
263263
discardInspectedContext(groupId, contextId);
264+
m_promiseHandlerTracker.makeWeakForContext(contextId);
264265
}
265266

266267
voidV8InspectorImpl::resetContextGroup(int contextGroupId) {

β€Ždeps/v8/src/inspector/v8-inspector-session-impl.ccβ€Ž

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,7 @@ void V8InspectorSessionImpl::discardInjectedScripts() {
233233
[&sessionId](InspectedContext* context) {
234234
context->discardInjectedScript(sessionId);
235235
});
236+
m_inspector->promiseHandlerTracker().makeWeakForSession(sessionId);
236237
}
237238

238239
Response V8InspectorSessionImpl::findInjectedScript(
@@ -269,6 +270,10 @@ void V8InspectorSessionImpl::releaseObjectGroup(const String16& objectGroup) {
269270
InjectedScript* injectedScript = context->getInjectedScript(sessionId);
270271
if (injectedScript) injectedScript->releaseObjectGroup(objectGroup);
271272
});
273+
if (!objectGroup.isEmpty()) {
274+
m_inspector->promiseHandlerTracker().makeWeakForObjectGroup(m_sessionId,
275+
objectGroup);
276+
}
272277
}
273278

274279
boolV8InspectorSessionImpl::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+
constevaluationModes=[
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+
functionevaluate(Protocol,mode,expression,extraArguments={}){
35+
returnProtocol.Runtime.evaluate(
36+
{...mode.arguments, ...extraArguments, expression});
37+
}
38+
39+
InspectorTest.runAsyncTestSuite([
40+
asyncfunctiontestPromiseIsKeptAlive(){
41+
for(constmodeofevaluationModes){
42+
InspectorTest.log(`Using ${mode.name}:`);
43+
constevaluation=evaluate(Protocol,mode,mode.expression);
44+
45+
awaitProtocol.HeapProfiler.collectGarbage();
46+
awaitProtocol.Runtime.evaluate({expression: mode.resolveExpression});
47+
48+
InspectorTest.logMessage(awaitevaluation);
49+
}
50+
},
51+
52+
asyncfunctiontestObjectGroupReleaseMakesPromiseCollectible(){
53+
for(constmodeofevaluationModes){
54+
InspectorTest.log(`Using ${mode.name}:`);
55+
constevaluation=evaluate(
56+
Protocol,mode,mode.pendingExpression,
57+
{objectGroup: 'evaluation'});
58+
59+
awaitProtocol.Runtime.releaseObjectGroup({objectGroup: 'evaluation'});
60+
awaitProtocol.HeapProfiler.collectGarbage();
61+
62+
InspectorTest.logMessage(awaitevaluation);
63+
}
64+
},
65+
66+
asyncfunctiontestContextDestructionDiscardsPromise(){
67+
for(constmodeofevaluationModes){
68+
InspectorTest.log(`Using ${mode.name}:`);
69+
constcontextGroup=newInspectorTest.ContextGroup();
70+
constsession=contextGroup.connect();
71+
constevaluation=evaluate(
72+
session.Protocol,mode,mode.pendingExpression);
73+
74+
awaitsession.Protocol.Runtime.evaluate(
75+
{expression: 'inspector.fireContextDestroyed()'});
76+
77+
InspectorTest.logMessage(awaitevaluation);
78+
session.disconnect();
79+
}
80+
},
81+
82+
asyncfunctiontestSessionDestructionMakesPromiseCollectible(){
83+
constcontextGroup=newInspectorTest.ContextGroup();
84+
constsession1=contextGroup.connect();
85+
constsession2=contextGroup.connect();
86+
session1.Protocol.Runtime.evaluate({
87+
expression: evaluationModes[1].expression,
88+
awaitPromise: true,
89+
});
90+
91+
awaitsession2.Protocol.HeapProfiler.collectGarbage();
92+
letresult=awaitsession2.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+
awaitsession2.Protocol.HeapProfiler.collectGarbage();
99+
result=awaitsession2.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)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Commit 7c534bf

Browse files
avivkelleraduh95
authored andcommitted
deps: V8: backport 5177b10891e6
Original commit message: 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 <szuend@chromium.org> Reviewed-by: Simon ZΓΌnd <szuend@chromium.org> Reviewed-by: Kim-Anh Tran <kimanh@chromium.org> Cr-Commit-Position: refs/heads/main@{#108874} Refs: v8/v8@5177b10 Co-authored-by: avivkeller <me@aviv.sh> PR-URL: #64631 Reviewed-By: Daeyeon Jeong <daeyeon.dev@gmail.com> Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
1 parent 8aba475 commit 7c534bf

8 files changed

Lines changed: 218 additions & 7 deletions

File tree

β€Žcommon.gypiβ€Ž

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141

4242
# Reset this number to 0 on major V8 upgrades.
4343
# Increment by one for each non-official patch applied to deps/v8.
44-
'v8_embedder_string': '-node.51',
44+
'v8_embedder_string': '-node.52',
4545

4646
##### V8 defaults for Node.js #####
4747

β€Ždeps/v8/AUTHORSβ€Ž

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ Artem Kobzar <artem.kobzar@jetbrains.com>
7676
Arthur Islamov <arthur@islamov.ai>
7777
Asuka Shikina <shikina.asuka@gmail.com>
7878
Aurèle Barrière <aurele.barriere@gmail.com>
79+
Aviv Keller <me@aviv.sh>
7980
Bala Avulapati <bavulapati@gmail.com>
8081
Bangfu Tao <bangfu.tao@samsung.com>
8182
Ben Coe <bencoe@gmail.com>

β€Ždeps/v8/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+
voidmakeWeak(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
voidthenCallback(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();
@@ -285,9 +291,10 @@ class InjectedScript::ProtocolPromiseHandler {
285291
}
286292

287293
voidcatchCallback(v8::Local<v8::Value> result) {
294+
m_isActive = true;
288295
// Hold strongly onto m_evaluationResult now to prevent `cleanup` from
289296
// running in case any code below triggers GC.
290-
m_evaluationResult.ClearWeak();
297+
if (m_evaluationResult.IsWeak()) m_evaluationResult.ClearWeak();
291298
V8InspectorSessionImpl* session =
292299
m_inspector->sessionById(m_contextGroupId, m_sessionId);
293300
if (!session) return;
@@ -393,6 +400,7 @@ class InjectedScript::ProtocolPromiseHandler {
393400
std::unique_ptr<WrapOptions> m_wrapOptions;
394401
bool m_replMode;
395402
bool m_throwOnSideEffect;
403+
bool m_isActive = false;
396404
std::weak_ptr<EvaluateCallback> m_callback;
397405
v8::Global<v8::Promise> m_evaluationResult;
398406
};
@@ -1190,8 +1198,7 @@ template <typename... Args>
11901198
PromiseHandlerTracker::Id PromiseHandlerTracker::create(Args&&... args) {
11911199
Id id = m_lastUsedId++;
11921200
InjectedScript::ProtocolPromiseHandler* handler =
1193-
newInjectedScript::ProtocolPromiseHandler(id,
1194-
std::forward<Args>(args)...);
1201+
newInjectedScript::ProtocolPromiseHandler(std::forward<Args>(args)...);
11951202
m_promiseHandlers.emplace(id, handler);
11961203
return id;
11971204
}
@@ -1225,6 +1232,30 @@ InjectedScript::ProtocolPromiseHandler* PromiseHandlerTracker::get(
12251232
return iter->second.get();
12261233
}
12271234

1235+
voidPromiseHandlerTracker::makeWeakForContext(int executionContextId) {
1236+
for (auto& [id, handler] : m_promiseHandlers) {
1237+
if (handler->m_executionContextId == executionContextId) {
1238+
handler->makeWeak(id);
1239+
}
1240+
}
1241+
}
1242+
1243+
voidPromiseHandlerTracker::makeWeakForObjectGroup(
1244+
int sessionId, const String16& objectGroup) {
1245+
for (auto& [id, handler] : m_promiseHandlers) {
1246+
if (handler->m_sessionId == sessionId &&
1247+
handler->m_objectGroup == objectGroup) {
1248+
handler->makeWeak(id);
1249+
}
1250+
}
1251+
}
1252+
1253+
voidPromiseHandlerTracker::makeWeakForSession(int sessionId) {
1254+
for (auto& [id, handler] : m_promiseHandlers) {
1255+
if (handler->m_sessionId == sessionId) handler->makeWeak(id);
1256+
}
1257+
}
1258+
12281259
voidPromiseHandlerTracker::sendFailure(
12291260
InjectedScript::ProtocolPromiseHandler* handler,
12301261
const protocol::DispatchResponse& response) const {

β€Ždeps/v8/src/inspector/injected-script.hβ€Ž

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -298,6 +298,9 @@ class PromiseHandlerTracker {
298298
Id create(Args&&... args);
299299
voiddiscard(Id id, DiscardReason reason);
300300
InjectedScript::ProtocolPromiseHandler* get(Id id) const;
301+
voidmakeWeakForContext(int executionContextId);
302+
voidmakeWeakForObjectGroup(int sessionId, const String16& objectGroup);
303+
voidmakeWeakForSession(int sessionId);
301304

302305
private:
303306
voidsendFailure(InjectedScript::ProtocolPromiseHandler* handler,

β€Ždeps/v8/src/inspector/v8-inspector-impl.ccβ€Ž

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,7 @@ void V8InspectorImpl::contextCollected(int groupId, int contextId) {
261261
session->runtimeAgent()->reportExecutionContextDestroyed(inspectedContext);
262262
});
263263
discardInspectedContext(groupId, contextId);
264+
m_promiseHandlerTracker.makeWeakForContext(contextId);
264265
}
265266

266267
voidV8InspectorImpl::resetContextGroup(int contextGroupId) {

β€Ždeps/v8/src/inspector/v8-inspector-session-impl.ccβ€Ž

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,7 @@ void V8InspectorSessionImpl::discardInjectedScripts() {
233233
[&sessionId](InspectedContext* context) {
234234
context->discardInjectedScript(sessionId);
235235
});
236+
m_inspector->promiseHandlerTracker().makeWeakForSession(sessionId);
236237
}
237238

238239
Response V8InspectorSessionImpl::findInjectedScript(
@@ -269,6 +270,10 @@ void V8InspectorSessionImpl::releaseObjectGroup(const String16& objectGroup) {
269270
InjectedScript* injectedScript = context->getInjectedScript(sessionId);
270271
if (injectedScript) injectedScript->releaseObjectGroup(objectGroup);
271272
});
273+
if (!objectGroup.isEmpty()) {
274+
m_inspector->promiseHandlerTracker().makeWeakForObjectGroup(m_sessionId,
275+
objectGroup);
276+
}
272277
}
273278

274279
boolV8InspectorSessionImpl::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+
constevaluationModes=[
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+
functionevaluate(Protocol,mode,expression,extraArguments={}){
35+
returnProtocol.Runtime.evaluate(
36+
{...mode.arguments, ...extraArguments, expression});
37+
}
38+
39+
InspectorTest.runAsyncTestSuite([
40+
asyncfunctiontestPromiseIsKeptAlive(){
41+
for(constmodeofevaluationModes){
42+
InspectorTest.log(`Using ${mode.name}:`);
43+
constevaluation=evaluate(Protocol,mode,mode.expression);
44+
45+
awaitProtocol.HeapProfiler.collectGarbage();
46+
awaitProtocol.Runtime.evaluate({expression: mode.resolveExpression});
47+
48+
InspectorTest.logMessage(awaitevaluation);
49+
}
50+
},
51+
52+
asyncfunctiontestObjectGroupReleaseMakesPromiseCollectible(){
53+
for(constmodeofevaluationModes){
54+
InspectorTest.log(`Using ${mode.name}:`);
55+
constevaluation=evaluate(
56+
Protocol,mode,mode.pendingExpression,
57+
{objectGroup: 'evaluation'});
58+
59+
awaitProtocol.Runtime.releaseObjectGroup({objectGroup: 'evaluation'});
60+
awaitProtocol.HeapProfiler.collectGarbage();
61+
62+
InspectorTest.logMessage(awaitevaluation);
63+
}
64+
},
65+
66+
asyncfunctiontestContextDestructionDiscardsPromise(){
67+
for(constmodeofevaluationModes){
68+
InspectorTest.log(`Using ${mode.name}:`);
69+
constcontextGroup=newInspectorTest.ContextGroup();
70+
constsession=contextGroup.connect();
71+
constevaluation=evaluate(
72+
session.Protocol,mode,mode.pendingExpression);
73+
74+
awaitsession.Protocol.Runtime.evaluate(
75+
{expression: 'inspector.fireContextDestroyed()'});
76+
77+
InspectorTest.logMessage(awaitevaluation);
78+
session.disconnect();
79+
}
80+
},
81+
82+
asyncfunctiontestSessionDestructionMakesPromiseCollectible(){
83+
constcontextGroup=newInspectorTest.ContextGroup();
84+
constsession1=contextGroup.connect();
85+
constsession2=contextGroup.connect();
86+
session1.Protocol.Runtime.evaluate({
87+
expression: evaluationModes[1].expression,
88+
awaitPromise: true,
89+
});
90+
91+
awaitsession2.Protocol.HeapProfiler.collectGarbage();
92+
letresult=awaitsession2.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+
awaitsession2.Protocol.HeapProfiler.collectGarbage();
99+
result=awaitsession2.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)