Skip to content

Instantly share code, notes, and snippets.

@brimston3
Created February 21, 2018 14:25
Show Gist options
  • Save brimston3/f595c2a99bfd85cb29684559b45a7017 to your computer and use it in GitHub Desktop.
Save brimston3/f595c2a99bfd85cb29684559b45a7017 to your computer and use it in GitHub Desktop.
Embed program source code (or any binary) in the output ELF.
DEBUG=-ggdb
selfprint: selfprint.c.o selfprint.c
$(CC) -o $@ $(DEBUG) $^
selfprint.c.o: selfprint.c
objcopy -I binary -O elf64-x86-64 -B i386 $< $@
.PHONY: show
show: selfprint
nm -S -t x $<
.PHONY: clean
clean:
rm -f selfprint.c.o selfprint
// vim: ts=2 sw=2 et:
// call as ./selfprint -v
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#define ANSI_COLOR_GREEN "\x1b[32m"
#define ANSI_COLOR_RESET "\x1b[0m"
extern char _binary_selfprint_c_start[];
extern char _binary_selfprint_c_end[];
extern const void * _binary_selfprint_c_size;
#define BINARY_FILE_SIZE ((uintptr_t)&_binary_selfprint_c_size)
int main(int argc, char *argv[]) {
printf("%p\n", _binary_selfprint_c_start);
printf("size_addr: %p\n", &_binary_selfprint_c_size); // never produces correct result.
printf("size_sym: %lx\n", BINARY_FILE_SIZE); // also wrong.
printf("size_cal: %ld\n", &_binary_selfprint_c_end[0] - &_binary_selfprint_c_start[0]);
fflush(stdout);
if (argc >= 2 && !strcmp(argv[1], "-v")) {
fwrite("\n", 1, 1, stdout);
fwrite(ANSI_COLOR_GREEN, 1, strlen(ANSI_COLOR_GREEN), stdout);
fwrite(_binary_selfprint_c_start, 1, &_binary_selfprint_c_end[0] - &_binary_selfprint_c_start[0], stdout);
fwrite(ANSI_COLOR_RESET, 1, strlen(ANSI_COLOR_GREEN), stdout);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment