Readout elf endianess and print error on mismatch

This commit is contained in:
Mario Hüttel 2022-12-17 19:33:13 +01:00
parent 320b0ce650
commit e56040438b
3 changed files with 27 additions and 5 deletions

View File

@ -41,7 +41,7 @@ enum crc_format {
FORMAT_STRUCT,
};
elfpatch_handle_t *elf_patch_open(const char *path, bool readonly);
elfpatch_handle_t *elf_patch_open(const char *path, bool readonly, bool expect_little_endian);
/**
* @brief Check if a section is present in file

View File

@ -293,9 +293,10 @@ static int elf_patch_update_info(elfpatch_handle_t *ep)
return 0;
}
elfpatch_handle_t *elf_patch_open(const char *path, bool readonly)
elfpatch_handle_t *elf_patch_open(const char *path, bool readonly, bool expect_little_endian)
{
struct elfpatch *ep;
const char *ident;
/* This is important to guarantee structure packing behavior */
CRC_OUT_CHECK_STRUCT_SIZES;
@ -320,7 +321,7 @@ elfpatch_handle_t *elf_patch_open(const char *path, bool readonly)
goto close_fd;
}
/* Prewvent Libelf from relayouting the sections, which would brick the load segments */
/* Prevent Libelf from relayouting the sections, which would brick the load segments */
elf_flagelf(ep->elf, ELF_C_SET, ELF_F_LAYOUT);
if (elf_patch_update_info(ep)) {
@ -328,6 +329,27 @@ elfpatch_handle_t *elf_patch_open(const char *path, bool readonly)
goto close_elf;
}
ident = elf_getident(ep->elf, NULL);
if (ident) {
switch (ident[5]) {
case 1:
print_debug("ELF Endianess: little\n");
if (!expect_little_endian) {
print_err("Big endian format expected. File is little endian. Double check settings!\n");
}
break;
case 2:
print_debug("ELF Endianess: big\n");
if (expect_little_endian) {
print_err("Little endian format expected. File is big endian. Double check settings!\n");
}
break;
default:
print_err("Cannot determine endianess of ELF file. EI_DATA is: %d\n", ident[5]);
break;
}
}
return (elfpatch_handle_t *)ep;
close_elf:
if (ep->elf) {
@ -634,7 +656,7 @@ int elf_patch_write_crcs_to_section(elfpatch_handle_t *ep, const char *section,
}
/* Flag section data as invalid to trigger rewrite.
* This is needed to to the forced memory layout
* This is needed due to the forced memory layout
*/
elf_flagdata(output_sec_data, ELF_C_SET, ELF_F_DIRTY);
ret = 0;

View File

@ -398,7 +398,7 @@ int main(int argc, char **argv)
elf_version(EV_CURRENT);
/* Open the ELF file */
ep = elf_patch_open(cmd_opts.elf_path, cmd_opts.dry_run);
ep = elf_patch_open(cmd_opts.elf_path, cmd_opts.dry_run, cmd_opts.little_endian);
if (!ep) {
ret = -2;
goto free_cmds;