src: add Malloc() size param + overflow detection

Adds an optional second parameter to `node::Malloc()` and
an optional third parameter to `node::Realloc()` giving the
size/number of items to be allocated, in the style of `calloc(3)`.

Use a proper overflow check using division;
the previous `CHECK_GE(n * size, n);` would not detect all cases
of overflow (e.g. `size == SIZE_MAX / 2 && n == 3`).

Backport-PR-URL: https://github.com/nodejs/node/pull/16587
PR-URL: https://github.com/nodejs/node/pull/8482
Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Michael Dawson <michael_dawson@ca.ibm.com>
Reviewed-By: Ilkka Myller <ilkka.myller@nodefield.com>
This commit is contained in:
Anna Henningsen authored and Myles Borins committed 2017-11-14 13:57:19 -05:00
1 parent 92b13e455f
commit 19f3ac9749
4 files changed
+25 -17

No files matched your search

+1 -1
View File
@@ -54,7 +54,7 @@ class ExternString: public ResourceType {
return scope.Escape(String::Empty(isolate));
TypeName* new_data =
static_cast<TypeName*>(node::Malloc(length * sizeof(*new_data)));
static_cast<TypeName*>(node::Malloc(length, sizeof(*new_data)));
if (new_data == nullptr) {
return Local<String>();
}