From f79d8d7f1ed5d1f25102a90f63740b6bdbe6f469 Mon Sep 17 00:00:00 2001 From: Karol Trzcinski Date: Fri, 27 Mar 2020 11:00:29 +0100 Subject: [PATCH] elf: Add function to read section content with allocation In many functions there is need to read user section content and check firmware version or write section content to some manifest or dictionary. Previously to do it, in each function was loop to search for proper section in proper module, then allocate buffer, read content and check for possible error between each step what is quite overwhelming. After change there will be one function responsible for this task. Signed-off-by: Karol Trzcinski --- src/elf.c | 46 +++++++++++++++++++++++++++++++++++++ src/include/rimage/rimage.h | 2 ++ 2 files changed, 48 insertions(+) diff --git a/src/elf.c b/src/elf.c index dc6fd4d9c..663b2e087 100644 --- a/src/elf.c +++ b/src/elf.c @@ -516,6 +516,52 @@ out: return ret; } +int elf_read_section(const struct image *image, const char *section_name, + const Elf32_Shdr **dst_section, void **dst_buff) +{ + const struct module *module; + const Elf32_Shdr *section; + int section_index = -1; + int read; + int i; + + /* when there is more than one module, then first one is bootloader */ + for (i = image->num_modules == 1 ? 0 : 1; i < image->num_modules; i++) { + module = &image->module[i]; + section_index = elf_find_section(module, section_name); + if (section_index >= 0) + break; + } + + if (section_index < 0) { + fprintf(stderr, "error: section %s can't be found\n", + section_name); + return -EINVAL; + } + + section = &module->section[section_index]; + if (dst_section) + *dst_section = section; + + /* alloc buffer for section content */ + *dst_buff = calloc(1, section->size); + if (!*dst_buff) + return -ENOMEM; + + /* fill buffer with section content */ + fseek(module->fd, section->off, SEEK_SET); + read = fread(*dst_buff, 1, section->size, module->fd); + if (read != section->size) { + fprintf(stderr, + "error: can't read %s section %d\n", section_name, + -errno); + free(*dst_buff); + return -errno; + } + + return section->size; +} + int elf_parse_module(struct image *image, int module_index, const char *name) { struct module *module; diff --git a/src/include/rimage/rimage.h b/src/include/rimage/rimage.h index e129d52de..68c14c591 100644 --- a/src/include/rimage/rimage.h +++ b/src/include/rimage/rimage.h @@ -177,6 +177,8 @@ void elf_free_module(struct image *image, int module_index); int elf_is_rom(struct image *image, Elf32_Shdr *section); int elf_validate_modules(struct image *image); int elf_find_section(const struct module *module, const char *name); +int elf_read_section(const struct image *image, const char *name, + const Elf32_Shdr **dst_section, void **dst_buff); int elf_validate_section(struct image *image, struct module *module, Elf32_Shdr *section, int index);