Skip to content

Commit

Permalink
src: Malloc/Calloc size 0 returns non-null pointer
Browse files Browse the repository at this point in the history
Change `Malloc()/Calloc()` so that size zero does not return a null
pointer, consistent with prior behavior.

Fixes: #8571
PR-URL: #8572
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: James M Snell <jasnell@keybase.io>
Reviewed-By: Yorkie Liu <yorkiefixer@gmail.com>
Reviewed-By: Michael Dawson <michael_dawson@ca.ibm.com>
  • Loading branch information
Trott authored and Myles Borins committed Sep 26, 2016
1 parent f8ad0dc commit 5902ba3
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/node_crypto.cc
Original file line number Diff line number Diff line change
Expand Up @@ -5368,7 +5368,7 @@ class RandomBytesRequest : public AsyncWrap {
error_(0),
size_(size),
data_(static_cast<char*>(node::Malloc(size))) {
if (data() == nullptr && size > 0)
if (data() == nullptr)
FatalError("node::RandomBytesRequest()", "Out of Memory");
Wrap(object, this);
}
Expand Down
4 changes: 3 additions & 1 deletion src/util-inl.h
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
14 changes: 14 additions & 0 deletions test/cctest/util.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
8 changes: 8 additions & 0 deletions test/parallel/test-crypto-pbkdf2.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}));
});

0 comments on commit 5902ba3

Please sign in to comment.