mgalgs mgalgs -3 years ago 196
C Question

How do you get the start and end addresses of a custom ELF section in C (gcc)?

I've seen the usage of of the gcc

attribute (especially in the Linux kernel) to collect data (usually function pointers) into custom ELF sections. How is the "stuff" that gets put in those custom sections retrieved and used?

Answer Source

As long as the section name results in a valid C variable name, gcc (ld, rather) generates two magic variables: __start_SECTION and __stop_SECTION. Those can be used to retrieve the start and end addresses of a section, like so:

 * Assuming you've tagged some stuff earlier with:
 * __attribute((__section__("my_custom_section")))

struct thing *iter = &__start_my_custom_section;

for ( ; iter < &__stop_my_custom_section; ++iter) {
    /* do something with *iter */

I couldn’t find any formal documentation for this feature, only a few obscure mailing list references. If you know where the docs are, drop a comment!

If you're using your own linker script (as the Linux kernel does) you'll have to add the magic variables yourself (see[Sh] and this SO answer).

See here for another example of using custom ELF sections.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download