From 96963d8574956e6fc02e56666ecdbc215dbfdf84 Mon Sep 17 00:00:00 2001 From: Martino Facchin Date: Fri, 4 Aug 2023 15:53:05 +0200 Subject: [PATCH] analogReference: fix heap corruption on startup, analogReference() is being called to read the real value of 5V voltage so there's a way to retrieve the real voltage via analogRead(). However, calling R_ADC_Close when the ADC is not yet open triggers a chain of events that ends up at __STATIC_INLINE void R_FSP_IsrContextSet (IRQn_Type const irq, void * p_context) { gp_renesas_isr_context[irq] = p_context; } If the irq is not initialized, setting gp_renesas_isr_context[somethig] will overwrite random memory. Fixes https://github.com/arduino/ArduinoCore-renesas/issues/76 --- cores/arduino/analog.cpp | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/cores/arduino/analog.cpp b/cores/arduino/analog.cpp index 16283ae81..cd61c281f 100644 --- a/cores/arduino/analog.cpp +++ b/cores/arduino/analog.cpp @@ -545,11 +545,15 @@ void analogReference(uint8_t mode) { ctrl = ADC_VREF_CONTROL_AVCC0_AVSS0; break; } - R_ADC_Close(&adc.ctrl); + if(adc.ctrl.opened) { + R_ADC_Close(&adc.ctrl); + } adc.cfg_extend.adc_vref_control = ctrl; R_ADC_Open(&adc.ctrl, &adc.cfg); - R_ADC_Close(&adc1.ctrl); + if(adc1.ctrl.opened) { + R_ADC_Close(&adc1.ctrl); + } adc1.cfg_extend.adc_vref_control = ctrl; R_ADC_Open(&adc1.ctrl, &adc1.cfg); } @@ -638,13 +642,17 @@ void analogReadResolution(int bits) { break; } - R_ADC_Close(&adc.ctrl); + if(adc.ctrl.opened) { + R_ADC_Close(&adc.ctrl); + } auto res = R_ADC_Open(&adc.ctrl, &adc.cfg); if (res != FSP_SUCCESS) { adc.cfg.resolution = old_read_resolution; } - R_ADC_Close(&adc1.ctrl); + if(adc1.ctrl.opened) { + R_ADC_Close(&adc1.ctrl); + } res = R_ADC_Open(&adc1.ctrl, &adc1.cfg); if (res != FSP_SUCCESS) { adc1.cfg.resolution = old1_read_resolution;