stm32使用jlink进行hardfault定位的方法
时间: 2024-05-08 12:20:09 浏览: 211
stm32-jlink.zip_JLINK STM32
您可以按照以下步骤使用J-Link进行STM32的HardFault定位:
1. 首先,在代码中添加HardFault异常处理函数,并通过操作寄存器将其地址存储在VTOR寄存器的第29位和第30位中。代码示例:
```c
void HardFault_Handler(void)
{
__asm volatile (
" tst lr, #4 \n"
" ite eq \n"
" mrseq r0, msp \n"
" mrsne r0, psp \n"
" ldr r1, [r0, #24] \n"
" ldr r2, handler2_address_const \n"
" bx r2 \n"
" handler2_address_const: .word HardFault_Handler2 \n"
);
}
void HardFault_Handler2(unsigned int * hardfault_args)
{
unsigned int stacked_r0;
unsigned int stacked_r1;
unsigned int stacked_r2;
unsigned int stacked_r3;
unsigned int stacked_r12;
unsigned int stacked_lr;
unsigned int stacked_pc;
unsigned int stacked_psr;
stacked_r0 = ((unsigned long) hardfault_args[0]);
stacked_r1 = ((unsigned long) hardfault_args[1]);
stacked_r2 = ((unsigned long) hardfault_args[2]);
stacked_r3 = ((unsigned long) hardfault_args[3]);
stacked_r12 = ((unsigned long) hardfault_args[4]);
stacked_lr = ((unsigned long) hardfault_args[5]);
stacked_pc = ((unsigned long) hardfault_args[6]);
stacked_psr = ((unsigned long) hardfault_args[7]);
printf ("[HardFault]\n");
printf ("- Stack frame:\n");
printf (" R0 = 0x%08x\n", stacked_r0);
printf (" R1 = 0x%08x\n", stacked_r1);
printf (" R2 = 0x%08x\n", stacked_r2);
printf (" R3 = 0x%08x\n", stacked_r3);
printf (" R12 = 0x%08x\n", stacked_r12);
printf (" LR [R14] = 0x%08x subroutine call return address\n", stacked_lr);
printf (" PC [R15] = 0x%08x program counter\n", stacked_pc);
printf (" PSR = 0x%08x\n", stacked_psr);
while (1);
}
```
2. 然后,打开J-Link GDB服务器,并连接到目标设备。代码示例:
```
$ JLinkGDBServer -device STM32F103ZE -if SWD
```
3. 通过GDB连接到J-Link服务器并加载程序文件。代码示例:
```
$ arm-none-eabi-gdb -ex "target remote localhost:2331" firmware.elf
```
4. 在GDB中设置读取HardFault异常原因的断点。代码示例:
```
(gdb) target remote localhost:2331
(gdb) break HardFault_Handler
(gdb) continue
```
5. 当程序触发HardFault异常时,程序将停止在HardFault异常处理函数中的断点处。您可以使用GDB检查寄存器的值,以及输出您在HardFault异常处理函数中添加的调试信息。代码示例:
```
[HardFault]
- Stack frame:
R0 = 0x00000000
R1 = 0x200048c4
R2 = 0x00000012
R3 = 0xffffffff
R12 = 0x00000000
LR [R14] = 0x080034b9 subroutine call return address
PC [R15] = 0x08002ccb program counter
PSR = 0x81000000
```
以上是使用J-Link进行STM32的HardFault定位的方法。希望能对您有所帮助。
阅读全文