From d2eb7ce0105369a9cad82787cb33a665e9bd00ad Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Fri, 16 Sep 2016 22:45:00 -0700 Subject: [PATCH] src: Malloc/Calloc size 0 returns non-null pointer Change `Malloc()/Calloc()` so that size zero does not return a null pointer, consistent with prior behavior. Fixes: https://github.com/nodejs/node/issues/8571 PR-URL: https://github.com/nodejs/node/pull/8572 Reviewed-By: Anna Henningsen Reviewed-By: James M Snell Reviewed-By: Yorkie Liu Reviewed-By: Michael Dawson --- src/node_crypto.cc | 2 +- src/util-inl.h | 4 +++- test/cctest/util.cc | 14 ++++++++++++++ test/parallel/test-crypto-pbkdf2.js | 8 ++++++++ 4 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/node_crypto.cc b/src/node_crypto.cc index 33b844f07d8857..7997d2113b4493 100644 --- a/src/node_crypto.cc +++ b/src/node_crypto.cc @@ -5368,7 +5368,7 @@ class RandomBytesRequest : public AsyncWrap { error_(0), size_(size), data_(static_cast(node::Malloc(size))) { - if (data() == nullptr && size > 0) + if (data() == nullptr) FatalError("node::RandomBytesRequest()", "Out of Memory"); Wrap(object, this); } diff --git a/src/util-inl.h b/src/util-inl.h index 5644ee90487744..31411bb47967e4 100644 --- a/src/util-inl.h +++ b/src/util-inl.h @@ -246,11 +246,13 @@ void* Realloc(void* pointer, size_t size) { // As per spec realloc behaves like malloc if passed nullptr. void* Malloc(size_t size) { + if (size == 0) size = 1; return Realloc(nullptr, size); } void* Calloc(size_t n, size_t size) { - if ((n == 0) || (size == 0)) return nullptr; + if (n == 0) n = 1; + if (size == 0) size = 1; CHECK_GE(n * size, n); // Overflow guard. return calloc(n, size); } diff --git a/test/cctest/util.cc b/test/cctest/util.cc index 862024aff33d6f..79f1524660b213 100644 --- a/test/cctest/util.cc +++ b/test/cctest/util.cc @@ -89,3 +89,17 @@ TEST(UtilTest, ToLower) { EXPECT_EQ('a', ToLower('a')); EXPECT_EQ('a', ToLower('A')); } + +TEST(UtilTest, Malloc) { + using node::Malloc; + EXPECT_NE(nullptr, Malloc(0)); + EXPECT_NE(nullptr, Malloc(1)); +} + +TEST(UtilTest, Calloc) { + using node::Calloc; + EXPECT_NE(nullptr, Calloc(0, 0)); + EXPECT_NE(nullptr, Calloc(1, 0)); + EXPECT_NE(nullptr, Calloc(0, 1)); + EXPECT_NE(nullptr, Calloc(1, 1)); +} \ No newline at end of file diff --git a/test/parallel/test-crypto-pbkdf2.js b/test/parallel/test-crypto-pbkdf2.js index c1897c2d69ebdd..f9fa7aa486318d 100644 --- a/test/parallel/test-crypto-pbkdf2.js +++ b/test/parallel/test-crypto-pbkdf2.js @@ -84,3 +84,11 @@ assert.throws(function() { assert.throws(function() { crypto.pbkdf2('password', 'salt', 1, 4073741824, 'sha256', common.fail); }, /Bad key length/); + +// Should not get FATAL ERROR with empty password and salt +// https://github.com/nodejs/node/issues/8571 +assert.doesNotThrow(() => { + crypto.pbkdf2('', '', 1, 32, 'sha256', common.mustCall((e) => { + assert.ifError(e); + })); +});