Created
May 22, 2015 00:31
-
-
Save carlos-jenkins/8a06d2fa804e8d4d51c2 to your computer and use it in GitHub Desktop.
C magic to put, and then iterate, some symbols in an ELF custom section.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
// | |
// Define a thing to store in sections | |
// | |
struct mything { | |
const char* name; | |
int num; | |
}; | |
// | |
// Define several things to store in section "mysection" | |
// | |
static struct mything thing1 __attribute__((section("mysection"))) __attribute__((used)) = { | |
.name = "thing1", | |
.num = 1 | |
}; | |
static struct mything thing2 __attribute__((section("mysection"))) __attribute__((used)) = { | |
.name = "thing2", | |
.num = 2 | |
}; | |
static struct mything thing3 __attribute__((section("mysection"))) __attribute__((used)) = { | |
.name = "thing3", | |
.num = 3 | |
}; | |
static struct mything thing4 __attribute__((section("mysection"))) __attribute__((used)) = { | |
.name = "thing4", | |
.num = 4 | |
}; | |
static struct mything thing5 __attribute__((section("mysection"))) __attribute__((used)) = { | |
.name = "thing5", | |
.num = 5 | |
}; | |
// | |
// Reference section end and start | |
// This variables are magically created by the linker | |
// | |
extern struct mything __start_mysection; | |
extern struct mything __stop_mysection; | |
// | |
// Print all things | |
// | |
int main() { | |
// Iterate over the section | |
for(struct mything* iter = &__start_mysection; iter < &__stop_mysection; ++iter) { | |
printf( | |
"Found thing \"%s\" with number %d.\n", | |
iter->name, iter->num | |
); | |
} | |
} | |
// Compile and execute me with: | |
// | |
// $ c99 custom_elf_section.c -o custom_elf_section | |
// $ ./custom_elf_section | |
// | |
// Found thing "thing1" with number 1. | |
// Found thing "thing2" with number 2. | |
// Found thing "thing3" with number 3. | |
// Found thing "thing4" with number 4. | |
// Found thing "thing5" with number 5. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment