Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

worker: handle detached MessagePort from a different context #49150

Merged
merged 1 commit into from
Oct 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/node_messaging.cc
Original file line number Diff line number Diff line change
Expand Up @@ -789,6 +789,13 @@ MaybeLocal<Value> MessagePort::ReceiveMessage(Local<Context> context,

void MessagePort::OnMessage(MessageProcessingMode mode) {
Debug(this, "Running MessagePort::OnMessage()");
// Maybe the async handle was triggered empty or more than needed.
// The data_ could be freed or, the handle has been/is being closed.
// A possible case for this, is transfer the MessagePort to another
// context, it will call the constructor and trigger the async handle empty.
// Because all data was sent from the preivous context.
if (IsDetached()) return;

HandleScope handle_scope(env()->isolate());
Local<Context> context =
object(env()->isolate())->GetCreationContext().ToLocalChecked();
Expand Down
30 changes: 28 additions & 2 deletions test/parallel/test-worker-workerdata-messageport.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
'use strict';

require('../common');
const assert = require('assert');
const assert = require('node:assert');

const {
Worker, MessageChannel
} = require('worker_threads');
} = require('node:worker_threads');

const channel = new MessageChannel();
const workerData = { mesage: channel.port1 };
Expand Down Expand Up @@ -59,3 +59,29 @@ const meowScript = () => 'meow';
'listed in transferList'
});
}

{
// Should not crash when MessagePort is transferred to another context.
// https://github.com/nodejs/node/issues/49075
const channel = new MessageChannel();
new Worker(`
const { runInContext, createContext } = require('node:vm')
const { workerData } = require('worker_threads');
const context = createContext(Object.create(null));
context.messagePort = workerData.messagePort;
runInContext(
\`messagePort.postMessage("Meow")\`,
context,
{ displayErrors: true }
);
`, {
eval: true,
workerData: { messagePort: channel.port2 },
transferList: [channel.port2]
});
channel.port1.on(
'message',
(message) =>
assert.strictEqual(message, 'Meow')
);
}