blackmagic-debug / blackmagic

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

Why add pc by 2 in cortexm_pc_write #825

Closed mttbx closed 3 years ago

mttbx commented 3 years ago

I noticed that there's cortexm_pc_write in cortexm_halt_resume function. And 0xBE00 is a bkpt instruction. Why should we add pc by 2?

stoyan-shopov commented 3 years ago

This just skips breakpoint instructions (2 bytes long) when resuming the target. There is no point in resuming the target if you know that you have hit a breakpoint, as you will hit the breakpoint again and again. Adding 2 to the PC skips the breakpoint instruction, and only then resumes the target. I believe such instructions are explicitly used with semihosting.

mttbx commented 3 years ago

Yes, I think so too, but is there any doc tells us that we need to add pc by two?

stoyan-shopov commented 3 years ago

The ARM documents, and reading the source code, I don't think there is anything better than this

mttbx commented 3 years ago

Can you be more specific? Just a reference would be good enough.

stoyan-shopov commented 3 years ago

You can refer to the ARM architecture reference manual for ARMv7M devices, document ddi0403, from ARM: https://developer.arm.com/documentation/ddi0403/latest

But, in short, when you resume a target, and there is a breakpoint on the address where the target will continue running - the target will immediately stop again on this address. If you do not skip this instruction, by adding 2 (bytes), which is the length of the BKPT instruction - your program will get stuck hitting the same breakpoint over and over again, and will never advance. As I said, I believe this use case is with semihosting, but I have no experience with semihosting, so cannot be 100 % sure. At least this is my understanding

mttbx commented 3 years ago

Thank you for your help and explain! I'll check it out.