Commit dd74cdbd authored by ivan tkachenko's avatar ivan tkachenko
Browse files

upower: Prevent integer overflow during new brightness computation

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 2ebe655d)
parent c1e29ec8
Pipeline #192052 passed with stage
in 1 minute and 21 seconds
...@@ -27,6 +27,7 @@ ...@@ -27,6 +27,7 @@
#include <KLocalizedString> #include <KLocalizedString>
#include <algorithm> #include <algorithm>
#include <climits>
#include <sys/utsname.h> #include <sys/utsname.h>
#ifdef Q_OS_FREEBSD #ifdef Q_OS_FREEBSD
...@@ -318,11 +319,13 @@ bool BacklightHelper::writeBrightness(int brightness) const ...@@ -318,11 +319,13 @@ bool BacklightHelper::writeBrightness(int brightness) const
#else #else
if (!m_devices.isEmpty()) { if (!m_devices.isEmpty()) {
int first_maxbrightness = m_devices.constFirst().second; const int first_maxbrightness = std::max(1, m_devices.constFirst().second);
if (first_maxbrightness <= 0)
first_maxbrightness = 1;
for (const auto &device : m_devices) { 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<qint64>(brightness) * static_cast<qint64>(device.second) / static_cast<qint64>(first_maxbrightness);
// cautiously truncate it back
const int new_brightness = static_cast<int>(std::min(static_cast<qint64>(std::numeric_limits<int>::max()), new_brightness_64));
writeToDevice(device.first, new_brightness);
} }
} }
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment