From aebedd22fd7f4e1b7a8089fabb658c1076e5df8f Mon Sep 17 00:00:00 2001 From: Roy Wright Date: Sun, 27 Jun 2021 17:24:19 -0400 Subject: [PATCH] test: dd check for nullptr inside String init PR-URL: https://github.com/nodejs/node-addon-api/pull/1015 Reviewed-By: Michael Dawson Reviewed-By: Kevin Eady --- napi-inl.h | 5 +++++ test/name.cc | 7 +++++++ test/name.js | 5 +++++ 3 files changed, 17 insertions(+) diff --git a/napi-inl.h b/napi-inl.h index 1f6563f..93cef59 100644 --- a/napi-inl.h +++ b/napi-inl.h @@ -900,6 +900,11 @@ inline String String::New(napi_env env, const std::u16string& val) { } inline String String::New(napi_env env, const char* val) { + if (val == nullptr) { + NAPI_THROW( + TypeError::New(env, "String::New received a nullpointer as a value"), + Napi::String()); + } napi_value value; napi_status status = napi_create_string_utf8(env, val, std::strlen(val), &value); NAPI_THROW_IF_FAILED(env, status, String()); diff --git a/test/name.cc b/test/name.cc index 3a296ec..4e56141 100644 --- a/test/name.cc +++ b/test/name.cc @@ -82,11 +82,18 @@ Value CheckSymbol(const CallbackInfo& info) { return Boolean::New(info.Env(), info[0].Type() == napi_symbol); } +void AssertErrorThrownWhenPassedNullptr(const CallbackInfo& info) { + const char* nullStr = nullptr; + String::New(info.Env(), nullStr); +} + Object InitName(Env env) { Object exports = Object::New(env); exports["echoString"] = Function::New(env, EchoString); exports["createString"] = Function::New(env, CreateString); + exports["nullStringShouldThrow"] = + Function::New(env, AssertErrorThrownWhenPassedNullptr); exports["checkString"] = Function::New(env, CheckString); exports["createSymbol"] = Function::New(env, CreateSymbol); exports["checkSymbol"] = Function::New(env, CheckSymbol); diff --git a/test/name.js b/test/name.js index 4577746..4c74542 100644 --- a/test/name.js +++ b/test/name.js @@ -7,6 +7,11 @@ module.exports = require('./common').runTest(test); function test(binding) { const expected = '123456789'; + + assert.throws(binding.name.nullStringShouldThrow, { + name: 'TypeError', + message: 'String::New received a nullpointer as a value', + }); assert.ok(binding.name.checkString(expected, 'utf8')); assert.ok(binding.name.checkString(expected, 'utf16')); assert.ok(binding.name.checkString(expected.substr(0, 3), 'utf8', 3));