ClickHouse/libs/libcommon/src/phdr_cache.cpp

97 lines
2.4 KiB
C++
Raw Normal View History

/// This code was developed by Fedor Korotkiy (prime@yandex-team.ru) for YT product in Yandex.
#include <link.h>
#include <dlfcn.h>
2019-07-25 19:54:16 +00:00
#include <vector>
#include <atomic>
#include <cstddef>
2019-07-24 15:27:37 +00:00
#include <stdexcept>
2019-07-24 15:35:19 +00:00
2019-07-25 19:54:16 +00:00
#if defined(__has_feature)
#if __has_feature(address_sanitizer)
#define ADDRESS_SANITIZER 1
#endif
#elif defined(__SANITIZE_ADDRESS__)
#define ADDRESS_SANITIZER 1
#endif
extern "C"
{
#ifdef ADDRESS_SANITIZER
void __lsan_ignore_object(const void *);
#else
void __lsan_ignore_object(const void *) {}
#endif
}
namespace
{
// This is adapted from
// https://github.com/scylladb/seastar/blob/master/core/exception_hacks.hh
// https://github.com/scylladb/seastar/blob/master/core/exception_hacks.cc
using DLIterateFunction = int (*) (int (*callback) (dl_phdr_info * info, size_t size, void * data), void * data);
DLIterateFunction getOriginalDLIteratePHDR()
{
void * func = dlsym(RTLD_NEXT, "dl_iterate_phdr");
if (!func)
throw std::runtime_error("Cannot find dl_iterate_phdr function with dlsym");
return reinterpret_cast<DLIterateFunction>(func);
}
2019-07-24 15:35:19 +00:00
2019-07-25 19:54:16 +00:00
using PHDRCache = std::vector<dl_phdr_info>;
std::atomic<PHDRCache *> phdr_cache {};
}
extern "C"
#ifndef __clang__
[[gnu::visibility("default")]]
[[gnu::externally_visible]]
#endif
int dl_iterate_phdr(int (*callback) (dl_phdr_info * info, size_t size, void * data), void * data)
{
2019-07-25 19:54:16 +00:00
auto current_phdr_cache = phdr_cache.load(std::memory_order_relaxed);
if (!current_phdr_cache)
{
// Cache is not yet populated, pass through to the original function.
return getOriginalDLIteratePHDR()(callback, data);
}
int result = 0;
2019-07-25 19:54:16 +00:00
for (auto & entry : *current_phdr_cache)
{
2019-07-25 19:54:16 +00:00
result = callback(&entry, offsetof(dl_phdr_info, dlpi_adds), data);
if (result != 0)
break;
}
return result;
}
2019-07-25 19:54:16 +00:00
void updatePHDRCache()
{
#if defined(__linux__)
// Fill out ELF header cache for access without locking.
// This assumes no dynamic object loading/unloading after this point
2019-07-25 19:54:16 +00:00
PHDRCache * new_phdr_cache = new PHDRCache;
getOriginalDLIteratePHDR()([] (dl_phdr_info * info, size_t /*size*/, void * data)
{
2019-07-25 19:54:16 +00:00
reinterpret_cast<PHDRCache *>(data)->push_back(*info);
return 0;
2019-07-25 19:54:16 +00:00
}, new_phdr_cache);
phdr_cache.store(new_phdr_cache);
/// Memory is intentionally leaked.
__lsan_ignore_object(new_phdr_cache);
#endif
}