Search code examples
cc11noreturn

How to use noreturn with function pointer?


I am writing a bootloader in C11. When the bootloader needs to transfer the control to the firmware, it reads a function pointer at a predefined memory address and calls it. The code looks like this:

typedef void (FirmwareBootFn)(void);

typedef struct
{
    uint32_t stackPointer;
    FirmwareBootFn* programCounter;
}
FirmwareBootControl;

static FirmwareBootControl g_bootControl __attribute__ ((section (".boot_control")));

void
Firmware_boot( void )
{
    setStackPointer( g_bootControl.stackPointer );
    g_bootControl.programCounter();
}

Function Firmware_boot() never returns, so it made sense to declare it as noreturn:

#include <stdnoreturn.h>

noreturn void
Firmware_boot( void );

But I need to declare FirmwareBootFn as noreturn as well to avoid the compiler complaining that Firmware_boot() may return.

I tried (possibly) every permutation of the noreturn in the typedef without any result. Also I understood that the attribute can't be set in the typedef because it is not part of the type.

Is there a way to tag my Firmware_boot() as noreturn avoiding the warning (well without cheating with warning suppression :-))?


Solution

  • _Noreturn in C11 can only be applied to function definitions or declarations. The fact that the function doesn't return is not part of the prototype, unfortunately.

    Since you seem to have gcc you could use an extension

    typedef struct
    {
        uint32_t stackPointer;
        __attribute__((__noreturn__)) FirmwareBootFn* programCounter;
    }
    FirmwareBootControl;
    

    to mark the function pointer as not returning. Unfortunately though, there doesn't seem to be a way to ensure that the function that you assign to that really has that property by syntax, allone.