Skip to content

Commit

Permalink
Use malloc/free for LRUHandle instead of new[]/delete[] (facebook#10884)
Browse files Browse the repository at this point in the history
Summary:
It's unsafe to call `malloc_usable_size` with an address not returned by a function from the `malloc` family (see facebook#10798). The patch switches from using `new[]` / `delete[]` for `LRUHandle` to `malloc` / `free`.

Pull Request resolved: facebook#10884

Test Plan: `make check`

Reviewed By: pdillinger

Differential Revision: D40738089

Pulled By: ltamasi

fbshipit-source-id: ac5583f88125fee49c314639be6b6df85937fbee
  • Loading branch information
ltamasi authored and facebook-github-bot committed Oct 27, 2022
1 parent 5671535 commit 22ff8c5
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 6 deletions.
9 changes: 4 additions & 5 deletions cache/lru_cache.cc
Original file line number Diff line number Diff line change
Expand Up @@ -386,7 +386,7 @@ Status LRUCacheShard::InsertItem(LRUHandle* e, LRUHandle** handle,
last_reference_list.push_back(e);
} else {
if (free_handle_on_fail) {
delete[] reinterpret_cast<char*>(e);
free(e);
*handle = nullptr;
}
s = Status::MemoryLimit("Insert failed due to LRU cache being full.");
Expand Down Expand Up @@ -559,8 +559,7 @@ LRUHandle* LRUCacheShard::Lookup(const Slice& key, uint32_t hash,
secondary_cache_->Lookup(key, create_cb, wait, found_dummy_entry,
is_in_sec_cache);
if (secondary_handle != nullptr) {
e = reinterpret_cast<LRUHandle*>(
new char[sizeof(LRUHandle) - 1 + key.size()]);
e = static_cast<LRUHandle*>(malloc(sizeof(LRUHandle) - 1 + key.size()));

e->m_flags = 0;
e->im_flags = 0;
Expand Down Expand Up @@ -683,8 +682,8 @@ Status LRUCacheShard::Insert(const Slice& key, uint32_t hash, void* value,
// Allocate the memory here outside of the mutex.
// If the cache is full, we'll have to release it.
// It shouldn't happen very often though.
LRUHandle* e = reinterpret_cast<LRUHandle*>(
new char[sizeof(LRUHandle) - 1 + key.size()]);
LRUHandle* e =
static_cast<LRUHandle*>(malloc(sizeof(LRUHandle) - 1 + key.size()));

e->value = value;
e->m_flags = 0;
Expand Down
4 changes: 3 additions & 1 deletion cache/lru_cache.h
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,7 @@ struct LRUHandle {

void Free() {
assert(refs == 0);

if (!IsSecondaryCacheCompatible() && info_.deleter) {
(*info_.deleter)(key(), value);
} else if (IsSecondaryCacheCompatible()) {
Expand All @@ -226,7 +227,8 @@ struct LRUHandle {
(*info_.helper->del_cb)(key(), value);
}
}
delete[] reinterpret_cast<char*>(this);

free(this);
}

inline size_t CalcuMetaCharge(
Expand Down

0 comments on commit 22ff8c5

Please sign in to comment.