Skip to content

Commit

Permalink
feat(server): Use mimalloc in SSL calls
Browse files Browse the repository at this point in the history
Until now, OpenSSL used `malloc()` directly. This PR overrides it to use
mimalloc.

Fixes #2709
  • Loading branch information
chakaz committed Mar 10, 2024
1 parent 8b31195 commit 9dba7dc
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/facade/dragonfly_listener.cc
Original file line number Diff line number Diff line change
Expand Up @@ -156,11 +156,38 @@ bool ConfigureKeepAlive(int fd) {
return true;
}

size_t ssl_allocated_bytes = 0;

void* OverriddenSSLMalloc(size_t size, const char* file, int line) {
void* res = mi_malloc(size);
ssl_allocated_bytes += mi_malloc_usable_size(res);
return res;
}

void* OverriddenSSLRealloc(void* addr, size_t size, const char* file, int line) {
size_t prev_size = mi_malloc_usable_size(addr);
void* res = mi_realloc(addr, size);
ssl_allocated_bytes += mi_malloc_usable_size(res);
ssl_allocated_bytes -= prev_size;
return res;
}

void OverriddenSSLFree(void* addr, const char* file, int line) {
ssl_allocated_bytes -= mi_malloc_usable_size(addr);
mi_free(addr);
}

std::once_flag g_set_mem_functions_flag;

} // namespace

Listener::Listener(Protocol protocol, ServiceInterface* si, Role role)
: service_(si), protocol_(protocol) {
#ifdef DFLY_USE_SSL
call_once(g_set_mem_functions_flag, []() {
CRYPTO_set_mem_functions(&OverriddenSSLMalloc, &OverriddenSSLRealloc, &OverriddenSSLFree);
});

// Always initialise OpenSSL so we can enable TLS at runtime.
OPENSSL_init_ssl(OPENSSL_INIT_SSL_DEFAULT, nullptr);
if (!ReconfigureTLS()) {
Expand Down

0 comments on commit 9dba7dc

Please sign in to comment.