Reputation: 3580
I'm trying to add meta-data to an ELF executable by storing strings in a special section (__dlog
). The current approach uses (abuses?) inline assembly to store the strings and nearly 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 a part of the string by taking advantage of the __func__
identifier. The end result should be the string
file.c:foo:int baz\0
in a section called __dlog
. But since __func__
is not a string literal, gcc complains with this code
".asciz \"" __FILE__ ":" __func__ ":" #proto "\"\n\t"
Is there anyway to get the contents of __func__
added to the string? Bonus points if the solution doesn't require custom build options or post-processing steps. Compiler is gcc 4.4 and 4.5.
Upvotes: 3
Views: 1455
Reputation: 12901
Edit: This seems to work, it doesn't give a completely un-mangled name, but the function name is there
#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
Original Answer:
In gcc-3.3 using c mode, __func__
is treated like a const char []
. If c++ mode, and in gcc > 3.3, __func__
is always a variable.
I guess you could use an older version of gcc, in c-mode, to accomplish this.
See the last paragraph on http://gcc.gnu.org/onlinedocs/gcc/Function-Names.html
Upvotes: 3