Skip to content

Instantly share code, notes, and snippets.

@pcercuei
Last active March 28, 2023 19:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pcercuei/61f81732b55993c4759cd887cc1a01ca to your computer and use it in GitHub Desktop.
Save pcercuei/61f81732b55993c4759cd887cc1a01ca to your computer and use it in GitHub Desktop.
Embed a binary blob into a C program with CMake
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
Copy link

3flares commented Mar 28, 2023

Would you mind showing an example of this is used and how to access the blob in your application?

@pcercuei
Copy link
Author

@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.

@3flares
Copy link

3flares commented Mar 28, 2023

@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