Skip to content

Commit

Permalink
test: dd check for nullptr inside String init
Browse files Browse the repository at this point in the history
PR-URL: nodejs#1015
Reviewed-By: Michael Dawson <midawson@redhat.com>
Reviewed-By: Kevin Eady <kevin.c.eady@gmail.com>
  • Loading branch information
JckXia authored and Deepak Rajamohan committed Sep 23, 2021
1 parent 92d1af5 commit 4f9b270
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 0 deletions.
5 changes: 5 additions & 0 deletions napi-inl.h
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down
7 changes: 7 additions & 0 deletions test/name.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
5 changes: 5 additions & 0 deletions test/name.js
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down

0 comments on commit 4f9b270

Please sign in to comment.