cancel
Showing results for 
Search instead for 
Did you mean: 

How to ignore bkpt instruction on Cortex M7?

Pavel A.
Evangelist III

If I understand correctly, the BKPT instruction is "promoted" to hard fault when debugger is not connected.

Is it possible to tweak STM32H7 so that BKPT will be silently ignored?

-- pa

1 ACCEPTED SOLUTION

Accepted Solutions
berendi
Principal

Enable the DebugMon exception

CoreDebug->DEMCR |= CoreDebug_DEMCR_MON_EN_Msk;

then it will be called instead of the hardfault handler. Unfortunately, it would return to the same BKPT instruction which would trigger the exception again and again, so you have to bump the exception return address on the stack past the BKPT. Assembly only, because we are messing with the stack frame.

__attribute__((naked))
void DebugMon_Handler(void) {
	asm volatile(
			"ldr r0, [sp, #24]\n\t" // PC is at offset 24 on the exception stack frame
			"add r0, #2\n\t"        // BKPT is encoded in 2 bytes
			"str r0, [sp, #24]\n\t"
			"bx lr\n\t"
			);
}

This works only when the exception handler is actually allowed to run, i.e. interrupts are not disabled, no other handler is running with priority 0 or whatever priority DebugMon_Handler actually has, which I could not find in the PM. But it definitely has one.

View solution in original post

3 REPLIES 3
berendi
Principal

Enable the DebugMon exception

CoreDebug->DEMCR |= CoreDebug_DEMCR_MON_EN_Msk;

then it will be called instead of the hardfault handler. Unfortunately, it would return to the same BKPT instruction which would trigger the exception again and again, so you have to bump the exception return address on the stack past the BKPT. Assembly only, because we are messing with the stack frame.

__attribute__((naked))
void DebugMon_Handler(void) {
	asm volatile(
			"ldr r0, [sp, #24]\n\t" // PC is at offset 24 on the exception stack frame
			"add r0, #2\n\t"        // BKPT is encoded in 2 bytes
			"str r0, [sp, #24]\n\t"
			"bx lr\n\t"
			);
}

This works only when the exception handler is actually allowed to run, i.e. interrupts are not disabled, no other handler is running with priority 0 or whatever priority DebugMon_Handler actually has, which I could not find in the PM. But it definitely has one.

Pavel A.
Evangelist III

Thank you a lot!

-- pa

mbrossett
Associate III

I know this is an old thread but for anyone still looking for how to detect if the debugger is attached, you can check the C_DEBUGEN bit of the DHCSR register. Below is a link to the ARM documentation.

 

https://developer.arm.com/documentation/ddi0403/d/Debug-Architecture/ARMv7-M-Debug/Debug-register-support-in-the-SCS/Debug-Halting-Control-and-Status-Register--DHCSR?lang=en

 

if (CoreDebug->DHCSR & 1) // check if debugger is connected
{			
	__BKPT(0); // halt program execution here with a breakpoint
}