Okay, I will review the code and attempt to identify potential out-of-bounds memory access issues. Since I don't have the full context of how the engine is used, I'll focus on areas where buffer sizes are defined, arrays are indexed, and memory is allocated, looking for inconsistencies or potential overflows.
Based on the provided file list, here are a few files I will examine more closely:
- ./repos/Stockfish-1/src/bitboard.cpp & ./repos/Stockfish-1/src/bitboard.h: These files define bitboard representations and operations. Out-of-bounds access could occur in bitboard manipulations, especially within the
init() function where lookup tables are initialized, or in functions that access the Magics array.
- ./repos/Stockfish-1/src/movegen.cpp & ./repos/Stockfish-1/src/movegen.h: These files generate moves, and a move list is essentially an array. Incorrectly calculating the size of this array or writing past the end of it during move generation would cause a memory issue. The
generate() and make_promotions() templates are good places to start. Also, check ExtMove and MoveList definitions.
- ./repos/Stockfish-1/src/position.cpp & ./repos/Stockfish-1/src/position.h: These files define the
Position class, which represents the board state. Out-of-bounds access could occur in the set() function when parsing FEN strings, or when accessing the board array. Also, look into castlingRightsMask definition.
- ./repos/Stockfish-1/src/tt.cpp (not provided, but relevant if available): Transposition tables are large hash tables. Resizing or accessing them incorrectly is a common source of memory bugs.
- ./repos/Stockfish-1/src/memory.cpp & ./repos/Stockfish-1/src/memory.h: Check if allocation size and alignment are correct.
Let's start with bitboard.cpp and bitboard.h.
In bitboard.h, I see these definitions:
extern uint8_t PopCnt16[1 << 16];
extern uint8_t SquareDistance[SQUARE_NB][SQUARE_NB];
extern Bitboard BetweenBB[SQUARE_NB][SQUARE_NB];
extern Bitboard LineBB[SQUARE_NB][SQUARE_NB];
extern Bitboard PseudoAttacks[PIECE_TYPE_NB][SQUARE_NB];
extern Bitboard PawnAttacks[COLOR_NB][SQUARE_NB];
and in bitboard.cpp:
void Bitboards::init() {
for (unsigned i = 0; i < (1 << 16); ++i)
PopCnt16[i] = uint8_t(std::bitset<16>(i).count());
for (Square s1 = SQ_A1; s1 <= SQ_H8; ++s1)
for (Square s2 = SQ_A1; s2 <= SQ_H8; ++s2)
SquareDistance[s1][s2] = std::max(distance<File>(s1, s2), distance<Rank>(s1, s2));
init_magics(ROOK, RookTable, Magics);
init_magics(BISHOP, BishopTable, Magics);
for (Square s1 = SQ_A1; s1 <= SQ_H8; ++s1)
{
PawnAttacks[WHITE][s1] = pawn_attacks_bb<WHITE>(square_bb(s1));
PawnAttacks[BLACK][s1] = pawn_attacks_bb<BLACK>(square_bb(s1));
for (int step : {-9, -8, -7, -1, 1, 7, 8, 9})
PseudoAttacks[KING][s1] |= safe_destination(s1, step);
for (int step : {-17, -15, -10, -6, 6, 10, 15, 17})
PseudoAttacks[KNIGHT][s1] |= safe_destination(s1, step);
PseudoAttacks[QUEEN][s1] = PseudoAttacks[BISHOP][s1] = attacks_bb<BISHOP>(s1, 0);
PseudoAttacks[QUEEN][s1] |= PseudoAttacks[ROOK][s1] = attacks_bb<ROOK>(s1, 0);
for (PieceType pt : {BISHOP, ROOK})
for (Square s2 = SQ_A1; s2 <= SQ_H8; ++s2)
{
if (PseudoAttacks[pt][s1] & s2)
{
LineBB[s1][s2] = (attacks_bb(pt, s1, 0) & attacks_bb(pt, s2, 0)) | s1 | s2;
BetweenBB[s1][s2] =
(attacks_bb(pt, s1, square_bb(s2)) & attacks_bb(pt, s2, square_bb(s1)));
}
BetweenBB[s1][s2] |= s2;
}
}
}
The loops iterating through Square s1 and Square s2 from SQ_A1 to SQ_H8 look correct, as SQUARE_NB is correctly defined. The PopCnt16 initialization also looks safe. The safe_destination function checks bounds. Let's investigate Magics array.
alignas(64) Magic Magics[SQUARE_NB][2];
void init_magics(PieceType pt, Bitboard table[], Magic magics[][2]) {
for (Square s = SQ_A1; s <= SQ_H8; ++s)
{
// Board edges are not considered in the relevant occupancies
Bitboard edges = ((Rank1BB | Rank8BB) & ~rank_bb(s)) | ((FileABB | FileHBB) & ~file_bb(s));
// Given a square 's', the mask is the bitboard of sliding attacks from
// 's' computed on an empty board. The index must be big enough to contain
// all the attacks for each possible subset of the mask and so is 2 power
// the number of 1s of the mask. Hence we deduce the size of the shift to
// apply to the 64 or 32 bits word to get the index.
Magic& m = magics[s][pt - BISHOP];
m.mask = sliding_attack(pt, s, 0) & ~edges;
#ifndef USE_PEXT
m.shift = (Is64Bit ? 64 : 32) - popcount(m.mask);
#endif
// Set the offset for the attacks table of the square. We have individual
// table sizes for each square with "Fancy Magic Bitboards".
m.attacks = s == SQ_A1 ? table : magics[s - 1][pt - BISHOP].attacks + size;
size = 0;
// Use Carry-Rippler trick to enumerate all subsets of masks[s] and
// store the corresponding sliding attack bitboard in reference[].
Bitboard b = 0;
do
{
reference[size] = sliding_attack(pt, s, b);
if (HasPext)
m.attacks[pext(b, m.mask)] = reference[size];
size++;
b = (b - m.mask) & m.mask;
} while (b);
In init_magics, the key line to watch is:
m.attacks = s == SQ_A1 ? table : magics[s - 1][pt - BISHOP].attacks + size;
This calculates offsets into the RookTable or BishopTable. The size variable represents the size of the attack table for the previous square. If the value of size is calculated incorrectly, m.attacks may point outside the allocated memory region for the current square s. pt - BISHOP is either 0 or 1, so that index is safe. The loop condition s <= SQ_H8 also looks correct.
The most probable source of error is size is calculated incorrectly and the offset is wrong. I would put a breakpoint in the loop and inspect the values of s, pt, size, magics[s - 1][pt - BISHOP].attacks and m.attacks to check if the address m.attacks is in the correct range.
Next, I will examine movegen.cpp and movegen.h.
In movegen.h:
struct ExtMove: public Move {
int value;
void operator=(Move m) { data = m.raw(); }
// Inhibit unwanted implicit conversions to Move
// with an ambiguity that yields to a compile error.
operator float() const = delete;
};
inline bool operator<(const ExtMove& f, const ExtMove& s) { return f.value < s.value; }
template<GenType>
ExtMove* generate(const Position& pos, ExtMove* moveList);
// The MoveList struct wraps the generate() function and returns a convenient
// list of moves. Using MoveList is sometimes preferable to directly calling
// the lower level generate() function.
template<GenType T>
struct MoveList {
explicit MoveList(const Position& pos) :
last(generate<T>(pos, moveList)) {}
const ExtMove* begin() const { return moveList; }
const ExtMove* end() const { return last; }
size_t size() const { return last - moveList; }
bool contains(Move move) const { return std::find(begin(), end(), move) != end(); }
private:
ExtMove moveList[MAX_MOVES], *last;
};
Here, MAX_MOVES is a crucial size. If the move generation functions write more than MAX_MOVES moves into the moveList array, a buffer overflow will occur. Let's see where MAX_MOVES is defined and how it is used in movegen.cpp.
In movegen.cpp:
template<GenType Type, Direction D, bool Enemy>
ExtMove* make_promotions(ExtMove* moveList, [[maybe_unused]] Square to) {
constexpr bool all = Type == EVASIONS || Type == NON_EVASIONS;
if constexpr (Type == CAPTURES || all)
*moveList++ = Move::make<PROMOTION>(to - D, to, QUEEN);
if constexpr ((Type == CAPTURES && Enemy) || (Type == QUIETS && !Enemy) || all)
{
*moveList++ = Move::make<PROMOTION>(to - D, to, ROOK);
*moveList++ = Move::make<PROMOTION>(to - D, to, BISHOP);
*moveList++ = Move::make<PROMOTION>(to - D, to, KNIGHT);
}
return moveList;
}
In make_promotions, up to 4 moves can be added to the moveList, if all the conditions are satisfied. This looks fine since MAX_MOVES is used to define moveList buffer.
Now the most important part, the generate functions:
template<Color Us, GenType Type>
ExtMove* generate_all(const Position& pos, ExtMove* moveList) {
static_assert(Type != LEGAL, "Unsupported type in generate_all()");
const Square ksq = pos.square<KING>(Us);
Bitboard target;
// Skip generating non-king moves when in double check
if (Type != EVASIONS || !more_than_one(pos.checkers()))
{
target = Type == EVASIONS ? between_bb(ksq, lsb(pos.checkers()))
: Type == NON_EVASIONS ? ~pos.pieces(Us)
: Type == CAPTURES ? pos.pieces(~Us)
: ~pos.pieces(); // QUIETS
moveList = generate_pawn_moves<Us, Type>(pos, moveList, target);
moveList = generate_moves<Us, KNIGHT>(pos, moveList, target);
moveList = generate_moves<Us, BISHOP>(pos, moveList, target);
moveList = generate_moves<Us, ROOK>(pos, moveList, target);
moveList = generate_moves<Us, QUEEN>(pos, moveList, target);
}
Bitboard b = attacks_bb<KING>(ksq) & (Type == EVASIONS ? ~pos.pieces(Us) : target);
while (b)
*moveList++ = Move(ksq, pop_lsb(b));
if ((Type == QUIETS || Type == NON_EVASIONS) && pos.can_castle(Us & ANY_CASTLING))
for (CastlingRights cr : {Us & KING_SIDE, Us & QUEEN_SIDE})
if (!pos.castling_impeded(cr) && pos.can_castle(cr))
*moveList++ = Move::make<CASTLING>(ksq, pos.castling_rook_square(cr));
return moveList;
}
The code iterates through all possible moves and adds them to the moveList. It's crucial to ensure that the number of possible moves in any given position never exceeds MAX_MOVES. Double check every possible legal position and if it overflows.
Also, it is very important that MAX_MOVES definition is high enough. Let's find it in the codebase.
Without MAX_MOVES value, I cannot determine if there is a real bug here.
In position.h, the castlingRightsMask is defined as:
int castlingRightsMask[SQUARE_NB];
If set_castling_right in position.cpp writes out of bounds to this array, it would cause a memory corruption.
Overall, I recommend the following debugging steps:
- Verify
MAX_MOVES: Find the definition of MAX_MOVES and verify it is sufficiently large for all legal chess positions (taking promotions into account).
- Inspect
init_magics: Add breakpoints in bitboard.cpp inside the loop in the init_magics function to examine the values of s, pt, size, magics[s - 1][pt - BISHOP].attacks and m.attacks.
- Check array indexing: In
position.cpp, examine how castlingRightsMask is accessed within set_castling_right. Ensure the index is always within the bounds of the array.
- Add assertions: Add assertions in the move generation code (
movegen.cpp) to check if moveList exceeds the maximum allowed size (MAX_MOVES).
- Run with a memory checker: Use a memory checker tool (e.g., Valgrind on Linux, AddressSanitizer or MemorySanitizer with Clang/GCC) to detect out-of-bounds memory accesses during program execution.
Without more information about the specific error you're encountering, or the complete source code of Stockfish, it's difficult to pinpoint the exact cause of the bug. However, by focusing on these potential areas and using the recommended debugging techniques, you should be able to identify and resolve the out-of-bounds memory access issue.