Skip to content

Commit

Permalink
src: use MaybeStackBuffer on DoSend/Writev
Browse files Browse the repository at this point in the history
instead of creating own buffer, use MaybeStackBuffer on DoSend to
take advantage of its destructor to free up memory, so buffer
never leaks memory - even if code in DoSend throws.

Use MaybeStackBuffer in Writev to take advantage of destructor
on MaybeStackBuffer to clear itself up, rather than Writev managing
resources itself.

PR-URL: #8626
Reviewed-By: Anna Henningsen <anna@addaleax.net>
  • Loading branch information
Paul Kiddie authored and Fishrock123 committed Oct 11, 2016
1 parent d72a7b3 commit 52f0f64
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 22 deletions.
12 changes: 2 additions & 10 deletions src/stream_base.cc
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,7 @@ int StreamBase::Writev(const FunctionCallbackInfo<Value>& args) {

size_t count = chunks->Length() >> 1;

uv_buf_t bufs_[16];
uv_buf_t* bufs = bufs_;
MaybeStackBuffer<uv_buf_t, 16> bufs(count);

// Determine storage size first
size_t storage_size = 0;
Expand Down Expand Up @@ -132,9 +131,6 @@ int StreamBase::Writev(const FunctionCallbackInfo<Value>& args) {
if (storage_size > INT_MAX)
return UV_ENOBUFS;

if (arraysize(bufs_) < count)
bufs = new uv_buf_t[count];

WriteWrap* req_wrap = WriteWrap::New(env,
req_wrap_obj,
this,
Expand Down Expand Up @@ -174,11 +170,7 @@ int StreamBase::Writev(const FunctionCallbackInfo<Value>& args) {
bytes += str_size;
}

int err = DoWrite(req_wrap, bufs, count, nullptr);

// Deallocate space
if (bufs != bufs_)
delete[] bufs;
int err = DoWrite(req_wrap, *bufs, count, nullptr);

req_wrap->object()->Set(env->async(), True(env->isolate()));
req_wrap->object()->Set(env->bytes_string(),
Expand Down
14 changes: 2 additions & 12 deletions src/udp_wrap.cc
Original file line number Diff line number Diff line change
Expand Up @@ -275,13 +275,7 @@ void UDPWrap::DoSend(const FunctionCallbackInfo<Value>& args, int family) {
SendWrap* req_wrap = new SendWrap(env, req_wrap_obj, have_callback);
size_t msg_size = 0;

// allocate uv_buf_t of the correct size
// if bigger than 16 elements
uv_buf_t bufs_[16];
uv_buf_t* bufs = bufs_;

if (arraysize(bufs_) < count)
bufs = new uv_buf_t[count];
MaybeStackBuffer<uv_buf_t, 16> bufs(count);

// construct uv_buf_t array
for (size_t i = 0; i < count; i++) {
Expand Down Expand Up @@ -313,16 +307,12 @@ void UDPWrap::DoSend(const FunctionCallbackInfo<Value>& args, int family) {
if (err == 0) {
err = uv_udp_send(&req_wrap->req_,
&wrap->handle_,
bufs,
*bufs,
count,
reinterpret_cast<const sockaddr*>(&addr),
OnSend);
}

// Deallocate space
if (bufs != bufs_)
delete[] bufs;

req_wrap->Dispatched();
if (err)
delete req_wrap;
Expand Down

0 comments on commit 52f0f64

Please sign in to comment.