blackmagic-debug / blackmagic

In application debugger for ARM Cortex microcontrollers.
GNU General Public License v3.0
3.22k stars 767 forks source link

Fix: `target_list_free()` exception handling #1851

Closed dragonmux closed 2 months ago

dragonmux commented 3 months ago

Detailed description

In this PR we address the lack of exception handling in target_list_free() which results in some very funky behaviour including crashes from double-free() and some other badness.

In the advent that the function is called and thinks it needs to detach from a target, but that target has gone away, target->detach() will throw. If left unhandled in this function, the target_list state becomes invalid/stale and in an unpredictable state, leading to all the bad things that happen. So, we envelop this section of the function in a TRY()-CATCH() so we can discard the exception and continue clean-up, giving a consistent and valid final state on the function returning.

Tested working on the STM32H503.

Test protocol is to scan and attach, then either disconnect the debug umbilical, or cut power to the target, and try to detach/kill. If running BMDA, a message such as

Exception caught while detaching from target: Remote protocol exception
TARGET LOST.

should be seen, but everything otherwise remains up and working.

Your checklist for this pull request

Closing issues