Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for tracy memory tracking #4272

Merged
merged 1 commit into from
May 30, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 74 additions & 1 deletion src/main/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
#include "util/Backtrace.h"
#include "util/FileSystemException.h"
#include "util/Logging.h"
#include <mutex>
#include <regex>
#include <stdexcept>

Expand All @@ -25,6 +26,7 @@
#include <system_error>
#include <xdrpp/marshal.h>
#ifdef USE_TRACY
#include <Tracy.hpp>
#include <TracyC.h>
#endif

Expand Down Expand Up @@ -237,6 +239,73 @@ checkStellarCoreMajorVersionProtocolIdentity()
}
}

#ifdef USE_TRACY

std::mutex TRACY_MUTEX;
static int TRACY_NOT_STARTED = 0;
static int TRACY_RUNNING = 1;
static int TRACY_STOPPED = 2;
static int TRACY_STATE = TRACY_NOT_STARTED;

// Call this only with mutex held
bool
tracyEnabled(std::lock_guard<std::mutex> const& _guard)
{
if (TRACY_STATE == TRACY_NOT_STARTED)
{
stellar::rust_bridge::start_tracy();
TRACY_STATE = TRACY_RUNNING;
}
return TRACY_STATE != TRACY_STOPPED;
}

void*
operator new(std::size_t count)
{
auto ptr = malloc(count);
std::lock_guard<std::mutex> guard(TRACY_MUTEX);
if (tracyEnabled(guard))
{
TracyAlloc(ptr, count);
}
return ptr;
}

void
operator delete(void* ptr) noexcept
{
std::lock_guard<std::mutex> guard(TRACY_MUTEX);
if (tracyEnabled(guard))
{
TracyFree(ptr);
}
free(ptr);
}

void*
operator new[](std::size_t count)
{
auto ptr = malloc(count);
std::lock_guard<std::mutex> guard(TRACY_MUTEX);
if (tracyEnabled(guard))
{
TracyAlloc(ptr, count);
}
return ptr;
}

void
operator delete[](void* ptr) noexcept
{
std::lock_guard<std::mutex> guard(TRACY_MUTEX);
if (tracyEnabled(guard))
{
TracyFree(ptr);
}
free(ptr);
}
#endif

int
main(int argc, char* const* argv)
{
Expand Down Expand Up @@ -276,7 +345,11 @@ main(int argc, char* const* argv)

int res = handleCommandLine(argc, argv);
#ifdef USE_TRACY
___tracy_shutdown_profiler();
{
std::lock_guard<std::mutex> guard(TRACY_MUTEX);
___tracy_shutdown_profiler();
TRACY_STATE = TRACY_STOPPED;
}
#endif
return res;
}
Loading