playground: add embedded resources example

This commit is contained in:
Jérôme Carretero 2014-04-24 00:53:36 -04:00
parent 14a8f03012
commit 955c09d037
3 changed files with 109 additions and 0 deletions

View File

@ -0,0 +1,18 @@
#include <stdio.h>
#include <stdint.h>
#include "x-resources.h"
int main()
{
EXTLD(main_c)
size_t length = LDLEN(main_c);
uint8_t const * data = LDVAR(main_c);
printf("Data at %p, len %lu\n", data, length);
printf("%s\n", data);
return 0;
}

View File

@ -0,0 +1,57 @@
#!/usr/bin/env python
#Demo on embedding resources in executables
"""
We embed the main.c source code in a section of the program.
See http://gareus.org/wiki/embedding_resources_in_executables
TODO: support for more toolchains
"""
from waflib import Task
from waflib.TaskGen import feature, before_method
def options(opt):
opt.load('compiler_c')
def configure(cfg):
cfg.load('compiler_c')
cfg.find_program('ld')
class resource_ldr(Task.Task):
def run(tsk):
dst = tsk.outputs[0]
src = tsk.inputs[0]
cmd = tsk.env.LD + [
'-r',
'-b', 'binary',
'-o', dst.abspath(),
src.name,
]
tsk.exec_command(cmd, cwd=src.parent.abspath())
@feature('resource_embed')
@before_method('process_source')
def ld_binary(self):
src = self.path.find_resource(self.source)
dst = src.change_ext('.o')
tsk = self.create_task('resource_ldr', src, dst)
try:
self.compiled_tasks.append(tsk)
except AttributeError:
self.compiled_tasks = [tsk]
self.source = []
def build(bld):
bld(
name='example',
source='main.c',
features='resource_embed',
)
bld(
target = 'app',
features = 'c cprogram',
source = 'main.c',
use='example',
)

View File

@ -0,0 +1,34 @@
#ifndef X_RESOURCES_H
#define X_RESOURCES_H
#ifdef __APPLE__
#include <mach-o/getsect.h>
#define EXTLD(NAME) \
extern const unsigned char _section$__DATA__ ## NAME [];
#define LDVAR(NAME) _section$__DATA__ ## NAME
#define LDLEN(NAME) (getsectbyname("__DATA", "__" #NAME)->size)
#elif (defined __WIN32__) /* mingw */
#define EXTLD(NAME) \
extern const unsigned char binary_ ## NAME ## _start[]; \
extern const unsigned char binary_ ## NAME ## _end[];
#define LDVAR(NAME) \
binary_ ## NAME ## _start
#define LDLEN(NAME) \
((binary_ ## NAME ## _end) - (binary_ ## NAME ## _start))
#else /* gnu/linux ld */
#define EXTLD(NAME) \
extern const unsigned char _binary_ ## NAME ## _start[]; \
extern const unsigned char _binary_ ## NAME ## _end[];
#define LDVAR(NAME) \
_binary_ ## NAME ## _start
#define LDLEN(NAME) \
((_binary_ ## NAME ## _end) - (_binary_ ## NAME ## _start))
#endif
#endif /* X_RESOURCES_H */