How to use __func__ with built-in assembly

I am trying to add metadata to an ELF executable by storing lines in a special section ( __dlog). The current approach uses (abuses?) The built-in assembly to store strings and almost works as desired.

#include <stdio.h>
#include <stdlib.h>

#define DLOG(proto...) \
        __asm__(".pushsection __dlog, \"S\", @note\n\t" \
                ".asciz \"" __FILE__ ":function_name_here:" #proto "\"\n\t" \
                ".popsection\n\t" )

int
foo(int bar)
{
    int baz = bar / 2;
    DLOG(int baz);
    return baz;
}

int
main(int argc, char *argv[])
{
    foo(argc);
    return EXIT_SUCCESS;
}

But ideally, the macro should automatically include the function name as part of the string using the identifier __func__. The end result should be a string

file.c:foo:int baz\0

in a section called __dlog. But since __func__it is not a string literal, gcc complains about this code

".asciz \"" __FILE__ ":" __func__ ":" #proto "\"\n\t"

Is it possible to add the contents of a string __func__to a string? Bonus points if the solution does not require custom assembly options or post-processing steps. The compiler is gcc 4.4 and 4.5.

+3
1

: , , ,

#define DLOG( proto...) \
__asm__(".pushsection __dlog, \"S\", @note\n\t" \
                ".asciz \"" __FILE__ ":%0:" #proto "\"\n\t" \
                ".popsection\n\t"  \
 : \
 :  "s" ( __func__ ) )


int main(int argc, char*argv[]) {
DLOG(int argc, char*argv[]);

return 0;
}

extern "C" void test(int bar) {
DLOG(bar);
}

g++ - 4.4 test.cpp && & xxd a.out | less -p test.cpp

0001020: 7465 7374 2e63 7070 3a24 5f5a 5a34 6d61  test.cpp:$_ZZ4ma
0001030: 696e 4538 5f5f 6675 6e63 5f5f 3a69 6e74  inE8__func__:int
0001040: 2061 7267 632c 2063 6861 722a 6172 6776   argc, char*argv
0001050: 5b5d 0074 6573 742e 6370 703a 245f 5a5a  [].test.cpp:$_ZZ
0001060: 3474 6573 7445 385f 5f66 756e 635f 5f3a  4testE8__func__:
0001070: 6261 7200 4743 433a 2028 5562 756e 7475  bar.GCC: (Ubuntu

:

gcc-3.3 c mode __func__ a const char []. ++, gcc > 3.3, __func__ .

, gcc c-mode, .

http://gcc.gnu.org/onlinedocs/gcc/Function-Names.html

+3

Source: https://habr.com/ru/post/1789637/


All Articles