Index: include/xray/xray_log_interface.h =================================================================== --- /dev/null +++ include/xray/xray_log_interface.h @@ -0,0 +1,51 @@ +//===-- xray_log_interface.h ----------------------------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file is a part of XRay, a function call tracing system. +// +// APIs for installing a new logging implementation. +//===----------------------------------------------------------------------===// +#ifndef XRAY_XRAY_LOG_INTERFACE_H +#define XRAY_XRAY_LOG_INTERFACE_H + +#include "xray/xray_interface.h" +#include + +extern "C" { + +enum XRayLogInitStatus { + XRAY_LOG_UNINITIALIZED, + XRAY_LOG_INITIALIZING, + XRAY_LOG_INITIALIZED, + XRAY_LOG_FINALIZING, + XRAY_LOG_FINALIZED, +}; + +enum XRayLogFlushStatus { + XRAY_LOG_NOT_FLUSHING, + XRAY_LOG_FLUSHING, + XRAY_LOG_FLUSHED +}; + +struct XRayLogImpl { + XRayLogInitStatus (*log_init)(size_t, size_t, void *, size_t); + XRayLogInitStatus (*log_finalize)(); + void (*handle_arg0)(int32_t, XRayEntryType); + void (*handle_arg1)(int32_t, XRayEntryType, uint64_t); + XRayLogFlushStatus (*flush_log)(); +}; + +void __xray_set_log_impl(XRayLogImpl Impl); +XRayLogInitStatus __xray_log_init(size_t BufferSize, size_t MaxBuffers, + void *Args, size_t ArgsSize); +XRayLogInitStatus __xray_log_finalize(); +XRayLogFlushStatus __xray_log_flushLog(); +} + +#endif // XRAY_XRAY_LOG_INTERFACE_H Index: lib/xray/CMakeLists.txt =================================================================== --- lib/xray/CMakeLists.txt +++ lib/xray/CMakeLists.txt @@ -9,7 +9,8 @@ # XRay flight data recorder (FDR) implementation files. set(XRAY_FDR_SOURCES - xray_buffer_queue.cc) + xray_buffer_queue.cc + xray_fdr_logging.cc) set(x86_64_SOURCES xray_x86_64.cc Index: lib/xray/tests/CMakeLists.txt =================================================================== --- lib/xray/tests/CMakeLists.txt +++ lib/xray/tests/CMakeLists.txt @@ -8,7 +8,8 @@ ${COMPILER_RT_UNITTEST_CFLAGS} ${COMPILER_RT_GTEST_CFLAGS} -I${COMPILER_RT_SOURCE_DIR}/include - -I${COMPILER_RT_SOURCE_DIR}/lib/xray) + -I${COMPILER_RT_SOURCE_DIR}/lib/xray + -I${COMPILER_RT_SOURCE_DIR}/lib) macro(xray_compile obj_list source arch) get_filename_component(basename ${source} NAME) @@ -46,7 +47,8 @@ DEPS ${TEST_DEPS} LINK_FLAGS ${TARGET_LINK_FLAGS} -lstdc++ -lm ${CMAKE_THREAD_LIBS_INIT} - -L${COMPILER_RT_LIBRARY_OUTPUT_DIR} -lclang_rt.xray-fdr-${arch}) + -L${COMPILER_RT_LIBRARY_OUTPUT_DIR} -lclang_rt.xray-fdr-${arch} + -ldl -lrt) endif() # FIXME: Figure out how to run even just the unit tests on APPLE. endforeach() Index: lib/xray/tests/unit/CMakeLists.txt =================================================================== --- lib/xray/tests/unit/CMakeLists.txt +++ lib/xray/tests/unit/CMakeLists.txt @@ -1,2 +1,4 @@ add_xray_unittest(XRayBufferQueueTest SOURCES buffer_queue_test.cc xray_unit_test_main.cc) +add_xray_unittest(XRayFDRLoggingTest SOURCES + fdr_logging_test.cc xray_unit_test_main.cc) Index: lib/xray/tests/unit/fdr_logging_test.cc =================================================================== --- /dev/null +++ lib/xray/tests/unit/fdr_logging_test.cc @@ -0,0 +1,56 @@ +//===-- fdr_logging_test.cc -----------------------------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file is a part of XRay, a function call tracing system. +// +//===----------------------------------------------------------------------===// +#include "xray_fdr_logging.h" +#include "gtest/gtest.h" + +#include +#include +#include + +namespace __xray { +namespace { + +constexpr auto kBufferSize = 16384; +constexpr auto kBufferMax = 10; + +TEST(FDRLoggingTest, Simple) { + // Set up the XRay FDR logging implementation. + FDRLoggingOptions Options; + ASSERT_EQ(FDRLogging_init(kBufferSize, kBufferMax, &Options, + sizeof(FDRLoggingOptions)), + XRayLogInitStatus::XRAY_LOG_INITIALIZED); + FDRLogging_handleArg0(1, XRayEntryType::ENTRY); + FDRLogging_handleArg0(1, XRayEntryType::EXIT); + ASSERT_EQ(FDRLogging_flush(), XRayLogFlushStatus::XRAY_LOG_FLUSHED); + ASSERT_EQ(FDRLogging_finalize(), XRayLogInitStatus::XRAY_LOG_FINALIZED); + ASSERT_EQ(FDRLogging_reset(), XRayLogInitStatus::XRAY_LOG_UNINITIALIZED); + // FIXME: Figure out how to load them data. +} + +TEST(FDRLoggingTest, Multiple) { + FDRLoggingOptions Options; + ASSERT_EQ(FDRLogging_init(kBufferSize, kBufferMax, &Options, + sizeof(FDRLoggingOptions)), + XRayLogInitStatus::XRAY_LOG_INITIALIZED); + for (uint64_t I = 0; I < 100; ++I) { + FDRLogging_handleArg0(1, XRayEntryType::ENTRY); + FDRLogging_handleArg0(1, XRayEntryType::EXIT); + } + ASSERT_EQ(FDRLogging_flush(), XRayLogFlushStatus::XRAY_LOG_FLUSHED); + ASSERT_EQ(FDRLogging_finalize(), XRayLogInitStatus::XRAY_LOG_FINALIZED); + ASSERT_EQ(FDRLogging_reset(), XRayLogInitStatus::XRAY_LOG_UNINITIALIZED); + // FIXME: Figure out how to load them data. +} + +} // namespace +} // namespace __xray Index: lib/xray/xray_buffer_queue.cc =================================================================== --- lib/xray/xray_buffer_queue.cc +++ lib/xray/xray_buffer_queue.cc @@ -22,10 +22,11 @@ : BufferSize(B), Buffers(N) { for (auto &Buf : Buffers) { void *Tmp = malloc(BufferSize); - Buf.Buffer = Tmp; - Buf.Size = B; - if (Tmp != 0) + if (Tmp != nullptr) { + Buf.Buffer = Tmp; + Buf.Size = B; OwnedBuffers.insert(Tmp); + } } } @@ -36,6 +37,8 @@ if (Buffers.empty()) return std::make_error_code(std::errc::not_enough_memory); Buf = Buffers.front(); + Buffers.front().Buffer = nullptr; + Buffers.front().Size = 0; Buffers.pop_front(); return {}; } @@ -46,7 +49,7 @@ std::lock_guard Guard(Mutex); Buffers.push_back(Buf); Buf.Buffer = nullptr; - Buf.Size = BufferSize; + Buf.Size = 0; return {}; } @@ -58,7 +61,8 @@ BufferQueue::~BufferQueue() { for (auto &Buf : Buffers) { - free(Buf.Buffer); + if (Buf.Buffer != nullptr) + free(Buf.Buffer); Buf.Buffer = nullptr; Buf.Size = 0; } Index: lib/xray/xray_fdr_logging.h =================================================================== --- /dev/null +++ lib/xray/xray_fdr_logging.h @@ -0,0 +1,91 @@ +//===-- xray_fdr_logging.h ------------------------------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file is a part of XRay, a function call tracing system. +// +//===----------------------------------------------------------------------===// +#ifndef XRAY_XRAY_FDR_LOGGING_H +#define XRAY_XRAY_FDR_LOGGING_H + +#include "xray/xray_log_interface.h" + +// FDR (Flight Data Recorder) Mode +// =============================== +// +// The XRay whitepaper describes a mode of operation for function call trace +// logging that involves writing small records into an in-memory circular +// buffer, that then gets logged to disk on demand. To do this efficiently and +// capture as much data as we can, we use smaller records compared to the +// default mode of always writing fixed-size records. + +namespace __xray { + +// A MetadataRecord encodes the kind of record in its first byte, and have 15 +// additional bytes in the end to hold free-form data. +struct alignas(16) MetadataRecord { + // A MetadataRecord must always have a type of 1. + int Type : 1; + + // Each kind of record is represented as a 7-bit value (even though we use an + // unsigned 8-bit enum class to do so). + enum RecordKind : uint8_t { + NewBuffer, + EndOfBuffer, + NewCPUId, + TSCWrap, + WalltimeMarker, + }; + int RecordKind : 7; // Use 7 bits to identify this record type. + char Data[15]; +} __attribute__((packed)); + +static_assert(sizeof(MetadataRecord) == 16, "Wrong size for MetadataRecord."); + +struct alignas(8) FunctionRecord { + // A FunctionRecord must always have a type of 0. + int Type : 1; + enum RecordKind { + FunctionEnter = 0x00, + FunctionExit = 0x01, + FunctionTailExit = 0x02, + }; + int RecordKind : 3; + + // We only use 28 bits of the function ID, so that we can use as few bytes as + // possible. This means we only support 2^28 (268,435,456) unique function ids + // in a single binary. + int FuncId : 28; + + // We use another 4 bytes to hold the delta between the previous entry's TSC. + // In case we've found that the distance is greater than the allowable 32 bits + // (either because we are running in a different CPU and the TSC might be + // different then), we should use a MetadataRecord before this FunctionRecord + // that will contain the full TSC for that CPU, and keep this to 0. + uint32_t TSCDelta; +} __attribute__((packed)); + +static_assert(sizeof(FunctionRecord) == 8, "Wrong size for FunctionRecord."); + +// Options used by the FDR implementation. +struct FDRLoggingOptions { + int Fd = -1; + bool ReportErrors = false; +}; + +// Flight Data Recorder mode implementation interfaces. +XRayLogInitStatus FDRLogging_init(std::size_t BufferSize, std::size_t BufferMax, + void *Options, size_t OptionsSize); +XRayLogInitStatus FDRLogging_finalize(); +void FDRLogging_handleArg0(int32_t FuncId, XRayEntryType Entry); +XRayLogFlushStatus FDRLogging_flush(); +XRayLogInitStatus FDRLogging_reset(); + +} // namespace __xray + +#endif // XRAY_XRAY_FDR_LOGGING_H Index: lib/xray/xray_fdr_logging.cc =================================================================== --- /dev/null +++ lib/xray/xray_fdr_logging.cc @@ -0,0 +1,451 @@ +//===-- xray_fdr_logging.cc ------------------------------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file is a part of XRay, a dynamic runtime instruementation system. +// +// Here we implement the Flight Data Recorder mode for XRay, where we use +// compact structures to store records in memory as well as when writing out the +// data to files. +// +//===----------------------------------------------------------------------===// +#include "xray_fdr_logging.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "xray_buffer_queue.h" +#include "xray_defs.h" + +// #include "sanitizer_common/sanitizer_common.h" + +namespace __xray { + +// Global BufferQueue. +std::shared_ptr BQ; + +std::atomic LoggingStatus{ + XRayLogInitStatus::XRAY_LOG_UNINITIALIZED}; + +std::atomic LogFlushStatus{ + XRayLogFlushStatus::XRAY_LOG_NOT_FLUSHING}; + +std::unique_ptr FDROptions; + +XRayLogInitStatus FDRLogging_init(std::size_t BufferSize, std::size_t BufferMax, + void *Options, + size_t OptionsSize) XRAY_NEVER_INSTRUMENT { + assert(OptionsSize == sizeof(FDRLoggingOptions)); + XRayLogInitStatus CurrentStatus = XRayLogInitStatus::XRAY_LOG_UNINITIALIZED; + if (!LoggingStatus.compare_exchange_weak( + CurrentStatus, XRayLogInitStatus::XRAY_LOG_INITIALIZING, + std::memory_order_release, std::memory_order_relaxed)) + return CurrentStatus; + + BQ = std::make_shared(BufferSize, BufferMax); + FDROptions.reset(new FDRLoggingOptions()); + *FDROptions = *reinterpret_cast(Options); + + // FIXME: Check the options! + + LoggingStatus.store(XRayLogInitStatus::XRAY_LOG_INITIALIZED, + std::memory_order_release); + return XRayLogInitStatus::XRAY_LOG_INITIALIZED; +} + +XRayLogFlushStatus FDRLogging_flush() XRAY_NEVER_INSTRUMENT { + XRayLogFlushStatus Result = XRayLogFlushStatus::XRAY_LOG_NOT_FLUSHING; + if (!LogFlushStatus.compare_exchange_weak( + Result, XRayLogFlushStatus::XRAY_LOG_FLUSHING, + std::memory_order_release, std::memory_order_relaxed)) + return Result; + + // Make a copy of the BufferQueue pointer to prevent other threads that may be + // resetting it from blowing away the queue prematurely while we're dealing + // with it. + auto LocalBQ = BQ; + + // FIXME: Actually write out the file! + + LogFlushStatus.store(XRayLogFlushStatus::XRAY_LOG_FLUSHED, + std::memory_order_release); + return XRayLogFlushStatus::XRAY_LOG_FLUSHED; +} + +XRayLogInitStatus FDRLogging_finalize() XRAY_NEVER_INSTRUMENT { + XRayLogInitStatus CurrentStatus = XRayLogInitStatus::XRAY_LOG_INITIALIZED; + if (!LoggingStatus.compare_exchange_weak( + CurrentStatus, XRayLogInitStatus::XRAY_LOG_FINALIZING, + std::memory_order_release, std::memory_order_relaxed)) + return CurrentStatus; + + // Do special things to make the log finalize itself, and not allow any more + // operations to be performed until re-initialized. + BQ->finalize(); + + LoggingStatus.store(XRayLogInitStatus::XRAY_LOG_FINALIZED, + std::memory_order_release); + return XRayLogInitStatus::XRAY_LOG_FINALIZED; +} + +XRayLogInitStatus FDRLogging_reset() XRAY_NEVER_INSTRUMENT { + XRayLogInitStatus CurrentStatus = XRayLogInitStatus::XRAY_LOG_FINALIZED; + if (!LoggingStatus.compare_exchange_weak( + CurrentStatus, XRayLogInitStatus::XRAY_LOG_UNINITIALIZED, + std::memory_order_release, std::memory_order_relaxed)) + return CurrentStatus; + + // Release the in-memory buffer queue. + BQ.reset(); + + // Spin until the flushing status is flushed. + XRayLogFlushStatus CurrentFlushingStatus = + XRayLogFlushStatus::XRAY_LOG_FLUSHED; + while (!LogFlushStatus.compare_exchange_weak( + CurrentFlushingStatus, XRayLogFlushStatus::XRAY_LOG_NOT_FLUSHING, + std::memory_order_release, std::memory_order_relaxed)) { + if (CurrentFlushingStatus == XRayLogFlushStatus::XRAY_LOG_NOT_FLUSHING) + break; + CurrentFlushingStatus = XRayLogFlushStatus::XRAY_LOG_FLUSHED; + } + + // At this point, we know that the status is flushed, and that we can assume + return XRayLogInitStatus::XRAY_LOG_UNINITIALIZED; +} + +namespace { +thread_local BufferQueue::Buffer Buffer; +thread_local char *RecordPtr = nullptr; + +void setupNewBuffer(const BufferQueue::Buffer &Buffer) XRAY_NEVER_INSTRUMENT { + RecordPtr = static_cast(Buffer.Buffer); + + static constexpr int InitRecordsCount = 2; + std::aligned_storage::type Records[InitRecordsCount]; + { + // Write out a MetadataRecord to signify that this is the start of a new + // buffer, associated with a particular thread, with a new CPU. For the + // data, we have 15 bytes to squeeze as much information as we can. At this + // point we only write down the following bytes: + // - Thread ID (pid_t, 4 bytes) + auto &NewBuffer = *reinterpret_cast(&Records[0]); + NewBuffer.Type = 1; + NewBuffer.RecordKind = MetadataRecord::RecordKind::NewBuffer; + *reinterpret_cast(&NewBuffer.Data) = getpid(); + } + + // Also write the WalltimeMarker record. + { + static_assert(sizeof(time_t) == 8, "time_t needs to be 8 bytes"); + auto &WalltimeMarker = *reinterpret_cast(&Records[1]); + WalltimeMarker.Type = 1; + WalltimeMarker.RecordKind = MetadataRecord::RecordKind::WalltimeMarker; + timespec TS{0, 0}; + clock_gettime(CLOCK_MONOTONIC, &TS); + std::memcpy(WalltimeMarker.Data, &TS, sizeof(TS)); + } + std::memcpy(RecordPtr, Records, sizeof(MetadataRecord) * InitRecordsCount); + RecordPtr += sizeof(MetadataRecord) * InitRecordsCount; +} + +void writeNewCPUIdMetadata(unsigned CPU, uint64_t TSC) XRAY_NEVER_INSTRUMENT { + MetadataRecord NewCPUId; + NewCPUId.Type = 1; + NewCPUId.RecordKind = MetadataRecord::RecordKind::NewCPUId; + + // The data for the New CPU will contain the following bytes: + // - CPU ID (uint16_t, 4 bytes) + // - Full TSC (uint64_t, 8 bytes) + // Total = 12 bytes. + *reinterpret_cast(&NewCPUId.Data) = CPU; + *reinterpret_cast(&NewCPUId.Data[sizeof(uint16_t)]) = TSC; + std::memcpy(RecordPtr, &NewCPUId, sizeof(MetadataRecord)); + RecordPtr += sizeof(MetadataRecord); +} + +void writeEOBMetadata() XRAY_NEVER_INSTRUMENT { + MetadataRecord EOBMeta; + EOBMeta.Type = 1; + EOBMeta.RecordKind = MetadataRecord::RecordKind::EndOfBuffer; + // For now we don't write any bytes into the Data field. + std::memcpy(RecordPtr, &EOBMeta, sizeof(MetadataRecord)); + RecordPtr += sizeof(MetadataRecord); +} + +void writeTSCWrapMetadata(uint64_t TSC) XRAY_NEVER_INSTRUMENT { + MetadataRecord TSCWrap; + TSCWrap.Type = 1; + TSCWrap.RecordKind = MetadataRecord::RecordKind::TSCWrap; + + // The data for the TSCWrap record contains the following bytes: + // - Full TSC (uint64_t, 8 bytes) + // Total = 8 bytes. + *reinterpret_cast(&TSCWrap.Data) = TSC; + std::memcpy(RecordPtr, &TSCWrap, sizeof(MetadataRecord)); + RecordPtr += sizeof(MetadataRecord); +} + +constexpr auto MetadataRecSize = sizeof(MetadataRecord); +constexpr auto FunctionRecSize = sizeof(FunctionRecord); + +class ThreadExitBufferCleanup { + std::weak_ptr Buffers; + BufferQueue::Buffer &Buffer; + +public: + explicit ThreadExitBufferCleanup(std::weak_ptr BQ, + BufferQueue::Buffer &Buffer) + XRAY_NEVER_INSTRUMENT : Buffers(BQ), + Buffer(Buffer) {} + + ~ThreadExitBufferCleanup() noexcept XRAY_NEVER_INSTRUMENT { + if (RecordPtr == nullptr) + return; + + // We make sure that upon exit, a thread will write out the EOB + // MetadataRecord in the thread-local log, and also release the buffer to + // the queue. + assert((RecordPtr + MetadataRecSize) - static_cast(Buffer.Buffer) >= + static_cast(MetadataRecSize)); + if (auto BQ = Buffers.lock()) { + writeEOBMetadata(); + if (BQ->releaseBuffer(Buffer)) + return; + } + } +}; + +class RecursionGuard { + bool &Running; + const bool Valid; + +public: + explicit RecursionGuard(bool &R) : Running(R), Valid(!R) { + if (Valid) + Running = true; + } + + RecursionGuard(const RecursionGuard &) = delete; + RecursionGuard(RecursionGuard &&) = delete; + RecursionGuard &operator=(const RecursionGuard &) = delete; + RecursionGuard &operator=(RecursionGuard &&) = delete; + + explicit operator bool() const { return Valid; } + + ~RecursionGuard() noexcept { + if (Valid) + Running = false; + } +}; + +inline bool loggingInitialized() { + return LoggingStatus.load(std::memory_order_acquire) == + XRayLogInitStatus::XRAY_LOG_INITIALIZED; +} + +} // namespace + +void FDRLogging_handleArg0(int32_t FuncId, + XRayEntryType Entry) XRAY_NEVER_INSTRUMENT { + // We want to get the TSC as early as possible, so that we can check whether + // we've seen this CPU before. We also do it before we load anything else, to + // allow for forward progress with the scheduling. + unsigned CPU; + uint64_t TSC = __rdtscp(&CPU); + + // Bail out right away if logging is not initialized yet. + if (LoggingStatus.load(std::memory_order_acquire) != + XRayLogInitStatus::XRAY_LOG_INITIALIZED) + return; + + // We use a thread_local variable to keep track of which CPUs we've already + // run, and the TSC times for these CPUs. This allows us to stop repeating the + // CPU field in the function records. + // + // We assume that we'll support only 65536 CPUs for x86_64. + // FIXME: Maybe not use 8kb just for a "known CPUs" bitset? + thread_local std::bitset::max()> KnownCPUs; + thread_local uint16_t CurrentCPU = std::numeric_limits::max(); + thread_local uint64_t LastTSC = 0; + + // Make sure a thread that's ever called handleArg0 has a thread-local + // live reference to the buffer queue for this particular instance of + // FDRLogging, and that we're going to clean it up when the thread exits. + thread_local auto LocalBQ = BQ; + thread_local ThreadExitBufferCleanup Cleanup(LocalBQ, Buffer); + + // Prevent signal handler recursion, so in case we're already in a log writing + // mode and the signal handler comes in (and is also instrumented) then we + // don't want to be clobbering potentially partial writes already happening in + // the thread. We use a simple thread_local latch to only allow one on-going + // handleArg0 to happen at any given time. + thread_local bool Running = false; + RecursionGuard Guard{Running}; + if (!Guard) { + assert(Running == true && "RecursionGuard is buggy!"); + return; + } + + if (!loggingInitialized() || LocalBQ->finalizing()) { + writeEOBMetadata(); + if (BQ->releaseBuffer(Buffer)) + return; + RecordPtr = nullptr; + } + + if (Buffer.Buffer == nullptr) { + if (LocalBQ->getBuffer(Buffer)) { + return; + } + + setupNewBuffer(Buffer); + } + + if (CurrentCPU == std::numeric_limits::max()) { + // This means this is the first CPU this thread has ever run on. We set the + // current CPU and record this as the first TSC we've seen. + CurrentCPU = CPU; + writeNewCPUIdMetadata(CPU, TSC); + } + + // Before we go setting up writing new function entries, we need to be + // really + // careful about the pointer math we're doing. This means we need to + // ensure + // that the record we are about to write is going to fit into the buffer, + // without overflowing the buffer. + // + // To do this properly, we use the following assumptions: + // + // - The least number of bytes we will ever write is 8 + // (sizeof(FunctionRecord)) only if the delta between the previous entry + // and this entry is within 32 bits. + // - The most number of bytes we will ever write is 8 + 16 = 24. This is + // computed by: + // + // sizeof(FunctionRecord) + sizeof(MetadataRecord) + // + // These arise in the following cases: + // + // 1. When the delta between the TSC we get and the previous TSC for the + // same CPU is outside of the uint32_t range, we end up having to + // write a MetadataRecord to indicate a "tsc wrap" before the actual + // FunctionRecord. + // 2. When we learn that we've moved CPUs, we need to write a + // MetadataRecord to indicate a "cpu change", and thus write out the + // current TSC for that CPU before writing out the actual + // FunctionRecord. + // 3. When we learn about a new CPU ID, we need to write down a "new cpu + // id" MetadataRecord before writing out the actual FunctionRecord. + // + // - An End-of-Buffer (EOB) MetadataRecord is 16 bytes. + // + // So the math we need to do is to determine whether writing 24 bytes past the + // current pointer leaves us with enough bytes to write the EOB + // MetadataRecord. If we don't have enough space after writing as much as 24 + // bytes in the end of the buffer, we need to write out the EOB, get a new + // Buffer, set it up properly before doing any further writing. + // + char *BufferStart = static_cast(Buffer.Buffer); + if ((RecordPtr + (MetadataRecSize + FunctionRecSize)) - BufferStart < + static_cast(MetadataRecSize)) { + writeEOBMetadata(); + if (LocalBQ->releaseBuffer(Buffer)) + return; + if (LocalBQ->getBuffer(Buffer)) + return; + setupNewBuffer(Buffer); + } + + // By this point, we are now ready to write at most 24 bytes (one metadata + // record and one function record). + BufferStart = static_cast(Buffer.Buffer); + assert((RecordPtr + (MetadataRecSize + FunctionRecSize)) - BufferStart >= + static_cast(MetadataRecSize) && + "Misconfigured BufferQueue provided; Buffer size not large enough."); + + std::aligned_storage::type + AlignedFuncRecordBuffer; + auto &FuncRecord = + *reinterpret_cast(&AlignedFuncRecordBuffer); + FuncRecord.Type = 0; + + // Only get the lower 28 bits of the function id. + FuncRecord.FuncId = FuncId | ~(0x03 << 28); + + // Here we compute the TSC Delta. There are a few interesting situations we + // need to account for: + // + // - The thread has migrated to a different CPU. If this is the case, then + // we write down the following records: + // + // 1. A 'NewCPUId' Metadata record. + // 2. A FunctionRecord with a 0 for the TSCDelta field. + // + // - The TSC delta is greater than the 32 bits we can store in a + // FunctionRecord. In this case we write down the following records: + // + // 1. A 'TSCWrap' Metadata record. + // 2. A FunctionRecord with a 0 for the TSCDelta field. + // + // - The TSC delta is representable within the 32 bits we can store in a + // FunctionRecord. In this case we write down just a FunctionRecord with + // the correct TSC delta. + // + FuncRecord.TSCDelta = 0; + if (CPU != CurrentCPU) { + // We've moved to a new CPU. + writeNewCPUIdMetadata(CPU, TSC); + } else { + // If the delta is greater than the range for a uint32_t, then we write out + // the TSC wrap metadata entry with the full TSC, and the TSC for the + // function record be 0. + auto Delta = LastTSC - TSC; + if (Delta > (1L << 32) - 1) + writeTSCWrapMetadata(TSC); + else + FuncRecord.TSCDelta = Delta; + } + + // We then update our "LastTSC" and "CurrentCPU" thread-local variables to aid + // us in future computations of this TSC delta value. + LastTSC = TSC; + CurrentCPU = CPU; + + switch (Entry) { + case XRayEntryType::ENTRY: + FuncRecord.RecordKind = FunctionRecord::RecordKind::FunctionEnter; + break; + case XRayEntryType::EXIT: + FuncRecord.RecordKind = FunctionRecord::RecordKind::FunctionExit; + break; + case XRayEntryType::TAIL: + FuncRecord.RecordKind = FunctionRecord::RecordKind::FunctionTailExit; + break; + } + + std::memcpy(RecordPtr, &AlignedFuncRecordBuffer, sizeof(FunctionRecord)); + RecordPtr += sizeof(FunctionRecord); + + // If we've exhausted the buffer by this time, we then release the buffer to + // make sure that other threads may start using this buffer. + if ((RecordPtr + MetadataRecSize) - BufferStart == MetadataRecSize) { + writeEOBMetadata(); + if (LocalBQ->releaseBuffer(Buffer)) + return; + RecordPtr = nullptr; + } +} + +} // namespace __xray