Skip to content

Instantly share code, notes, and snippets.

@mgalgs
Last active April 11, 2018 17:09
Show Gist options
  • Save mgalgs/5537133 to your computer and use it in GitHub Desktop.
Save mgalgs/5537133 to your computer and use it in GitHub Desktop.
ELF section hacking!
all: section_hacking
section_hacking:
gcc -g -O0 -Werror -Wall -o section_hacking section_hacking.c plugin.c
clean:
rm -f *.o section_hacking
Formatters are sitting from 0x0x601020 to 0x0x601060
Formatting with in_quotes: "My Formatted Text"
Formatting with in_equotes: `My Formatted Text'
Formatting with in_arrows: hi-->>>My Formatted Text<<<---
Formatting with in_pizza: :pizza:My Formatted Text:pizza:
#include <stdio.h>
#include "section_hacking.h"
static void in_equotes(const char *txt)
{
printf("`%s'\n", txt);
}
REGISTER_FORMATTER(in_equotes);
static void in_arrows(const char *txt)
{
printf("-->>>%s<<<---\n", txt);
}
REGISTER_FORMATTER(in_arrows);
static void in_pizza(const char *txt)
{
printf(":pizza:%s:pizza:\n", txt);
}
REGISTER_FORMATTER(in_pizza);
#include <stdio.h>
#include "section_hacking.h"
static void in_quotes(const char *txt)
{
printf("\"%s\"\n", txt);
}
REGISTER_FORMATTER(in_quotes);
extern struct formatter_info __start_my_formatters;
extern struct formatter_info __stop_my_formatters;
static void format_all(const char *txt)
{
struct formatter_info *iter = &__start_my_formatters;
for ( ; iter < &__stop_my_formatters; ++iter) {
printf("Formatting with %s: ", iter->name);
iter->fn(txt);
}
}
int main(int argc, char *argv[])
{
printf("Formatters are sitting from 0x%p to 0x%p\n",
(void *)&__start_my_formatters,
(void *)&__stop_my_formatters);
format_all("My Formatted Text");
return 0;
}
#ifndef __SECTION_HACKING_H__
#define __SECTION_HACKING_H__
typedef void (*formatter_fn_t)(const char *);
struct formatter_info {
formatter_fn_t fn;
char *name;
};
#define REGISTER_FORMATTER(func) \
static struct formatter_info __formatter_ ## func \
__attribute((__section__("my_formatters"))) \
__attribute((__used__)) = { \
.fn = func, \
.name = #func, \
}
#endif /* __SECTION_HACKING_H__ */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment