Skip to content

Commit

Permalink
worker: handle detached MessagePort from a different context
Browse files Browse the repository at this point in the history
When `worker.moveMessagePortToContext` is used, the async handle
associated with the port, will be triggered more than needed (at least
one more time) and with null data. That can be avoided by simply
checking that the data is present and the port is not detached.

Fixes: #49075
Signed-off-by: Juan José Arboleda <[email protected]>
  • Loading branch information
juanarbol committed Aug 13, 2023
1 parent 6432060 commit f100bf8
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
5 changes: 5 additions & 0 deletions src/node_messaging.cc
Original file line number Diff line number Diff line change
Expand Up @@ -795,6 +795,11 @@ void MessagePort::OnMessage(MessageProcessingMode mode) {

size_t processing_limit;
if (mode == MessageProcessingMode::kNormalOperation) {
// Maybe the async handle was triggered empty or more than needed
// (called twiced on a new context).
if (GetTransferMode() == TransferMode::kDisallowCloneAndTransfer || !data_)
return;

Mutex::ScopedLock(data_->mutex_);
processing_limit = std::max(data_->incoming_messages_.size(),
static_cast<size_t>(1000));
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')
);
}

0 comments on commit f100bf8

Please sign in to comment.