1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
From dd74cdbdd3849fbd86e6613ef7ecab6c7857cb89 Mon Sep 17 00:00:00 2001
From: ivan tkachenko <me@ratijas.tk>
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 <KLocalizedString>
#include <algorithm>
+#include <climits>
#include <sys/utsname.h>
#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<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);
}
}
--
GitLab
|