How do you get the start and end addresses of a custom ELF section?

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 vmlinux.lds.[Sh] and this SO answer).

See here for another example of using custom ELF sections.

Leave a Comment