Skip to content
This repository has been archived by the owner on Mar 4, 2020. It is now read-only.

Commit

Permalink
Allocate memory of Buffer with V8's allocator
Browse files Browse the repository at this point in the history
(cherry picked from commit 813a45f)
(cherry picked from commit cbbe8e8)
  • Loading branch information
zcbenz authored and alexeykuzmin committed May 29, 2018
1 parent 201f3b6 commit f61bae3
Show file tree
Hide file tree
Showing 6 changed files with 101 additions and 52 deletions.
25 changes: 14 additions & 11 deletions src/node_buffer.cc
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,10 @@ bool zero_fill_all_buffers = false;

namespace {

inline void* BufferMalloc(size_t length) {
return zero_fill_all_buffers ? node::UncheckedCalloc(length) :
node::UncheckedMalloc(length);
inline void* BufferMalloc(v8::Isolate* isolate, size_t length) {
auto* allocator = isolate->GetArrayBufferAllocator();
return zero_fill_all_buffers ? allocator->Allocate(length) :
allocator->AllocateUninitialized(length);
}

} // namespace
Expand Down Expand Up @@ -241,7 +242,7 @@ MaybeLocal<Object> New(Isolate* isolate,
char* data = nullptr;

if (length > 0) {
data = static_cast<char*>(BufferMalloc(length));
data = static_cast<char*>(BufferMalloc(isolate, length));

if (data == nullptr)
return Local<Object>();
Expand All @@ -250,10 +251,11 @@ MaybeLocal<Object> New(Isolate* isolate,
CHECK(actual <= length);

if (actual == 0) {
free(data);
isolate->GetArrayBufferAllocator()->Free(data, length);
data = nullptr;
} else if (actual < length) {
data = node::Realloc(data, actual);
// We should call realloc here, but v8::ArrayBufferAllocator does not
// provide such ability.
}
}

Expand All @@ -262,7 +264,7 @@ MaybeLocal<Object> New(Isolate* isolate,
return scope.Escape(buf);

// Object failed to be created. Clean up resources.
free(data);
isolate->GetArrayBufferAllocator()->Free(data, length);
return Local<Object>();
}

Expand All @@ -286,7 +288,7 @@ MaybeLocal<Object> New(Environment* env, size_t length) {

void* data;
if (length > 0) {
data = BufferMalloc(length);
data = BufferMalloc(env->isolate(), length);
if (data == nullptr)
return Local<Object>();
} else {
Expand All @@ -302,7 +304,7 @@ MaybeLocal<Object> New(Environment* env, size_t length) {

if (ui.IsEmpty()) {
// Object failed to be created. Clean up resources.
free(data);
env->isolate()->GetArrayBufferAllocator()->Free(data, length);
}

return scope.Escape(ui.FromMaybe(Local<Uint8Array>()));
Expand All @@ -327,10 +329,11 @@ MaybeLocal<Object> Copy(Environment* env, const char* data, size_t length) {
return Local<Object>();
}

auto* allocator = env->isolate()->GetArrayBufferAllocator();
void* new_data;
if (length > 0) {
CHECK_NE(data, nullptr);
new_data = node::UncheckedMalloc(length);
new_data = allocator->AllocateUninitialized(length);
if (new_data == nullptr)
return Local<Object>();
memcpy(new_data, data, length);
Expand All @@ -347,7 +350,7 @@ MaybeLocal<Object> Copy(Environment* env, const char* data, size_t length) {

if (ui.IsEmpty()) {
// Object failed to be created. Clean up resources.
free(new_data);
allocator->Free(new_data, length);
}

return scope.Escape(ui.FromMaybe(Local<Uint8Array>()));
Expand Down
73 changes: 47 additions & 26 deletions src/node_crypto.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1890,7 +1890,8 @@ void SSLWrap<Base>::GetSession(const FunctionCallbackInfo<Value>& args) {
int slen = i2d_SSL_SESSION(sess, nullptr);
CHECK_GT(slen, 0);

char* sbuf = Malloc(slen);
auto* allocator = env->isolate()->GetArrayBufferAllocator();
char* sbuf = static_cast<char*>(allocator->AllocateUninitialized(slen));
unsigned char* p = reinterpret_cast<unsigned char*>(sbuf);
i2d_SSL_SESSION(sess, &p);
args.GetReturnValue().Set(Buffer::New(env, sbuf, slen).ToLocalChecked());
Expand Down Expand Up @@ -3011,7 +3012,8 @@ CipherBase::UpdateResult CipherBase::Update(const char* data,
return kErrorState;
}

*out = Malloc<unsigned char>(buff_len);
auto* allocator = env()->isolate()->GetArrayBufferAllocator();
*out = static_cast<unsigned char*>(allocator->AllocateUninitialized(buff_len));
int r = EVP_CipherUpdate(ctx_.get(),
*out,
out_len,
Expand Down Expand Up @@ -3053,7 +3055,8 @@ void CipherBase::Update(const FunctionCallbackInfo<Value>& args) {
}

if (r != kSuccess) {
free(out);
auto* allocator = env->isolate()->GetArrayBufferAllocator();
allocator->Free(out, out_len);
if (r == kErrorState) {
ThrowCryptoError(env, ERR_get_error(),
"Trying to add data in unsupported state");
Expand Down Expand Up @@ -3091,8 +3094,9 @@ bool CipherBase::Final(unsigned char** out, int* out_len) {

const int mode = EVP_CIPHER_CTX_mode(ctx_.get());

*out = Malloc<unsigned char>(
static_cast<size_t>(EVP_CIPHER_CTX_block_size(ctx_.get())));
auto* allocator = env()->isolate()->GetArrayBufferAllocator();
*out = static_cast<unsigned char*>(allocator->AllocateUninitialized(
EVP_CIPHER_CTX_block_size(ctx_.get())));

// In CCM mode, final() only checks whether authentication failed in update().
// EVP_CipherFinal_ex must not be called and will fail.
Expand Down Expand Up @@ -3135,7 +3139,8 @@ void CipherBase::Final(const FunctionCallbackInfo<Value>& args) {
bool r = cipher->Final(&out_value, &out_len);

if (out_len <= 0 || !r) {
free(out_value);
auto* allocator = env->isolate()->GetArrayBufferAllocator();
allocator->Free(out_value, out_len);
out_value = nullptr;
out_len = 0;
if (!r) {
Expand Down Expand Up @@ -3781,7 +3786,8 @@ void Verify::VerifyFinal(const FunctionCallbackInfo<Value>& args) {
template <PublicKeyCipher::Operation operation,
PublicKeyCipher::EVP_PKEY_cipher_init_t EVP_PKEY_cipher_init,
PublicKeyCipher::EVP_PKEY_cipher_t EVP_PKEY_cipher>
bool PublicKeyCipher::Cipher(const char* key_pem,
bool PublicKeyCipher::Cipher(Environment* env,
const char* key_pem,
int key_pem_len,
const char* passphrase,
int padding,
Expand All @@ -3790,6 +3796,7 @@ bool PublicKeyCipher::Cipher(const char* key_pem,
unsigned char** out,
size_t* out_len) {
EVPKeyPointer pkey;
auto* allocator = env->isolate()->GetArrayBufferAllocator();

BIOPointer bp(BIO_new_mem_buf(const_cast<char*>(key_pem), key_pem_len));
if (!bp)
Expand Down Expand Up @@ -3837,7 +3844,7 @@ bool PublicKeyCipher::Cipher(const char* key_pem,
if (EVP_PKEY_cipher(ctx.get(), nullptr, out_len, data, len) <= 0)
return false;

*out = Malloc<unsigned char>(*out_len);
*out = static_cast<unsigned char*>(allocator->AllocateUninitialized(*out_len));

if (EVP_PKEY_cipher(ctx.get(), *out, out_len, data, len) <= 0)
return false;
Expand Down Expand Up @@ -3870,6 +3877,7 @@ void PublicKeyCipher::Cipher(const FunctionCallbackInfo<Value>& args) {
ClearErrorOnReturn clear_error_on_return;

bool r = Cipher<operation, EVP_PKEY_cipher_init, EVP_PKEY_cipher>(
env,
kbuf,
klen,
args.Length() >= 3 && !args[2]->IsNull() ? *passphrase : nullptr,
Expand All @@ -3880,7 +3888,8 @@ void PublicKeyCipher::Cipher(const FunctionCallbackInfo<Value>& args) {
&out_len);

if (out_len == 0 || !r) {
free(out_value);
auto* allocator = env->isolate()->GetArrayBufferAllocator();
allocator->Free(out_value, out_len);
out_value = nullptr;
out_len = 0;
if (!r) {
Expand Down Expand Up @@ -4085,7 +4094,8 @@ void DiffieHellman::GenerateKeys(const FunctionCallbackInfo<Value>& args) {
const BIGNUM* pub_key;
DH_get0_key(diffieHellman->dh_.get(), &pub_key, nullptr);
size_t size = BN_num_bytes(pub_key);
char* data = Malloc(size);
auto* allocator = env->isolate()->GetArrayBufferAllocator();
char* data = static_cast<char*>(allocator->AllocateUninitialized(size));
BN_bn2bin(pub_key, reinterpret_cast<unsigned char*>(data));
args.GetReturnValue().Set(Buffer::New(env, data, size).ToLocalChecked());
}
Expand All @@ -4104,7 +4114,8 @@ void DiffieHellman::GetField(const FunctionCallbackInfo<Value>& args,
if (num == nullptr) return env->ThrowError(err_if_null);

size_t size = BN_num_bytes(num);
char* data = Malloc(size);
auto* allocator = env->isolate()->GetArrayBufferAllocator();
char* data = static_cast<char*>(allocator->AllocateUninitialized(size));
BN_bn2bin(num, reinterpret_cast<unsigned char*>(data));
args.GetReturnValue().Set(Buffer::New(env, data, size).ToLocalChecked());
}
Expand Down Expand Up @@ -4168,7 +4179,8 @@ void DiffieHellman::ComputeSecret(const FunctionCallbackInfo<Value>& args) {
Buffer::Length(args[0]),
0));

MallocedBuffer<char> data(DH_size(diffieHellman->dh_.get()));
auto* allocator = env->isolate()->GetArrayBufferAllocator();
MallocedBuffer<char> data(DH_size(diffieHellman->dh_.get()), allocator);

int size = DH_compute_key(reinterpret_cast<unsigned char*>(data.data),
key.get(),
Expand Down Expand Up @@ -4388,13 +4400,14 @@ void ECDH::ComputeSecret(const FunctionCallbackInfo<Value>& args) {
}

// NOTE: field_size is in bits
auto* allocator = env->isolate()->GetArrayBufferAllocator();
int field_size = EC_GROUP_get_degree(ecdh->group_);
size_t out_len = (field_size + 7) / 8;
char* out = node::Malloc(out_len);
char* out = static_cast<char*>(allocator->AllocateUninitialized(out_len));

int r = ECDH_compute_key(out, out_len, pub.get(), ecdh->key_.get(), nullptr);
if (!r) {
free(out);
allocator->Free(out, out_len);
return env->ThrowError("Failed to compute ECDH key");
}

Expand Down Expand Up @@ -4424,11 +4437,13 @@ void ECDH::GetPublicKey(const FunctionCallbackInfo<Value>& args) {
if (size == 0)
return env->ThrowError("Failed to get public key length");

unsigned char* out = node::Malloc<unsigned char>(size);
auto* allocator = env->isolate()->GetArrayBufferAllocator();
unsigned char* out =
static_cast<unsigned char*>(allocator->AllocateUninitialized(size));

int r = EC_POINT_point2oct(ecdh->group_, pub, form, out, size, nullptr);
if (r != size) {
free(out);
allocator->Free(out, size);
return env->ThrowError("Failed to get public key");
}

Expand All @@ -4448,11 +4463,13 @@ void ECDH::GetPrivateKey(const FunctionCallbackInfo<Value>& args) {
if (b == nullptr)
return env->ThrowError("Failed to get ECDH private key");

auto* allocator = env->isolate()->GetArrayBufferAllocator();
int size = BN_num_bytes(b);
unsigned char* out = node::Malloc<unsigned char>(size);
unsigned char* out =
static_cast<unsigned char*>(allocator->AllocateUninitialized(size));

if (size != BN_bn2bin(b, out)) {
free(out);
allocator->Free(out, size);
return env->ThrowError("Failed to convert ECDH private key to Buffer");
}

Expand Down Expand Up @@ -4572,7 +4589,7 @@ class PBKDF2Request : public AsyncWrap, public ThreadPoolWork {
success_(false),
pass_(std::move(pass)),
salt_(std::move(salt)),
key_(keylen),
key_(keylen, env->isolate()->GetArrayBufferAllocator()),
iteration_count_(iteration_count) {
}

Expand Down Expand Up @@ -4634,6 +4651,7 @@ void PBKDF2Request::AfterThreadPoolWork(int status) {

void PBKDF2(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
auto* allocator = env->isolate()->GetArrayBufferAllocator();

const EVP_MD* digest = nullptr;
int keylen = -1;
Expand All @@ -4642,12 +4660,12 @@ void PBKDF2(const FunctionCallbackInfo<Value>& args) {

int passlen = Buffer::Length(args[0]);

MallocedBuffer<char> pass(passlen);
MallocedBuffer<char> pass(passlen, allocator);
memcpy(pass.data, Buffer::Data(args[0]), passlen);

int saltlen = Buffer::Length(args[1]);

MallocedBuffer<char> salt(saltlen);
MallocedBuffer<char> salt(saltlen, allocator);
memcpy(salt.data, Buffer::Data(args[1]), saltlen);

iteration_count = args[2]->Int32Value(env->context()).FromJust();
Expand Down Expand Up @@ -4724,9 +4742,10 @@ class RandomBytesRequest : public AsyncWrap, public ThreadPoolWork {
}

inline void release() {
size_t free_size = size_;
size_ = 0;
if (free_mode_ == FREE_DATA) {
free(data_);
env()->isolate()->GetArrayBufferAllocator()->Free(data_, free_size);
data_ = nullptr;
}
}
Expand Down Expand Up @@ -4840,7 +4859,8 @@ void RandomBytes(const FunctionCallbackInfo<Value>& args) {

Local<Object> obj = env->randombytes_constructor_template()->
NewInstance(env->context()).ToLocalChecked();
char* data = node::Malloc(size);
char* data = static_cast<char*>(
env->isolate()->GetArrayBufferAllocator()->AllocateUninitialized(size));
std::unique_ptr<RandomBytesRequest> req(
new RandomBytesRequest(env,
obj,
Expand Down Expand Up @@ -5015,8 +5035,9 @@ void VerifySpkac(const FunctionCallbackInfo<Value>& args) {
}


char* ExportPublicKey(const char* data, int len, size_t* size) {
char* ExportPublicKey(Environment* env, const char* data, int len, size_t* size) {
char* buf = nullptr;
auto* allocator = env->isolate()->GetArrayBufferAllocator();

BIOPointer bio(BIO_new(BIO_s_mem()));
if (!bio)
Expand All @@ -5037,7 +5058,7 @@ char* ExportPublicKey(const char* data, int len, size_t* size) {
BIO_get_mem_ptr(bio.get(), &ptr);

*size = ptr->length;
buf = Malloc(*size);
buf = static_cast<char*>(allocator->AllocateUninitialized(*size));
memcpy(buf, ptr->data, *size);

return buf;
Expand All @@ -5055,7 +5076,7 @@ void ExportPublicKey(const FunctionCallbackInfo<Value>& args) {
CHECK_NE(data, nullptr);

size_t pkey_size;
char* pkey = ExportPublicKey(data, length, &pkey_size);
char* pkey = ExportPublicKey(env, data, length, &pkey_size);
if (pkey == nullptr)
return args.GetReturnValue().SetEmptyString();

Expand Down
3 changes: 2 additions & 1 deletion src/node_crypto.h
Original file line number Diff line number Diff line change
Expand Up @@ -554,7 +554,8 @@ class PublicKeyCipher {
template <Operation operation,
EVP_PKEY_cipher_init_t EVP_PKEY_cipher_init,
EVP_PKEY_cipher_t EVP_PKEY_cipher>
static bool Cipher(const char* key_pem,
static bool Cipher(Environment* env,
const char* key_pem,
int key_pem_len,
const char* passphrase,
int padding,
Expand Down
11 changes: 9 additions & 2 deletions src/stream_base.cc
Original file line number Diff line number Diff line change
Expand Up @@ -355,19 +355,26 @@ void StreamResource::ClearError() {


uv_buf_t StreamListener::OnStreamAlloc(size_t suggested_size) {
return uv_buf_init(Malloc(suggested_size), suggested_size);
CHECK_NE(stream_, nullptr);
StreamBase* stream = static_cast<StreamBase*>(stream_);
Environment* env = stream->stream_env();
auto* allocator = env->isolate()->GetArrayBufferAllocator();
return uv_buf_init(
static_cast<char*>(allocator->AllocateUninitialized(suggested_size)),
suggested_size);
}


void EmitToJSStreamListener::OnStreamRead(ssize_t nread, const uv_buf_t& buf) {
CHECK_NE(stream_, nullptr);
StreamBase* stream = static_cast<StreamBase*>(stream_);
Environment* env = stream->stream_env();
auto* allocator = env->isolate()->GetArrayBufferAllocator();
HandleScope handle_scope(env->isolate());
Context::Scope context_scope(env->context());

if (nread <= 0) {
free(buf.base);
allocator->Free(buf.base, buf.len);
if (nread < 0)
stream->CallJSOnreadMethod(nread, Local<Object>());
return;
Expand Down
Loading

0 comments on commit f61bae3

Please sign in to comment.