Skip to content

Commit

Permalink
Fix thread-safety violation in Allocations Profiler:
Browse files Browse the repository at this point in the history
Re-use the shared `ptls->bt_data` buffer from the thread-local storage
for the buffer, to ensure that each thread has a separate buffer.

This buffer is shared with the exception throwing mechanism, but is safe
to share since julia exception throwing never interleaves with
allocations profiling.
  • Loading branch information
NHDaly committed Feb 15, 2022
1 parent 99aab66 commit 4b5d076
Showing 1 changed file with 13 additions and 4 deletions.
17 changes: 13 additions & 4 deletions src/gc-alloc-profiler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -49,15 +49,24 @@ jl_combined_results g_combined_results; // Will live forever.
// === stack stuff ===

jl_raw_backtrace_t get_raw_backtrace() JL_NOTSAFEPOINT {
// A single large buffer to record backtraces onto
static jl_bt_element_t static_bt_data[JL_MAX_BT_SIZE];
// We first record the backtrace onto a MAX-sized buffer, so that we don't have to
// allocate the buffer until we know the size. To ensure thread-safety, we *re-use the
// per-thread backtrace buffer*, which is shared with Julia's exception throwing
// mechanism. This sharing is safe, because this function cannot be interleaved with
// exception throwing.
jl_ptls_t ptls = jl_current_task->ptls;
jl_bt_element_t *shared_bt_data_buffer = ptls->bt_data;

size_t bt_size = rec_backtrace(static_bt_data, JL_MAX_BT_SIZE, 2);
size_t bt_size = rec_backtrace(shared_bt_data_buffer, JL_MAX_BT_SIZE, 2);

// Then we copy only the needed bytes out of the buffer into our profile.
size_t bt_bytes = bt_size * sizeof(jl_bt_element_t);
jl_bt_element_t *bt_data = (jl_bt_element_t*) malloc(bt_bytes);
memcpy(bt_data, static_bt_data, bt_bytes);
memcpy(bt_data, shared_bt_data_buffer, bt_bytes);

// Now, "clear" the ptls buffer, so that this buffer isn't incorrectly rooting objects
// in that buffer.
ptls->bt_size = 0;

return jl_raw_backtrace_t{
bt_data,
Expand Down

0 comments on commit 4b5d076

Please sign in to comment.