Prevent out of bounds access of dbg info arrays

closes https://github.com/official-stockfish/Stockfish/pull/5721

No functional change
This commit is contained in:
Shawn Xu
2024-12-15 01:35:15 -08:00
committed by Disservin
parent ba145332c9
commit 77ec878ffa
+29 -24
View File
@@ -18,7 +18,9 @@
#include "misc.h"
#include <array>
#include <atomic>
#include <cassert>
#include <cctype>
#include <cmath>
#include <cstdlib>
@@ -287,7 +289,10 @@ template<size_t N>
struct DebugInfo {
std::atomic<int64_t> data[N] = {0};
constexpr std::atomic<int64_t>& operator[](int index) { return data[index]; }
[[nodiscard]] constexpr std::atomic<int64_t>& operator[](size_t index) {
assert(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<DebugInfo<2>, MaxDebugSlots> hit;
std::array<DebugInfo<2>, MaxDebugSlots> mean;
std::array<DebugInfo<3>, MaxDebugSlots> stdev;
std::array<DebugInfo<6>, MaxDebugSlots> correl;
std::array<DebugExtremes, MaxDebugSlots> 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() {