Timer1 remap cause debug crash on STM32F103
STM32F103 [...] STM32CubeMx [...] when I start the debug session and when the MCU executes the macro "__HAL_AFIO_REMAP_TIM1_ENABLE()" the debug session crash.


I don't use the STM32CubeMX HAL, but I can explain the issue and the workaround.

The problem is that the STM32F1 series has one register AFIO_MAPR which contains the settings for remapping various peripherals and for enabling/disabling the JTAG/SWD connection to your debugger. And to make this more complicated, the bits in that register which enable/disable the JTAG/SWD settings (bits 24-26) are write-only so their existing state cannot be read.

See this extract from the STM32F1 Reference Manual:






This means that any attempt to change the settings of the various "peripheral remap" bits, by doing a read-modify-write sequence to this register, could read different values instead of the real current values in the JTAG/SWD bits. Then, when the write to the register is done, your debugger access stops because whatever was read from those JTAG/SWD bits, is written back to them. (Other effects have also been reported, but I won't go into that now).

From what I could find without installing the HAL, the macros used are:

#define __HAL_AFIO_REMAP_TIM1_ENABLE()
    MODIFY_REG(AFIO-&gt;MAPR, AFIO_MAPR_TIM1_REMAP, AFIO_MAPR_TIM1_REMAP_FULLREMAP)

and MODIFY_REG is:

#define MODIFY_REG(REG, CLEARMASK, SETMASK)
    WRITE_REG((REG), (((READ_REG(REG)) &amp; (~(CLEARMASK))) | (SETMASK)))

So as you see, MODIFY_REG is doing a read-modify-write and you don't know what values it will read from JTAG/SWD bits 24-26 and hence what values it will write back to there! The values read from those bits are "undefined" (to quote ST) and I know I have read different values from the same STM32F1 at different times.

The "fix" I have used with the SPL, is to change any remapping code to specifically set the JTAG/SWD bits which you want, whenever you write to the AFIO_MAPR register. You will need to figure out how you want to do the same with the HAL code. One way is to use a temporary variable so, from memory, the sequence becomes:


Read AFIO_MAPR register into temp variable
Change desired peripheral remap bits in the temp variable
Mask out bits 24-26 in the temp variable
Set bits 24-26 in the temp variable to whatever I wanted (therefore ignoring whatever their, likely incorrect, "read" value was)
Write temp variable to AFIO_MAPR


Thankfully ST changed to a better register arrangement in later STM32 models (e.g. STM32F4).