Skip to content

Commit 281c342

Browse files
authored
node-api: make napi_get_buffer_info check if passed buffer is valid
PR-URL: #51571 Reviewed-By: Michael Dawson <midawson@redhat.com> Reviewed-By: Vladimir Morozov <vmorozov@microsoft.com> Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
1 parent f04abdb commit 281c342

File tree

3 files changed

+22
-0
lines changed

3 files changed

+22
-0
lines changed

src/node_api.cc

+2
Original file line numberDiff line numberDiff line change
@@ -1118,6 +1118,8 @@ napi_status NAPI_CDECL napi_get_buffer_info(napi_env env,
11181118
CHECK_ARG(env, value);
11191119

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

11221124
if (data != nullptr) {
11231125
*data = node::Buffer::Data(buffer);

test/node-api/test_buffer/test.js

+3
Original file line numberDiff line numberDiff line change
@@ -25,4 +25,7 @@ const tick = require('util').promisify(require('../../common/tick'));
2525
await tick(10);
2626
console.log('gc2');
2727
assert.strictEqual(binding.getDeleterCallCount(), 2);
28+
29+
// To test this doesn't crash
30+
binding.invalidObjectAsBuffer({});
2831
})().then(common.mustCall());

test/node-api/test_buffer/test_buffer.c

+17
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,22 @@ static napi_value staticBuffer(napi_env env, napi_callback_info info) {
107107
return theBuffer;
108108
}
109109

110+
static napi_value invalidObjectAsBuffer(napi_env env, napi_callback_info info) {
111+
size_t argc = 1;
112+
napi_value args[1];
113+
NODE_API_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL));
114+
NODE_API_ASSERT(env, argc == 1, "Wrong number of arguments");
115+
116+
napi_value notTheBuffer = args[0];
117+
napi_status status = napi_get_buffer_info(env, notTheBuffer, NULL, NULL);
118+
NODE_API_ASSERT(env,
119+
status == napi_invalid_arg,
120+
"napi_get_buffer_info: should fail with napi_invalid_arg "
121+
"when passed non buffer");
122+
123+
return notTheBuffer;
124+
}
125+
110126
static napi_value Init(napi_env env, napi_value exports) {
111127
napi_value theValue;
112128

@@ -123,6 +139,7 @@ static napi_value Init(napi_env env, napi_value exports) {
123139
DECLARE_NODE_API_PROPERTY("bufferHasInstance", bufferHasInstance),
124140
DECLARE_NODE_API_PROPERTY("bufferInfo", bufferInfo),
125141
DECLARE_NODE_API_PROPERTY("staticBuffer", staticBuffer),
142+
DECLARE_NODE_API_PROPERTY("invalidObjectAsBuffer", invalidObjectAsBuffer),
126143
};
127144

128145
NODE_API_CALL(env, napi_define_properties(

0 commit comments

Comments
 (0)