diff --git a/src/node_api.cc b/src/node_api.cc index 80b1610a3cc679..5b5f6a55a0fc93 100644 --- a/src/node_api.cc +++ b/src/node_api.cc @@ -1118,6 +1118,8 @@ napi_status NAPI_CDECL napi_get_buffer_info(napi_env env, CHECK_ARG(env, value); v8::Local buffer = v8impl::V8LocalValueFromJsValue(value); + RETURN_STATUS_IF_FALSE( + env, node::Buffer::HasInstance(buffer), napi_invalid_arg); if (data != nullptr) { *data = node::Buffer::Data(buffer); diff --git a/test/node-api/test_buffer/test.js b/test/node-api/test_buffer/test.js index ac9cdff408a4a8..bf16860f6d42f8 100644 --- a/test/node-api/test_buffer/test.js +++ b/test/node-api/test_buffer/test.js @@ -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()); diff --git a/test/node-api/test_buffer/test_buffer.c b/test/node-api/test_buffer/test_buffer.c index 013a7e2d417fbe..8d112fb11fd015 100644 --- a/test/node-api/test_buffer/test_buffer.c +++ b/test/node-api/test_buffer/test_buffer.c @@ -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; @@ -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(