Skip to content

Pseudo-random behavior of GCC start-up template when main() returns #15

@0xa000

Description

@0xa000

Board: NUCLEO-H723ZG
Compiler: arm-none-eabi-gcc (Arch Repository) 14.1.0

The GCC start-up assembly template for the H723xx (see here) contains the following code at the end of Reset_Handler:

/* Call static constructors */
  bl __libc_init_array
/* Call the application's entry point.*/
  bl  main
  bx  lr

Usually, main is assumed not to return. However, if it does, the next instruction BX LR will jump to the address stored in the link register. This address will usually be the return address for the last sub-routine call inside main. So, this instruction will jump back into main to a more or less random location. In my particular case, this location was close to the end of main, and execution continued through to the end of main where it pop-ed a value of zero into the program counter. This then triggered a hard fault, because zero is not a thumb mode address, and the default hard fault handler (an infinite loop) was entered.

Of course, one can debate about the desired behavior if main returns, but I think we can agree the current behavior is not it. One approach would be to replace BX LR with an infinite loop, similar to the GCC start-up templates for the H5 series. See for example this snippet below (taken from here):

/* Call static constructors */
  bl __libc_init_array
/* Call the application's entry point.*/
  bl main

LoopForever:
    b LoopForever

One could also consider throwing in a call to __libc_fini_array() after main and before the infinite loop for symmetry.

Metadata

Metadata

Assignees

Labels

bugSomething isn't workingcmsisCMSIS-related issue or pull-request.good first issueGood for newcomersinternal bug trackerIssue confirmed and reported into a ticket in the internal bug tracking system.

Type

Projects

Status

In progress

Relationships

None yet

Development

No branches or pull requests

Issue actions