Skip to content

Commit 9b187ab

Browse files
committed
drivers: adc: mcux_adc16: Fix buffer size check for multi-channel reads
The mcux_adc16 driver's read function fails to validate the user-provided buffer size when `adc_sequence.options` are used (extra samplings). The calculation erroneously considered only the size required for one channel, neglecting the total number of channels in the sequence. This leads to a **buffer overflow** when reading multiple channels. Fix this by using `POPCOUNT(sequence->channels)` to determine the correct channel count and ensure the buffer size is sufficient. Signed-off-by: Your Name <[email protected]>
1 parent 3af17bf commit 9b187ab

File tree

1 file changed

+20
-3
lines changed

1 file changed

+20
-3
lines changed

drivers/adc/adc_mcux_adc16.c

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,8 @@ static int start_read(const struct device *dev,
192192
uint32_t tmp32;
193193
ADC_Type *base = config->base;
194194

195+
uint32_t channels_count = POPCOUNT(sequence->channels);
196+
195197
switch (sequence->resolution) {
196198
case 8:
197199
case 9:
@@ -247,10 +249,25 @@ static int start_read(const struct device *dev,
247249
return -EINVAL;
248250
}
249251

252+
size_t min_buffer_size = channels_count * sizeof(uint16_t);
253+
254+
if (channels_count == 0) {
255+
LOG_ERR("No channels selected");
256+
return -EINVAL;
257+
}
258+
259+
if (sequence->buffer_size < min_buffer_size) {
260+
LOG_ERR("sequence buffer size too small %d < %d",
261+
sequence->buffer_size, min_buffer_size);
262+
return -EINVAL;
263+
}
264+
250265
if (sequence->options) {
251-
if (sequence->buffer_size <
252-
2 * (sequence->options->extra_samplings + 1)) {
253-
LOG_ERR("sequence buffer size too small < 2 * extra + 2");
266+
min_buffer_size = channels_count * sizeof(uint16_t) *
267+
(sequence->options->extra_samplings + 1);
268+
if (sequence->buffer_size < min_buffer_size) {
269+
LOG_ERR("sequence buffer size too small for samplings: %d < %d",
270+
sequence->buffer_size, min_buffer_size);
254271
return -EINVAL;
255272
}
256273
}

0 commit comments

Comments
 (0)