본문 바로가기
Embedded

[C] Get return address of functions (__builtin_return_address)

by llHoYall 2021. 3. 2.

Let's get the return address of a function with __builtin_return_address.

Syntax

void* __builtin_return_address(unsigned int level);

 

level

  • 0 : Return the address of the current function
  • 1 : Return the address of the caller of the current function
  • 2 ~ 63 : Return the address of the caller's caller, and so forth

If the top of the call stack has been reached, the function will return 0.

It is usually safe to only use the value 0 for level.

Usage

This is an example code.

#include <stdio.h>

void funcC(void)
{
    printf("In Func C: %p\n", __builtin_return_address(0));
}

void funcB(void)
{
    printf("In Func B: %p\n", __builtin_return_address(0));

    funcC();
}

void funcA(void)
{
    printf("In Func A: %p\n", __builtin_return_address(0));

    funcB();
}

int main(int argc, char *agrv[])
{
    printf("Func A: %p\n", funcA);
    printf("Func B: %p\n", funcB);
    printf("Func C: %p\n", funcC);

    funcA();

    return 0;
}

The result of this code on my system is below (macOS Big Sur v11.2.1).

To validate the result try disassembly our application.

$ otool -tV <output binary name>

Look at the yellow box, it looks like the function's start address.

And the blue box is the important point.

It represents where to return the function.

 

In other words, this code will return the same return address.

void funcC(void)
{
    printf("In Func C: %p\n", __builtin_return_address(2));
}

void funcB(void)
{
    printf("In Func B: %p\n", __builtin_return_address(1));

    funcC();
}

void funcA(void)
{
    printf("In Func A: %p\n", __builtin_return_address(0));

    funcB();
}

It works well as my thought.

'Embedded' 카테고리의 다른 글

[Embedded] Unittest using GoogleTest on CMake  (0) 2021.10.13
[Embedded] Build using CMake  (0) 2021.10.13
[C] Preprocessors - #if, #ifdef, #if defined  (0) 2021.06.11

댓글