From 1ed0b35520e7d0a5545dff3f73539fd8021522ef Mon Sep 17 00:00:00 2001 From: Rubidium Date: Sun, 15 Jan 2023 11:08:08 +0100 Subject: [PATCH] Fix #10009: bad overflow protection when taking out loans --- src/core/overflowsafe_type.hpp | 3 +++ src/misc_cmd.cpp | 6 ++++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/core/overflowsafe_type.hpp b/src/core/overflowsafe_type.hpp index 14f0eaa7a7..0c3957aaad 100644 --- a/src/core/overflowsafe_type.hpp +++ b/src/core/overflowsafe_type.hpp @@ -176,6 +176,9 @@ public: inline constexpr bool operator <= (const int other) const { return !(*this > other); } inline constexpr operator T () const { return this->m_value; } + + static inline constexpr OverflowSafeInt max() { return T_MAX; } + static inline constexpr OverflowSafeInt min() { return T_MIN; } }; diff --git a/src/misc_cmd.cpp b/src/misc_cmd.cpp index 6422bcf3ac..a18504c1ef 100644 --- a/src/misc_cmd.cpp +++ b/src/misc_cmd.cpp @@ -60,8 +60,10 @@ CommandCost CmdIncreaseLoan(DoCommandFlag flags, LoanCommand cmd, Money amount) break; } - /* Overflow protection */ - if (c->money + c->current_loan + loan < c->money) return CMD_ERROR; + /* In case adding the loan triggers the overflow protection of Money, + * we would essentially be losing money as taking and repaying the loan + * immediately would not get us back to the same bank balance anymore. */ + if (c->money > Money::max() - loan) return CMD_ERROR; if (flags & DC_EXEC) { c->money += loan;