Skip to content

Commit

Permalink
worker: add typechecking for postMessage transfer list
Browse files Browse the repository at this point in the history
If the transfer list argument is present, it should be an array.
This commit adds typechecking to that effect. This aligns behaviour
with browsers.

PR-URL: #28033
Reviewed-By: Rich Trott <rtrott@gmail.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
  • Loading branch information
addaleax authored and BridgeAR committed Jun 17, 2019
1 parent d7641d8 commit 79a8cd0
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/node_messaging.cc
Original file line number Diff line number Diff line change
Expand Up @@ -714,6 +714,15 @@ void MessagePort::PostMessage(const FunctionCallbackInfo<Value>& args) {
return THROW_ERR_MISSING_ARGS(env, "Not enough arguments to "
"MessagePort.postMessage");
}
if (!args[1]->IsNullOrUndefined() && !args[1]->IsObject()) {
// Browsers ignore null or undefined, and otherwise accept an array or an
// options object.
// TODO(addaleax): Add support for an options object and generic sequence
// support.
// Refs: https://github.com/nodejs/node/pull/28033#discussion_r289964991
return THROW_ERR_INVALID_ARG_TYPE(env,
"Optional transferList argument must be an array");
}

MessagePort* port = Unwrap<MessagePort>(args.This());
// Even if the backing MessagePort object has already been deleted, we still
Expand Down
21 changes: 21 additions & 0 deletions test/parallel/test-worker-message-port.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,27 @@ const { MessageChannel, MessagePort } = require('worker_threads');
});
}

{
const { port1, port2 } = new MessageChannel();
port2.on('message', common.mustCall(4));
port1.postMessage(1, null);
port1.postMessage(2, undefined);
port1.postMessage(3, []);
port1.postMessage(4, {});

const err = {
constructor: TypeError,
code: 'ERR_INVALID_ARG_TYPE',
message: 'Optional transferList argument must be an array'
};

assert.throws(() => port1.postMessage(5, 0), err);
assert.throws(() => port1.postMessage(5, false), err);
assert.throws(() => port1.postMessage(5, 'X'), err);
assert.throws(() => port1.postMessage(5, Symbol('X')), err);
port1.close();
}

{
assert.deepStrictEqual(
Object.getOwnPropertyNames(MessagePort.prototype).sort(),
Expand Down

0 comments on commit 79a8cd0

Please sign in to comment.