From 23f54ba4a48ada84355d6e45217b733edb70fc7d Mon Sep 17 00:00:00 2001 From: Shawn Xu Date: Sun, 15 Dec 2024 01:35:15 -0800 Subject: [PATCH] prevent out of bounds access of dbg_* arrays no functional change --- src/misc.cpp | 53 ++++++++++++++++++++++++++++------------------------ 1 file changed, 29 insertions(+), 24 deletions(-) diff --git a/src/misc.cpp b/src/misc.cpp index 10c86b7a6e7..6976eeb281f 100644 --- a/src/misc.cpp +++ b/src/misc.cpp @@ -18,7 +18,9 @@ #include "misc.h" +#include #include +#include #include #include #include @@ -287,7 +289,10 @@ template struct DebugInfo { std::atomic data[N] = {0}; - constexpr std::atomic& operator[](int index) { return data[index]; } + [[nodiscard]] constexpr std::atomic& operator[](size_t index) { + assert(0 <= index && index < N); + return data[index]; + } }; struct DebugExtremes: public DebugInfo<3> { @@ -297,54 +302,54 @@ struct DebugExtremes: public DebugInfo<3> { } }; -DebugInfo<2> hit[MaxDebugSlots]; -DebugInfo<2> mean[MaxDebugSlots]; -DebugInfo<3> stdev[MaxDebugSlots]; -DebugInfo<6> correl[MaxDebugSlots]; -DebugExtremes extremes[MaxDebugSlots]; +std::array, MaxDebugSlots> hit; +std::array, MaxDebugSlots> mean; +std::array, MaxDebugSlots> stdev; +std::array, MaxDebugSlots> correl; +std::array extremes; } // namespace void dbg_hit_on(bool cond, int slot) { - ++hit[slot][0]; + ++hit.at(slot)[0]; if (cond) - ++hit[slot][1]; + ++hit.at(slot)[1]; } void dbg_mean_of(int64_t value, int slot) { - ++mean[slot][0]; - mean[slot][1] += value; + ++mean.at(slot)[0]; + mean.at(slot)[1] += value; } void dbg_stdev_of(int64_t value, int slot) { - ++stdev[slot][0]; - stdev[slot][1] += value; - stdev[slot][2] += value * value; + ++stdev.at(slot)[0]; + stdev.at(slot)[1] += value; + stdev.at(slot)[2] += value * value; } void dbg_extremes_of(int64_t value, int slot) { - ++extremes[slot][0]; + ++extremes.at(slot)[0]; - int64_t current_max = extremes[slot][1].load(); - while (current_max < value && !extremes[slot][1].compare_exchange_weak(current_max, value)) + int64_t current_max = extremes.at(slot)[1].load(); + while (current_max < value && !extremes.at(slot)[1].compare_exchange_weak(current_max, value)) {} - int64_t current_min = extremes[slot][2].load(); - while (current_min > value && !extremes[slot][2].compare_exchange_weak(current_min, value)) + int64_t current_min = extremes.at(slot)[2].load(); + while (current_min > value && !extremes.at(slot)[2].compare_exchange_weak(current_min, value)) {} } void dbg_correl_of(int64_t value1, int64_t value2, int slot) { - ++correl[slot][0]; - correl[slot][1] += value1; - correl[slot][2] += value1 * value1; - correl[slot][3] += value2; - correl[slot][4] += value2 * value2; - correl[slot][5] += value1 * value2; + ++correl.at(slot)[0]; + correl.at(slot)[1] += value1; + correl.at(slot)[2] += value1 * value1; + correl.at(slot)[3] += value2; + correl.at(slot)[4] += value2 * value2; + correl.at(slot)[5] += value1 * value2; } void dbg_print() {