Last active
March 28, 2023 19:14
-
-
Save pcercuei/61f81732b55993c4759cd887cc1a01ca to your computer and use it in GitHub Desktop.
Embed a binary blob into a C program with CMake
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
set(EMBEDDED_FILE "" CACHE PATH "Path to the file to embed (optional)") | |
if (EMBEDDED_FILE) | |
file(SIZE ${EMBEDDED_FILE} EMBEDDED_FILE_SIZE) | |
file(GENERATE OUTPUT ${CMAKE_BINARY_DIR}/empty.c CONTENT "") | |
set_source_files_properties(${CMAKE_BINARY_DIR}/empty.c PROPERTIES GENERATED TRUE) | |
add_library(empty OBJECT ${CMAKE_BINARY_DIR}/empty.c) | |
add_custom_command(OUTPUT payload.o | |
WORKING_DIRECTORY ${CMAKE_BINARY_DIR} | |
COMMAND ${CMAKE_OBJCOPY} | |
--add-section=.image=${EMBEDDED_FILE} | |
--set-section-flags=.image=contents,alloc,load,readonly,data | |
--add-symbol=__start_image=.image:0 | |
--add-symbol=__end_image=.image:${EMBEDDED_FILE_SIZE} | |
$<TARGET_OBJECTS:empty> payload.o | |
DEPENDS empty | |
) | |
set_source_files_properties(payload.o PROPERTIES GENERATED TRUE) | |
target_sources(${PROJECT_NAME} PRIVATE payload.o) | |
endif () |
@3flares https://github.com/OpenDingux/odbootd/blob/master/odboot-client.c#L459-L461
(void *) &__start_image
will get you a pointer to the blob. (void *) &__end_image
will point to the end, and by doing some pointer arithmetic you can get the blob size.
@pcercuei That's great! Thanks for the quick response.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Would you mind showing an example of this is used and how to access the blob in your application?