blob: a7ab77bc7cca41f2270c2156ebe4e23cb5e87313 [file]
// Copyright 2023 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <zircon/availability.h>
#if FUCHSIA_API_LEVEL_AT_LEAST(29)
#include <elf.h>
#include <fidl/fuchsia.memory.sampler/cpp/fidl.h>
#include <fidl/fuchsia.memory.sampler/cpp/natural_types.h>
#include <fidl/fuchsia.memory.sampler/cpp/wire_types.h>
#include <lib/component/incoming/cpp/service.h>
#include <lib/zx/result.h>
#include <link.h>
#include <pthread.h>
#include <zircon/process.h>
#include <zircon/sanitizer.h>
#include <zircon/syscalls.h>
#include <zircon/syscalls/object.h>
#include <zircon/time.h>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <mutex>
#include <new>
#include <span>
#include <utility>
#include <vector>
#include <fbl/auto_lock.h>
#include "allocation_table.h"
#include "poisson_sampler.h"
#include "recorder.h"
namespace {
// Note: The destructor is never called. This is on purpose.
std::atomic<memory_sampler::Recorder*> singleton;
// Threshold for truncating overly long stack frames.
// LINT.IfChange(max_datagram_size)
constexpr size_t kMaxStackFramesLength = 512;
// LINT.ThenChange(//src/memory/sampler/src/sampler_service.rs:max_datagram_size)
constexpr uint64_t kMinSamplingIntervalBytes =
memory_sampler::Recorder::kDefaultSamplingIntervalBytes;
constexpr uint64_t kMaxSamplingIntervalBytes = static_cast<uint64_t>(8 * 1024 * 1024);
bool IsChannelPeerClosed(const fidl::ClientEnd<fuchsia_memory_sampler::Sampler>& client_end) {
zx_signals_t signals = 0;
return client_end.channel().wait_one(ZX_CHANNEL_PEER_CLOSED, zx::time::infinite_past(),
&signals) == ZX_OK &&
(signals & ZX_CHANNEL_PEER_CLOSED) != 0;
}
constexpr size_t AlignNoteSize(size_t size) { return (size + 3u) & ~size_t{3u}; }
bool IsNoteInLoadableSegment(std::span<const ElfW(Phdr)> phdrs, const ElfW(Phdr) & note_phdr) {
const uintptr_t note_start = note_phdr.p_vaddr;
const uintptr_t note_end = note_start + note_phdr.p_filesz;
if (note_end < note_start) {
return false;
}
for (const auto& phdr : phdrs) {
if (phdr.p_type != PT_LOAD || (phdr.p_flags & PF_R) == 0) {
continue;
}
const uintptr_t load_start = phdr.p_vaddr;
const uintptr_t load_end = load_start + phdr.p_memsz;
if (load_end >= load_start && note_start >= load_start && note_end <= load_end) {
return true;
}
}
return false;
}
std::span<const uint8_t> ParseBuildIdFromNotes(uintptr_t vaddr, size_t size) {
const uintptr_t end = vaddr + size;
if ((vaddr & 3u) != 0 || end < vaddr) {
return {};
}
while (end - vaddr >= sizeof(ElfW(Nhdr))) {
ElfW(Nhdr) nhdr;
std::memcpy(&nhdr, reinterpret_cast<const void*>(vaddr), sizeof(nhdr));
vaddr += sizeof(ElfW(Nhdr));
const size_t aligned_name_size = AlignNoteSize(nhdr.n_namesz);
if (end - vaddr < aligned_name_size) {
break;
}
const uintptr_t name_addr = vaddr;
vaddr += aligned_name_size;
const size_t aligned_desc_size = AlignNoteSize(nhdr.n_descsz);
if (end - vaddr < aligned_desc_size) {
break;
}
const uintptr_t desc_addr = vaddr;
vaddr += aligned_desc_size;
if (nhdr.n_type == NT_GNU_BUILD_ID && nhdr.n_namesz == sizeof(ELF_NOTE_GNU) &&
nhdr.n_descsz > 0 && nhdr.n_descsz <= fuchsia_memory_sampler::kBuildIdBytes &&
std::memcmp(reinterpret_cast<const void*>(name_addr), ELF_NOTE_GNU, sizeof(ELF_NOTE_GNU)) ==
0) {
return {reinterpret_cast<const uint8_t*>(desc_addr), nhdr.n_descsz};
}
}
return {};
}
std::span<const uint8_t> ParseBuildId(const struct dl_phdr_info& info) {
const std::span<const ElfW(Phdr)> phdrs{info.dlpi_phdr, info.dlpi_phnum};
for (const auto& phdr : phdrs) {
if (phdr.p_type == PT_NOTE && IsNoteInLoadableSegment(phdrs, phdr)) {
std::span<const uint8_t> build_id =
ParseBuildIdFromNotes(info.dlpi_addr + phdr.p_vaddr, phdr.p_filesz);
if (!build_id.empty()) {
return build_id;
}
}
}
return {};
}
// Collects the module layout of the current process and communicates it to the profiler.
fit::result<fidl::OneWayError> SetModulesInfo(
const fidl::SyncClient<fuchsia_memory_sampler::Sampler>& client) {
std::vector<fuchsia_memory_sampler::ModuleMap> modules;
// Iterate through loaded ELF modules via the dynamic linker's in-memory table
// to map executable segments to their corresponding GNU build ID.
dl_iterate_phdr(
[](struct dl_phdr_info* info, size_t /*size*/, void* data) -> int {
const std::span<const uint8_t> build_id = ParseBuildId(*info);
if (build_id.empty()) {
return 0;
}
auto* modules = static_cast<std::vector<fuchsia_memory_sampler::ModuleMap>*>(data);
const size_t kPageSize = zx_system_get_page_size();
const std::span<const ElfW(Phdr)> phdrs{info->dlpi_phdr, info->dlpi_phnum};
std::vector<fuchsia_memory_sampler::ExecutableSegment> segments;
for (const auto& phdr : phdrs) {
// Skip non-loadable or non-executable sections.
if (phdr.p_type != PT_LOAD || (phdr.p_flags & PF_X) == 0) {
continue;
}
const uintptr_t start = phdr.p_vaddr & -kPageSize;
const uintptr_t end = (phdr.p_vaddr + phdr.p_memsz + kPageSize - 1) & -kPageSize;
auto& segment = segments.emplace_back();
segment.start_address(info->dlpi_addr + start);
segment.size(end - start);
segment.relative_address(start);
}
auto& module_map = modules->emplace_back();
module_map.build_id({{build_id.begin(), build_id.end()}});
module_map.executable_segments(std::move(segments));
return 0;
},
&modules);
// Retrieve the name of the current process.
const zx_handle_t process = zx_process_self();
char name[ZX_MAX_NAME_LEN]{};
zx_object_get_property(process, ZX_PROP_NAME, name, ZX_MAX_NAME_LEN);
return client->SetProcessInfo({{.process_name = name, .module_map = std::move(modules)}});
}
// Note: this implementation currently relies on `thread_local` to
// track the allocated bytes and thresholds, which means that each
// thread implements a different Poisson process.
memory_sampler::PoissonSampler& GetPoissonSampler() {
thread_local memory_sampler::PoissonSampler sampler{
[]
// Return a sampling interval fit for the current level of congestion.
{
auto* recorder = memory_sampler::Recorder::GetIfReady();
if (recorder == nullptr) {
return memory_sampler::Recorder::kDefaultSamplingIntervalBytes;
}
recorder->ApplyBackpressure();
return recorder->GetSamplingIntervalBytes();
}};
return sampler;
}
} // namespace
namespace memory_sampler {
Recorder* Recorder::InitInPlace(
void* storage, zx::result<fidl::ClientEnd<fuchsia_memory_sampler::Sampler>> client_end) {
if (client_end.is_error() || IsChannelPeerClosed(client_end.value())) {
return nullptr;
}
fidl::SyncClient client{std::move(client_end.value())};
zx::socket client_socket;
#if FUCHSIA_API_LEVEL_AT_LEAST(NEXT)
zx::socket server_socket;
if (zx::socket::create(ZX_SOCKET_DATAGRAM, &client_socket, &server_socket) != ZX_OK) {
return nullptr;
}
if (client->SetSharedSocket({{.socket = std::move(server_socket)}}).is_error()) {
return nullptr;
}
#endif
if (SetModulesInfo(client).is_error()) {
return nullptr;
}
return new (storage) Recorder(std::move(client), std::move(client_socket));
}
// Upon connecting, transmits the memory layout of the current process.
void Recorder::InitSingletonOnce() {
alignas(Recorder) static std::byte storage[sizeof(Recorder)];
Recorder* recorder = InitInPlace(storage, component::Connect<fuchsia_memory_sampler::Sampler>());
if (recorder != nullptr) {
// Only set the singleton once all allocations are done, to avoid a deadlock.
singleton.store(recorder, std::memory_order_release);
}
}
Recorder* Recorder::Get() {
static std::once_flag once_flag;
std::call_once(once_flag, InitSingletonOnce);
return singleton.load(std::memory_order_acquire);
}
Recorder* Recorder::GetIfReady() { return singleton.load(std::memory_order_acquire); }
void Recorder::Disconnect() {
if (bool expected = false;
!is_disabled_.compare_exchange_strong(expected, true, std::memory_order_acq_rel)) {
return;
}
if (this == singleton.load(std::memory_order_relaxed)) {
singleton.store(nullptr, std::memory_order_release);
}
{
fbl::AutoLock lock(&lock_);
client_ = {};
}
recorded_allocations_.Clear();
}
// Profiling every single allocation has a large impact on the
// performance of the instrumented process. Sampling allocation
// profilers work around this issue by sampling a subset of the
// allocations, reducing the overhead while hopefully capturing enough
// relevant data to be useful.
void Recorder::MaybeRecordAllocation(void* address, size_t size) {
if (address == nullptr || is_disabled_.load(std::memory_order_relaxed)) {
return;
}
std::optional<uint64_t> sampling_interval = GetPoissonSampler().ShouldSampleAllocation(size);
if (!sampling_interval.has_value()) {
return;
}
if (!RecordAllocation(address, size, *sampling_interval)) {
return;
}
// Store the address of the allocation if still active. Re-check
// `is_disabled_` after inserting so that an allocation racing with
// `Disconnect()` cannot remain in `recorded_allocations_` after `Clear()`.
if (!is_disabled_.load(std::memory_order_relaxed)) {
recorded_allocations_.Insert(address);
if (is_disabled_.load(std::memory_order_acquire)) [[unlikely]] {
recorded_allocations_.TryRemove(address);
}
}
}
// `RecordAllocation` and `ForgetAllocation` are marked `noinline` so LTO does
// not inline their large stack buffers (backtrace buffer, FIDL arena) into the
// Scudo hooks, which would otherwise force stack-clash probes, stack-protector
// canaries, and extra register spills onto every allocation and deallocation.
[[gnu::noinline]] bool Recorder::RecordAllocation(void* address, size_t size,
uint64_t sampling_interval) {
if (is_disabled_.load(std::memory_order_relaxed)) {
return false;
}
uint64_t pc_buffer[kMaxStackFramesLength]{};
const size_t count = __sanitizer_fast_backtrace(pc_buffer, kMaxStackFramesLength);
#if FUCHSIA_API_LEVEL_AT_LEAST(NEXT)
fuchsia_memory_sampler::RecordAllocationEvent event{{
.address = std::optional{reinterpret_cast<uint64_t>(address)},
.stack_trace = std::optional<fuchsia_memory_sampler::StackTrace>{{{
.stack_frames = std::optional{std::vector<uint64_t>(pc_buffer, pc_buffer + count)},
}}},
.size = std::optional<uint64_t>{size},
.sampling_interval_bytes = std::optional<uint64_t>{sampling_interval},
}};
if (socket_.is_valid()) {
auto datagram = fuchsia_memory_sampler::SamplerDatagram::WithRecordAllocation(std::move(event));
fit::result encoded = fidl::Persist(datagram);
if (encoded.is_ok()) {
zx_status_t status = socket_.write(0, encoded->data(), encoded->size(), nullptr);
if (status == ZX_OK) {
return true;
}
if (status == ZX_ERR_PEER_CLOSED) {
Disconnect();
} else if (status == ZX_ERR_SHOULD_WAIT) {
if (!peer_signaled_.exchange(true, std::memory_order_relaxed)) {
if (socket_.signal_peer(0, ZX_USER_SIGNAL_0) == ZX_ERR_PEER_CLOSED) {
Disconnect();
}
}
}
}
return false;
}
// Fallback FIDL path
bool is_peer_closed = false;
bool is_ok = false;
{
fbl::AutoLock lock(&lock_);
if (!client_.is_valid()) {
return false;
}
zx_signals_t signals = 0;
if (client_.client_end().channel().wait_one(ZX_CHANNEL_PEER_CLOSED, zx::time::infinite_past(),
&signals) == ZX_OK &&
(signals & ZX_CHANNEL_PEER_CLOSED)) {
is_peer_closed = true;
} else {
auto result = client_->RecordAllocation(event);
if (result.is_error()) {
is_peer_closed = true;
} else {
is_ok = true;
}
}
}
if (is_peer_closed) {
Disconnect();
return false;
}
return is_ok;
#else
bool is_peer_closed = false;
bool is_ok = false;
{
fbl::AutoLock lock(&lock_);
if (!client_.is_valid()) {
return false;
}
zx_signals_t signals = 0;
if (client_.client_end().channel().wait_one(ZX_CHANNEL_PEER_CLOSED, zx::time::infinite_past(),
&signals) == ZX_OK &&
(signals & ZX_CHANNEL_PEER_CLOSED)) {
is_peer_closed = true;
} else {
auto result = client_->RecordAllocation({{
.address = std::optional{reinterpret_cast<uint64_t>(address)},
.stack_trace = std::optional<fuchsia_memory_sampler::StackTrace>(
{{.stack_frames =
std::optional{std::vector<uint64_t>(pc_buffer, pc_buffer + count)}}}),
.size = std::optional<uint64_t>{size},
}});
if (result.is_error()) {
is_peer_closed = true;
} else {
is_ok = true;
}
}
}
if (is_peer_closed) {
Disconnect();
return false;
}
return is_ok;
#endif
}
void Recorder::MaybeForgetAllocation(void* address) {
if (address == nullptr || is_disabled_.load(std::memory_order_relaxed)) {
return;
}
if (!recorded_allocations_.TryRemove(address)) {
return;
}
ForgetAllocation(address);
}
[[gnu::noinline]] void Recorder::ForgetAllocation(void* address) {
if (is_disabled_.load(std::memory_order_relaxed)) {
return;
}
uint64_t pc_buffer[kMaxStackFramesLength]{};
const size_t count = __sanitizer_fast_backtrace(pc_buffer, kMaxStackFramesLength);
#if FUCHSIA_API_LEVEL_AT_LEAST(NEXT)
fuchsia_memory_sampler::RecordDeallocationEvent event{{
.address = std::optional{reinterpret_cast<uint64_t>(address)},
.stack_trace = std::optional<fuchsia_memory_sampler::StackTrace>{{{
.stack_frames = std::optional{std::vector<uint64_t>(pc_buffer, pc_buffer + count)},
}}},
}};
if (socket_.is_valid()) {
auto datagram =
fuchsia_memory_sampler::SamplerDatagram::WithRecordDeallocation(std::move(event));
fit::result encoded = fidl::Persist(datagram);
if (encoded.is_ok()) {
zx_status_t status = socket_.write(0, encoded->data(), encoded->size(), nullptr);
if (status == ZX_ERR_PEER_CLOSED) {
Disconnect();
} else if (status == ZX_ERR_SHOULD_WAIT) {
if (!peer_signaled_.exchange(true, std::memory_order_relaxed)) {
if (socket_.signal_peer(0, ZX_USER_SIGNAL_0) == ZX_ERR_PEER_CLOSED) {
Disconnect();
}
}
}
}
return;
}
// Fallback FIDL path
bool is_peer_closed = false;
{
fbl::AutoLock lock(&lock_);
if (!client_.is_valid()) {
return;
}
zx_signals_t signals = 0;
if (client_.client_end().channel().wait_one(ZX_CHANNEL_PEER_CLOSED, zx::time::infinite_past(),
&signals) == ZX_OK &&
(signals & ZX_CHANNEL_PEER_CLOSED)) {
is_peer_closed = true;
} else {
auto result = client_->RecordDeallocation(event);
if (result.is_error()) {
is_peer_closed = true;
}
}
}
if (is_peer_closed) {
Disconnect();
}
#else
bool is_peer_closed = false;
{
fbl::AutoLock lock(&lock_);
if (!client_.is_valid()) {
return;
}
zx_signals_t signals = 0;
if (client_.client_end().channel().wait_one(ZX_CHANNEL_PEER_CLOSED, zx::time::infinite_past(),
&signals) == ZX_OK &&
(signals & ZX_CHANNEL_PEER_CLOSED)) {
is_peer_closed = true;
} else {
auto result = client_->RecordDeallocation(
{{.address = std::optional{reinterpret_cast<uint64_t>(address)},
.stack_trace = std::optional<fuchsia_memory_sampler::StackTrace>{
{{.stack_frames =
std::optional{std::vector<uint64_t>(pc_buffer, pc_buffer + count)}}}}}});
if (result.is_error()) {
is_peer_closed = true;
}
}
}
if (is_peer_closed) {
Disconnect();
}
#endif
}
void Recorder::ApplyBackpressure() {
if (!socket_.is_valid()) {
return;
}
zx_info_socket_t info;
if (socket_.get_info(ZX_INFO_SOCKET, &info, sizeof(info), nullptr, nullptr) != ZX_OK) {
return;
}
if (info.tx_buf_max == 0) {
return;
}
double usage = static_cast<double>(info.tx_buf_size) / static_cast<double>(info.tx_buf_max);
uint64_t new_interval;
if (usage < 0.125) {
new_interval = kMinSamplingIntervalBytes;
} else if (usage < 0.25) {
new_interval = kMinSamplingIntervalBytes * 2;
} else if (usage < 0.375) {
new_interval = kMinSamplingIntervalBytes * 4;
} else if (usage < 0.50) {
new_interval = kMinSamplingIntervalBytes * 8;
} else if (usage < 0.625) {
new_interval = kMinSamplingIntervalBytes * 16;
} else if (usage < 0.75) {
new_interval = kMinSamplingIntervalBytes * 32;
} else {
static_assert(kMaxSamplingIntervalBytes > kMinSamplingIntervalBytes * 32);
new_interval = kMaxSamplingIntervalBytes;
}
uint64_t current_interval = current_sampling_interval_bytes_.load(std::memory_order_relaxed);
if (new_interval != current_interval) {
current_sampling_interval_bytes_.store(new_interval, std::memory_order_relaxed);
}
}
Recorder::Recorder(fidl::SyncClient<fuchsia_memory_sampler::Sampler> client, zx::socket socket,
bool is_disabled)
: client_(std::move(client)), socket_(std::move(socket)), is_disabled_(is_disabled) {}
void Recorder::SetPoissonSamplerForTesting(PoissonSampler sampler) {
GetPoissonSampler() = std::move(sampler);
}
Recorder Recorder::CreateRecorderForTesting(
fidl::SyncClient<fuchsia_memory_sampler::Sampler> client, PoissonSampler sampler,
[[maybe_unused]] bool use_socket) {
SetPoissonSamplerForTesting(std::move(sampler));
#if FUCHSIA_API_LEVEL_AT_LEAST(NEXT)
if (use_socket) {
zx::socket client_socket, server_socket;
if (IsChannelPeerClosed(client.client_end()) ||
zx::socket::create(ZX_SOCKET_DATAGRAM, &client_socket, &server_socket) != ZX_OK ||
client->SetSharedSocket({{.socket = std::move(server_socket)}}).is_error()) {
return Recorder{{}, {}, /*is_disabled=*/true};
}
return Recorder{std::move(client), std::move(client_socket)};
}
#endif
return Recorder{std::move(client), zx::socket{}};
}
} // namespace memory_sampler
#endif // FUCHSIA_API_LEVEL_AT_LEAST(29)