From a44292c173bad87f8e77ac5249d7224d67f8413c Mon Sep 17 00:00:00 2001 From: Tomasz Sobczyk Date: Wed, 10 May 2023 16:29:24 +0200 Subject: [PATCH] Terminate on positions with piece configurations impossible in chess that could result in too many generated moves. (for example 3 rooks and 9 queens) --- src/position.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/position.cpp b/src/position.cpp index ee9d1d36fdd..3ddc680e465 100644 --- a/src/position.cpp +++ b/src/position.cpp @@ -227,6 +227,26 @@ Position& Position::set(const string& fenStr, bool isChess960, StateInfo* si, Th UCI::critical_error(std::string("Invalid FEN. Invalid piece: ") + std::string(1, token)); } + int pawns_w = count(WHITE); + int pawns_b = count(BLACK); + if (pawns_w > 8) + UCI::critical_error("Invalid FEN. WHITE has more than 8 pawns."); + if (pawns_b > 8) + UCI::critical_error("Invalid FEN. BLACK has more than 8 pawns."); + + int additional_knights_w = std::max((int)count(WHITE) - 2, 0); + int additional_knights_b = std::max((int)count(BLACK) - 2, 0); + int additional_bishops_w = std::max((int)count(WHITE) - 2, 0); + int additional_bishops_b = std::max((int)count(BLACK) - 2, 0); + int additional_rooks_w = std::max((int)count(WHITE) - 2, 0); + int additional_rooks_b = std::max((int)count(BLACK) - 2, 0); + int additional_queens_w = std::max((int)count(WHITE) - 1, 0); + int additional_queens_b = std::max((int)count(BLACK) - 1, 0); + if (additional_knights_w + additional_bishops_w + additional_rooks_w + additional_queens_w > 8 - pawns_w) + UCI::critical_error("Invalid FEN. Invalid piece configuration for WHITE."); + if (additional_knights_b + additional_bishops_b + additional_rooks_b + additional_queens_b > 8 - pawns_b) + UCI::critical_error("Invalid FEN. Invalid piece configuration for BLACK."); + // 2. Active color ss >> token; if (token != 'w' && token != 'b')