Skip to content

Commit

Permalink
node-api: make napi_get_buffer_info check if passed buffer is valid
Browse files Browse the repository at this point in the history
PR-URL: #51571
Reviewed-By: Michael Dawson <[email protected]>
Reviewed-By: Vladimir Morozov <[email protected]>
Reviewed-By: Chengzhong Wu <[email protected]>
  • Loading branch information
Janrupf authored and richardlau committed Mar 25, 2024
1 parent fbe0e36 commit f6867f5
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/node_api.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1117,6 +1117,8 @@ napi_status NAPI_CDECL napi_get_buffer_info(napi_env env,
CHECK_ARG(env, value);

v8::Local<v8::Value> buffer = v8impl::V8LocalValueFromJsValue(value);
RETURN_STATUS_IF_FALSE(
env, node::Buffer::HasInstance(buffer), napi_invalid_arg);

if (data != nullptr) {
*data = node::Buffer::Data(buffer);
Expand Down
3 changes: 3 additions & 0 deletions test/node-api/test_buffer/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,7 @@ const tick = require('util').promisify(require('../../common/tick'));
await tick(10);
console.log('gc2');
assert.strictEqual(binding.getDeleterCallCount(), 2);

// To test this doesn't crash
binding.invalidObjectAsBuffer({});
})().then(common.mustCall());
17 changes: 17 additions & 0 deletions test/node-api/test_buffer/test_buffer.c
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,22 @@ static napi_value staticBuffer(napi_env env, napi_callback_info info) {
return theBuffer;
}

static napi_value invalidObjectAsBuffer(napi_env env, napi_callback_info info) {
size_t argc = 1;
napi_value args[1];
NODE_API_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL));
NODE_API_ASSERT(env, argc == 1, "Wrong number of arguments");

napi_value notTheBuffer = args[0];
napi_status status = napi_get_buffer_info(env, notTheBuffer, NULL, NULL);
NODE_API_ASSERT(env,
status == napi_invalid_arg,
"napi_get_buffer_info: should fail with napi_invalid_arg "
"when passed non buffer");

return notTheBuffer;
}

static napi_value Init(napi_env env, napi_value exports) {
napi_value theValue;

Expand All @@ -123,6 +139,7 @@ static napi_value Init(napi_env env, napi_value exports) {
DECLARE_NODE_API_PROPERTY("bufferHasInstance", bufferHasInstance),
DECLARE_NODE_API_PROPERTY("bufferInfo", bufferInfo),
DECLARE_NODE_API_PROPERTY("staticBuffer", staticBuffer),
DECLARE_NODE_API_PROPERTY("invalidObjectAsBuffer", invalidObjectAsBuffer),
};

NODE_API_CALL(env, napi_define_properties(
Expand Down

0 comments on commit f6867f5

Please sign in to comment.