From dd74cdbdd3849fbd86e6613ef7ecab6c7857cb89 Mon Sep 17 00:00:00 2001 From: ivan tkachenko Date: Thu, 16 Jun 2022 00:17:42 +0300 Subject: [PATCH] upower: Prevent integer overflow during new brightness computation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Provably, if two integers can fit in 31 bits each, the result of their multiplication is expressible in 62 bits (let alone 63 available). So, this should be safe. And the division can't do much harm: the divisor is always at least 1, and worst case scenario — it would be so big that the overall results becomes zero. This code still assumes that the allowed brightness values can fit in 32 bits int, which is not totally unreasonable so far. BUG: 454161 (cherry picked from commit 2ebe655d220c9167b66893a823b2fff2e2b8a531) --- daemon/backends/upower/backlighthelper.cpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/daemon/backends/upower/backlighthelper.cpp b/daemon/backends/upower/backlighthelper.cpp index 84c6aee1..c9e34e4b 100644 --- a/daemon/backends/upower/backlighthelper.cpp +++ b/daemon/backends/upower/backlighthelper.cpp @@ -27,6 +27,7 @@ #include #include +#include #include #ifdef Q_OS_FREEBSD @@ -318,11 +319,13 @@ bool BacklightHelper::writeBrightness(int brightness) const #else if (!m_devices.isEmpty()) { - int first_maxbrightness = m_devices.constFirst().second; - if (first_maxbrightness <= 0) - first_maxbrightness = 1; + const int first_maxbrightness = std::max(1, m_devices.constFirst().second); for (const auto &device : m_devices) { - writeToDevice(device.first, brightness * device.second / first_maxbrightness); + // Some monitor brightness values are ridiculously high, and can easily overflow during computation + const qint64 new_brightness_64 = static_cast(brightness) * static_cast(device.second) / static_cast(first_maxbrightness); + // cautiously truncate it back + const int new_brightness = static_cast(std::min(static_cast(std::numeric_limits::max()), new_brightness_64)); + writeToDevice(device.first, new_brightness); } } -- GitLab