Skip to content

Commit 9ae1d18

Browse files
committed
crypto: free excessive memory in NodeBIO
Before this commit NodeBIO never shrank, possibly consuming a lot of memory (depending on reader's haste). All buffers between write_head's child and read_head should be deallocated on read, leaving only space left in write_head and in the next buffer.
1 parent 4bb4f73 commit 9ae1d18

2 files changed

Lines changed: 28 additions & 0 deletions

File tree

src/node_crypto_bio.cc

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,10 +210,34 @@ size_t NodeBIO::Read(char* out, size_t size) {
210210
assert(expected == bytes_read);
211211
length_ -= bytes_read;
212212

213+
// Free all empty buffers, but write_head's child
214+
FreeEmpty();
215+
213216
return bytes_read;
214217
}
215218

216219

220+
void NodeBIO::FreeEmpty() {
221+
Buffer* child = write_head_->next_;
222+
if (child == write_head_ || child == read_head_)
223+
return;
224+
Buffer* cur = child->next_;
225+
if (cur == write_head_ || cur == read_head_)
226+
return;
227+
228+
while (cur != read_head_) {
229+
assert(cur != write_head_);
230+
assert(cur->write_pos_ == cur->read_pos_);
231+
232+
Buffer* next = cur->next_;
233+
child->next_ = next;
234+
delete cur;
235+
236+
cur = next;
237+
}
238+
}
239+
240+
217241
size_t NodeBIO::IndexOf(char delim, size_t limit) {
218242
size_t bytes_read = 0;
219243
size_t max = Length() > limit ? limit : Length();

src/node_crypto_bio.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,10 @@ class NodeBIO {
6262
// Read `len` bytes maximum into `out`, return actual number of read bytes
6363
size_t Read(char* out, size_t size);
6464

65+
// Memory optimization:
66+
// Deallocate children of write head's child if they're empty
67+
void FreeEmpty();
68+
6569
// Find first appearance of `delim` in buffer or `limit` if `delim`
6670
// wasn't found.
6771
size_t IndexOf(char delim, size_t limit);

0 commit comments

Comments
 (0)