Skip to content

Instantly share code, notes, and snippets.

@Atari2
Created June 11, 2022 21:35
Show Gist options
  • Save Atari2/7ab5011da0d6b4568a864d995ed3791a to your computer and use it in GitHub Desktop.
Save Atari2/7ab5011da0d6b4568a864d995ed3791a to your computer and use it in GitHub Desktop.
Include binary blobs inside your C++ executable. (works on GCC)
#include "IncBinTest.h"
#include <cstdio>
// imagine that somewhere in your directory there's a file called test.bin
// this will a create test_data() function that returns an instance of incbin_data.
DEF_INCBIN(test, ".bin")
int main()
{
auto ptr = test_data();
printf("%p %d\n", ptr.ptr, ptr.size);
for (size_t i = 0; i < ptr.size; i++) {
printf("%02X ", ptr.ptr[i]);
}
printf("\n");
return 0;
}
#pragma once
#include <cstddef>
#include <cstdint>
struct incbin_data {
const uint8_t* ptr;
const size_t size;
};
#define DEF_INCBIN(filename, ext) \
incbin_data filename##_data() { \
static volatile uintptr_t ptr = 0; \
static volatile size_t sz = 0; \
if (ptr == 0 && sz == 0) { \
__asm__ volatile("jmp ." #filename "_data_end\n" \
"." #filename "_data_begin:\n" \
" .incbin \"" #filename ext "\"\n" \
"." #filename "_data_end:\n" \
"lea ." #filename "_data_begin(%%rip), %0\n" \
"mov $." #filename "_data_end-." #filename "_data_begin, %1" \
: "=r"(ptr), "=r"(sz) \
: \
: "memory"); \
} \
return { reinterpret_cast<uint8_t*>(ptr), sz }; \
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment