diff --git a/common_modules/module_manager/utilities/module_converter_elf32.h b/common_modules/module_manager/utilities/module_converter_elf32.h new file mode 100644 index 000000000..af82bcc75 --- /dev/null +++ b/common_modules/module_manager/utilities/module_converter_elf32.h @@ -0,0 +1,185 @@ +/*************************************************************************** + * Copyright (c) 2026 Eclipse ThreadX contributors + * + * This program and the accompanying materials are made available under the + * terms of the MIT License which is available at + * https://opensource.org/licenses/MIT. + * + * AI Disclosure: This file was largely AI-generated by OpenAI Codex (GPT-6). + * The AI-generated portions may be considered public domain (CC0-1.0) + * and not subject to the project's licence. The human contributor must + * review and verify the code before submission. + * + * SPDX-License-Identifier: MIT and CC0-1.0 + ***************************************************************************/ + +#ifndef MODULE_CONVERTER_ELF32_H +#define MODULE_CONVERTER_ELF32_H + +#include +#include + +/* ELF32 field layouts and little-endian byte decoding. */ +#define MODULE_ELF32_IDENT_SIZE 16UL +#define MODULE_ELF32_HEADER_SIZE 52UL +#define MODULE_ELF32_PROGRAM_HEADER_SIZE 32UL +#define MODULE_ELF32_SECTION_HEADER_SIZE 40UL +#define MODULE_ELF32_SYMBOL_TABLE_ENTRY_SIZE 16UL + +/* These structures hold host-side values after decoding. They are never used + as overlays for bytes from the file. */ +typedef struct ELF_HEADER_STRUCT +{ + uint8_t elf_header_id_string[MODULE_ELF32_IDENT_SIZE]; + uint16_t elf_header_file_type; + uint16_t elf_header_machinge_type; + uint32_t elf_header_version; + uint32_t elf_header_entry_address; + uint32_t elf_header_program_header_offset; + uint32_t elf_header_section_header_offset; + uint32_t elf_header_processor_flags; + uint16_t elf_header_size; + uint16_t elf_header_program_header_size; + uint16_t elf_header_program_header_entries; + uint16_t elf_header_section_header_size; + uint16_t elf_header_section_header_entries; + uint16_t elf_header_section_string_index; +} ELF_HEADER; + + +typedef struct ELF_PROGRAM_HEADER_STRUCT +{ + uint32_t elf_program_header_type; + uint32_t elf_program_header_offset; + uint32_t elf_program_header_virtual_address; + uint32_t elf_program_header_physical_address; + uint32_t elf_program_header_file_size; + uint32_t elf_program_header_memory_size; + uint32_t elf_program_header_flags; + uint32_t elf_program_header_alignment; +} ELF_PROGRAM_HEADER; + + +typedef struct ELF_SECTION_HEADER_STRUCT +{ + uint32_t elf_section_header_name; + uint32_t elf_section_header_type; + uint32_t elf_section_header_flags; + uint32_t elf_section_header_address; + uint32_t elf_section_header_offset; + uint32_t elf_section_header_size; + uint32_t elf_section_header_link; + uint32_t elf_section_header_info; + uint32_t elf_section_header_alignment; + uint32_t elf_section_header_entry_size; +} ELF_SECTION_HEADER; + + +typedef struct ELF_SYMBOL_TABLE_ENTRY_STRUCT +{ + uint32_t elf_symbol_table_entry_name; + uint32_t elf_symbol_table_entry_address; + uint32_t elf_symbol_table_entry_size; + uint8_t elf_symbol_table_entry_info; + uint8_t elf_symbol_table_entry_other; + uint16_t elf_symbol_table_entry_shndx; +} ELF_SYMBOL_TABLE_ENTRY; + +/* C99-compatible layout checks keep host-side values predictable. + A failure means a future edit changed a value structure away from the ELF32 + field sizes. */ +typedef char module_elf32_header_size_check[ + (sizeof(ELF_HEADER) == MODULE_ELF32_HEADER_SIZE) ? 1 : -1]; +typedef char module_elf32_program_header_size_check[ + (sizeof(ELF_PROGRAM_HEADER) == MODULE_ELF32_PROGRAM_HEADER_SIZE) ? 1 : -1]; +typedef char module_elf32_section_header_size_check[ + (sizeof(ELF_SECTION_HEADER) == MODULE_ELF32_SECTION_HEADER_SIZE) ? 1 : -1]; +typedef char module_elf32_symbol_table_entry_size_check[ + (sizeof(ELF_SYMBOL_TABLE_ENTRY) == MODULE_ELF32_SYMBOL_TABLE_ENTRY_SIZE) ? 1 : -1]; + +/* Decode raw file bytes explicitly; do not cast file data to a + host structure, because host endianness and alignment may differ. */ +/* Decode a 16-bit little-endian ELF field. Version: 6.5.2. */ +static uint16_t module_elf32_read_u16_le(const uint8_t *bytes) +{ + + return((uint16_t)((uint16_t)bytes[0] | ((uint16_t)bytes[1] << 8))); +} + +/* Decode a 32-bit little-endian ELF field. Version: 6.5.2. */ +static uint32_t module_elf32_read_u32_le(const uint8_t *bytes) +{ + + return(((uint32_t)bytes[0]) | + ((uint32_t)bytes[1] << 8) | + ((uint32_t)bytes[2] << 16) | + ((uint32_t)bytes[3] << 24)); +} + +/* Validate and decode a complete ELF32 little-endian file header. + MISRA C:2023 Rule 15.5 deviation: reject an invalid identification before decoding. */ +static int module_elf32_decode_header(const uint8_t *bytes, ELF_HEADER *header) +{ + + size_t index; + + /* Accept the ELF32 little-endian encoding supported by these tools. */ + if ((bytes[0] != 0x7FU) || (bytes[1] != (uint8_t)'E') || + (bytes[2] != (uint8_t)'L') || (bytes[3] != (uint8_t)'F') || + (bytes[4] != 1U) || (bytes[5] != 1U) || (bytes[6] != 1U)) + { + + return(1); + } + + for (index = 0; index < MODULE_ELF32_IDENT_SIZE; index++) + { + + header -> elf_header_id_string[index] = bytes[index]; + } + + header -> elf_header_file_type = module_elf32_read_u16_le(&bytes[16]); + header -> elf_header_machinge_type = module_elf32_read_u16_le(&bytes[18]); + header -> elf_header_version = module_elf32_read_u32_le(&bytes[20]); + header -> elf_header_entry_address = module_elf32_read_u32_le(&bytes[24]); + header -> elf_header_program_header_offset = module_elf32_read_u32_le(&bytes[28]); + header -> elf_header_section_header_offset = module_elf32_read_u32_le(&bytes[32]); + header -> elf_header_processor_flags = module_elf32_read_u32_le(&bytes[36]); + header -> elf_header_size = module_elf32_read_u16_le(&bytes[40]); + header -> elf_header_program_header_size = module_elf32_read_u16_le(&bytes[42]); + header -> elf_header_program_header_entries = module_elf32_read_u16_le(&bytes[44]); + header -> elf_header_section_header_size = module_elf32_read_u16_le(&bytes[46]); + header -> elf_header_section_header_entries = module_elf32_read_u16_le(&bytes[48]); + header -> elf_header_section_string_index = module_elf32_read_u16_le(&bytes[50]); + + if ((header -> elf_header_version != 1U) || + (header -> elf_header_size != MODULE_ELF32_HEADER_SIZE) || + ((header -> elf_header_program_header_entries != 0U) && + (header -> elf_header_program_header_size != MODULE_ELF32_PROGRAM_HEADER_SIZE)) || + (header -> elf_header_section_header_entries == 0U) || + (header -> elf_header_section_header_size != MODULE_ELF32_SECTION_HEADER_SIZE)) + { + + return(1); + } + + return(0); +} + +/* Decode one complete ELF32 section-header record from raw bytes. */ +static void module_elf32_decode_section_header(const uint8_t *bytes, ELF_SECTION_HEADER *header) +{ + + header -> elf_section_header_name = module_elf32_read_u32_le(&bytes[0]); + header -> elf_section_header_type = module_elf32_read_u32_le(&bytes[4]); + header -> elf_section_header_flags = module_elf32_read_u32_le(&bytes[8]); + header -> elf_section_header_address = module_elf32_read_u32_le(&bytes[12]); + header -> elf_section_header_offset = module_elf32_read_u32_le(&bytes[16]); + header -> elf_section_header_size = module_elf32_read_u32_le(&bytes[20]); + header -> elf_section_header_link = module_elf32_read_u32_le(&bytes[24]); + header -> elf_section_header_info = module_elf32_read_u32_le(&bytes[28]); + header -> elf_section_header_alignment = module_elf32_read_u32_le(&bytes[32]); + header -> elf_section_header_entry_size = module_elf32_read_u32_le(&bytes[36]); +} + +#endif /* MODULE_CONVERTER_ELF32_H */ diff --git a/common_modules/module_manager/utilities/module_to_binary.c b/common_modules/module_manager/utilities/module_to_binary.c index 0b159cd78..ca368dfca 100644 --- a/common_modules/module_manager/utilities/module_to_binary.c +++ b/common_modules/module_manager/utilities/module_to_binary.c @@ -15,6 +15,8 @@ #include #include +#include "module_converter_elf32.h" + /* MISRA C:2012 Rule 21.3 and Dir 4.12 deviation: dynamic memory is used in this file. This is a host-side conversion utility executed on the development @@ -32,70 +34,7 @@ FILE *source_file; FILE *binary_file; - - -#define ELF_ID_STRING_SIZE 16 -#define ELF_ARM_MACHINE_TYPE 40 -#define ELF_EXECUTABLE 2 - - -typedef struct ELF_HEADER_STRUCT -{ - unsigned char elf_header_id_string[ELF_ID_STRING_SIZE]; - unsigned short elf_header_file_type; - unsigned short elf_header_machinge_type; - unsigned long elf_header_version; - unsigned long elf_header_entry_address; - unsigned long elf_header_program_header_offset; - unsigned long elf_header_section_header_offset; - unsigned long elf_header_processor_flags; - unsigned short elf_header_size; - unsigned short elf_header_program_header_size; - unsigned short elf_header_program_header_entries; - unsigned short elf_header_section_header_size; - unsigned short elf_header_section_header_entries; - unsigned short elf_header_section_string_index; -} ELF_HEADER; - - -typedef struct ELF_PROGRAM_HEADER_STRUCT -{ - unsigned long elf_program_header_type; - unsigned long elf_program_header_offset; - unsigned long elf_program_header_virtual_address; - unsigned long elf_program_header_physical_address; - unsigned long elf_program_header_file_size; - unsigned long elf_program_header_memory_size; - unsigned long elf_program_header_flags; - unsigned long elf_program_header_alignment; -} ELF_PROGRAM_HEADER; - - -typedef struct ELF_SECTION_HEADER_STRUCT -{ - unsigned long elf_section_header_name; - unsigned long elf_section_header_type; - unsigned long elf_section_header_flags; - unsigned long elf_section_header_address; - unsigned long elf_section_header_offset; - unsigned long elf_section_header_size; - unsigned long elf_section_header_link; - unsigned long elf_section_header_info; - unsigned long elf_section_header_alignment; - unsigned long elf_section_header_entry_size; -} ELF_SECTION_HEADER; - - -typedef struct ELF_SYMBOL_TABLE_ENTRY_STRUCT -{ - unsigned long elf_symbol_table_entry_name; - unsigned long elf_symbol_table_entry_address; - unsigned long elf_symbol_table_entry_size; - unsigned char elf_symbol_table_entry_info; - unsigned char elf_symbol_table_entry_other; - unsigned short elf_symbol_table_entry_shndx; - -} ELF_SYMBOL_TABLE_ENTRY; +long source_file_size; typedef struct CODE_SECTION_ENTRY_STRUCT @@ -109,7 +48,8 @@ typedef struct CODE_SECTION_ENTRY_STRUCT /* Define global variables. */ ELF_HEADER header; -ELF_PROGRAM_HEADER *program_header; +unsigned char *program_header; +unsigned char *raw_section_header_table; ELF_SECTION_HEADER *section_header; unsigned char *section_string_table; unsigned char *main_string_table; @@ -122,18 +62,45 @@ CODE_SECTION_ENTRY *code_section_array; /* Define helper functions. */ -int elf_object_read(unsigned long offset, void *object_address, int object_size) +/* Read into a valid buffer after checking its range against the recorded file size. */ +static int elf_object_read(unsigned long offset, void *object_address, size_t object_size) { -int i; +size_t i; int alpha; unsigned char *buffer; +unsigned long remaining_bytes; + + /* Accept empty tables and reject reads outside the input file. */ + if (object_size == 0) + { + + return(0); + } + + /* Reject offsets or lengths outside the opened source file. */ + if (offset > (unsigned long)source_file_size) + { + + return(1); + } + + remaining_bytes = (unsigned long)source_file_size - offset; + if (object_size > remaining_bytes) + { + + return(1); + } /* Setup the buffer pointer. */ buffer = (unsigned char *) object_address; /* Seek to the proper position in the file. */ - fseek(source_file, offset, SEEK_SET); + if (fseek(source_file, (long)offset, SEEK_SET) != 0) + { + + return(1); + } /* Read the ELF object. */ for (i = 0; i < object_size; i++) @@ -156,6 +123,7 @@ unsigned char *buffer; tolerate being called with resources that were never acquired. The areas it releases are the file scope pointers declared above. */ +/* Close converter files and release allocated ELF buffers. Version: 6.5.2. */ static void converter_cleanup(void) { @@ -181,6 +149,9 @@ static void converter_cleanup(void) is supplied a NULL pointer, so no test is required here. */ free(program_header); program_header = NULL; + /* Release the temporary on-disk section-header bytes. */ + free(raw_section_header_table); + raw_section_header_table = NULL; free(section_header); section_header = NULL; free(section_string_table); @@ -190,6 +161,7 @@ static void converter_cleanup(void) } +/* Convert an ELF32 module into a binary file. Version: 6.5.2. */ int main(int argc, char* argv[]) { @@ -198,6 +170,9 @@ unsigned long address; unsigned long size; unsigned long allocation_size; unsigned char *code_buffer; +unsigned char raw_header[MODULE_ELF32_HEADER_SIZE]; +unsigned long table_index; +unsigned char *raw_section_entry; unsigned long code_section_index; CODE_SECTION_ENTRY code_section_temp; unsigned char zero_value; @@ -231,25 +206,33 @@ unsigned char zero_value; return(2); } - /* Attempt to open the binary file for writing. */ - binary_file = fopen(argv[2], "wb"); + /* Record file length, then validate/decode raw ELF header bytes + before creating the output file. */ + /* Record the input size so every later read can reject out-of-range data. */ + if (fseek(source_file, 0L, SEEK_END) != 0) + { - /* Determine if the binary file was opened properly. */ - if (binary_file == NULL) + printf("**** Error: unable to determine source ELF file size **** \n"); + converter_cleanup(); + return(6); + } + + source_file_size = ftell(source_file); + if ((source_file_size < 0) || (fseek(source_file, 0L, SEEK_SET) != 0)) { - /* Print an error message out and wait for user key hit. */ - printf("**** Error: open failed on binary output file **** \n"); - printf(" File: %s ", argv[2]); - return(3); + printf("**** Error: unable to determine source ELF file size **** \n"); + converter_cleanup(); + return(6); } - /* Read the ELF header. */ - if (elf_object_read(0, &header, sizeof(header)) != 0) + /* Read and decode the fixed-size ELF32 header from raw file bytes. */ + if ((elf_object_read(0, raw_header, sizeof(raw_header)) != 0) || + (module_elf32_decode_header(raw_header, &header) != 0)) { /* Print an error message out. */ - printf("**** Error: read failed on the ELF header **** \n"); + printf("**** Error: invalid or unsupported ELF32 little-endian header **** \n"); /* Close the files and release the ELF areas. */ converter_cleanup(); @@ -257,8 +240,23 @@ unsigned char zero_value; return(6); } + /* Attempt to open the binary file for writing only after the input header + has been accepted. */ + binary_file = fopen(argv[2], "wb"); + + /* Determine if the binary file was opened properly. */ + if (binary_file == NULL) + { + + /* Print an error message out and wait for user key hit. */ + printf("**** Error: open failed on binary output file **** \n"); + printf(" File: %s ", argv[2]); + converter_cleanup(); + return(3); + } + /* Allocate memory for the program header(s). */ - allocation_size = sizeof(ELF_PROGRAM_HEADER)*header.elf_header_program_header_entries; + allocation_size = MODULE_ELF32_PROGRAM_HEADER_SIZE*header.elf_header_program_header_entries; program_header = malloc(allocation_size); /* Determine if the memory allocation was successful. Note that an empty area @@ -288,12 +286,14 @@ unsigned char zero_value; return(6); } + /* Read section headers as raw ELF bytes, then decode each + fixed-width field into host-side values. */ /* Allocate memory for the section header(s). */ - allocation_size = sizeof(ELF_SECTION_HEADER)*header.elf_header_section_header_entries; - section_header = malloc(allocation_size); + allocation_size = MODULE_ELF32_SECTION_HEADER_SIZE*header.elf_header_section_header_entries; + raw_section_header_table = malloc(allocation_size); /* Determine if the memory allocation was successful. */ - if ((section_header == NULL) && (allocation_size != 0)) + if (raw_section_header_table == NULL) { /* Print an error message out. */ @@ -306,7 +306,7 @@ unsigned char zero_value; } /* Read the section header(s). */ - if (elf_object_read(header.elf_header_section_header_offset, section_header, allocation_size) != 0) + if (elf_object_read(header.elf_header_section_header_offset, raw_section_header_table, allocation_size) != 0) { /* Print an error message out. */ @@ -318,6 +318,28 @@ unsigned char zero_value; return(6); } + /* Allocate host-side section records and decode each ELF32 entry. */ + allocation_size = sizeof(ELF_SECTION_HEADER)*header.elf_header_section_header_entries; + section_header = malloc(allocation_size); + if (section_header == NULL) + { + + printf("**** Error: memory allocation failed for decoded section headers **** \n"); + converter_cleanup(); + return(5); + } + + for (table_index = 0; table_index < header.elf_header_section_header_entries; table_index++) + { + + raw_section_entry = raw_section_header_table + + (table_index*MODULE_ELF32_SECTION_HEADER_SIZE); + module_elf32_decode_section_header(raw_section_entry, §ion_header[table_index]); + } + + free(raw_section_header_table); + raw_section_header_table = NULL; + /* Determine if the section string table index supplied by the ELF header is inside the section header area that was just read. */ if (header.elf_header_section_string_index >= header.elf_header_section_header_entries) diff --git a/common_modules/module_manager/utilities/module_to_c_array.c b/common_modules/module_manager/utilities/module_to_c_array.c index 72e87de0d..8f0cc3102 100644 --- a/common_modules/module_manager/utilities/module_to_c_array.c +++ b/common_modules/module_manager/utilities/module_to_c_array.c @@ -15,6 +15,8 @@ #include #include +#include "module_converter_elf32.h" + /* MISRA C:2012 Rule 21.3 and Dir 4.12 deviation: dynamic memory is used in this file. This is a host-side conversion utility executed on the development @@ -32,70 +34,7 @@ FILE *source_file; FILE *array_file; - - -#define ELF_ID_STRING_SIZE 16 -#define ELF_ARM_MACHINE_TYPE 40 -#define ELF_EXECUTABLE 2 - - -typedef struct ELF_HEADER_STRUCT -{ - unsigned char elf_header_id_string[ELF_ID_STRING_SIZE]; - unsigned short elf_header_file_type; - unsigned short elf_header_machinge_type; - unsigned long elf_header_version; - unsigned long elf_header_entry_address; - unsigned long elf_header_program_header_offset; - unsigned long elf_header_section_header_offset; - unsigned long elf_header_processor_flags; - unsigned short elf_header_size; - unsigned short elf_header_program_header_size; - unsigned short elf_header_program_header_entries; - unsigned short elf_header_section_header_size; - unsigned short elf_header_section_header_entries; - unsigned short elf_header_section_string_index; -} ELF_HEADER; - - -typedef struct ELF_PROGRAM_HEADER_STRUCT -{ - unsigned long elf_program_header_type; - unsigned long elf_program_header_offset; - unsigned long elf_program_header_virtual_address; - unsigned long elf_program_header_physical_address; - unsigned long elf_program_header_file_size; - unsigned long elf_program_header_memory_size; - unsigned long elf_program_header_flags; - unsigned long elf_program_header_alignment; -} ELF_PROGRAM_HEADER; - - -typedef struct ELF_SECTION_HEADER_STRUCT -{ - unsigned long elf_section_header_name; - unsigned long elf_section_header_type; - unsigned long elf_section_header_flags; - unsigned long elf_section_header_address; - unsigned long elf_section_header_offset; - unsigned long elf_section_header_size; - unsigned long elf_section_header_link; - unsigned long elf_section_header_info; - unsigned long elf_section_header_alignment; - unsigned long elf_section_header_entry_size; -} ELF_SECTION_HEADER; - - -typedef struct ELF_SYMBOL_TABLE_ENTRY_STRUCT -{ - unsigned long elf_symbol_table_entry_name; - unsigned long elf_symbol_table_entry_address; - unsigned long elf_symbol_table_entry_size; - unsigned char elf_symbol_table_entry_info; - unsigned char elf_symbol_table_entry_other; - unsigned short elf_symbol_table_entry_shndx; - -} ELF_SYMBOL_TABLE_ENTRY; +long source_file_size; typedef struct CODE_SECTION_ENTRY_STRUCT @@ -109,7 +48,8 @@ typedef struct CODE_SECTION_ENTRY_STRUCT /* Define global variables. */ ELF_HEADER header; -ELF_PROGRAM_HEADER *program_header; +unsigned char *program_header; +unsigned char *raw_section_header_table; ELF_SECTION_HEADER *section_header; unsigned char *section_string_table; unsigned char *main_string_table; @@ -122,18 +62,45 @@ CODE_SECTION_ENTRY *code_section_array; /* Define helper functions. */ -int elf_object_read(unsigned long offset, void *object_address, int object_size) +/* Read into a valid buffer after checking its range against the recorded file size. */ +static int elf_object_read(unsigned long offset, void *object_address, size_t object_size) { -int i; +size_t i; int alpha; unsigned char *buffer; +unsigned long remaining_bytes; + + /* Accept empty tables and reject reads outside the input file. */ + if (object_size == 0) + { + + return(0); + } + + /* Reject offsets or lengths outside the opened source file. */ + if (offset > (unsigned long)source_file_size) + { + + return(1); + } + + remaining_bytes = (unsigned long)source_file_size - offset; + if (object_size > remaining_bytes) + { + + return(1); + } /* Setup the buffer pointer. */ buffer = (unsigned char *) object_address; /* Seek to the proper position in the file. */ - fseek(source_file, offset, SEEK_SET); + if (fseek(source_file, (long)offset, SEEK_SET) != 0) + { + + return(1); + } /* Read the ELF object. */ for (i = 0; i < object_size; i++) @@ -156,6 +123,7 @@ unsigned char *buffer; tolerate being called with resources that were never acquired. The areas it releases are the file scope pointers declared above. */ +/* Close converter files and release allocated ELF buffers. Version: 6.5.2. */ static void converter_cleanup(void) { @@ -181,6 +149,9 @@ static void converter_cleanup(void) is supplied a NULL pointer, so no test is required here. */ free(program_header); program_header = NULL; + /* Release the temporary on-disk section-header bytes. */ + free(raw_section_header_table); + raw_section_header_table = NULL; free(section_header); section_header = NULL; free(section_string_table); @@ -190,6 +161,7 @@ static void converter_cleanup(void) } +/* Convert an ELF32 module into a C array source file. Version: 6.5.2. */ int main(int argc, char* argv[]) { @@ -199,6 +171,9 @@ unsigned long size; unsigned long allocation_size; unsigned long column; unsigned char *code_buffer; +unsigned char raw_header[MODULE_ELF32_HEADER_SIZE]; +unsigned long table_index; +unsigned char *raw_section_entry; unsigned long code_section_index; CODE_SECTION_ENTRY code_section_temp; @@ -231,25 +206,33 @@ CODE_SECTION_ENTRY code_section_temp; return(2); } - /* Attempt to open the dump file for writing. */ - array_file = fopen(argv[2], "w"); + /* Record file length, then validate/decode raw ELF header bytes + before creating the output file. */ + /* Record the input size so every later read can reject out-of-range data. */ + if (fseek(source_file, 0L, SEEK_END) != 0) + { - /* Determine if the dump file was opened properly. */ - if (array_file == NULL) + printf("**** Error: unable to determine source ELF file size **** \n"); + converter_cleanup(); + return(6); + } + + source_file_size = ftell(source_file); + if ((source_file_size < 0) || (fseek(source_file, 0L, SEEK_SET) != 0)) { - /* Print an error message out and wait for user key hit. */ - printf("**** Error: open failed on C array file **** \n"); - printf(" File: %s ", argv[2]); - return(3); + printf("**** Error: unable to determine source ELF file size **** \n"); + converter_cleanup(); + return(6); } - /* Read the ELF header. */ - if (elf_object_read(0, &header, sizeof(header)) != 0) + /* Read and decode the fixed-size ELF32 header from raw file bytes. */ + if ((elf_object_read(0, raw_header, sizeof(raw_header)) != 0) || + (module_elf32_decode_header(raw_header, &header) != 0)) { /* Print an error message out. */ - printf("**** Error: read failed on the ELF header **** \n"); + printf("**** Error: invalid or unsupported ELF32 little-endian header **** \n"); /* Close the files and release the ELF areas. */ converter_cleanup(); @@ -257,6 +240,20 @@ CODE_SECTION_ENTRY code_section_temp; return(6); } + /* Attempt to open the dump file after the input header is accepted. */ + array_file = fopen(argv[2], "w"); + + /* Determine if the dump file was opened properly. */ + if (array_file == NULL) + { + + /* Print an error message out and wait for user key hit. */ + printf("**** Error: open failed on C array file **** \n"); + printf(" File: %s ", argv[2]); + converter_cleanup(); + return(3); + } + fprintf(array_file, "/**************************** Module-to-C-array Utility *****************************************/\n"); fprintf(array_file, "/* */\n"); fprintf(array_file, "/* Copyright (c) 2024 Microsoft Corp */\n"); @@ -270,7 +267,7 @@ CODE_SECTION_ENTRY code_section_temp; fprintf(array_file, "*/\n\n"); /* Allocate memory for the program header(s). */ - allocation_size = sizeof(ELF_PROGRAM_HEADER)*header.elf_header_program_header_entries; + allocation_size = MODULE_ELF32_PROGRAM_HEADER_SIZE*header.elf_header_program_header_entries; program_header = malloc(allocation_size); /* Determine if the memory allocation was successful. Note that an empty area @@ -300,12 +297,14 @@ CODE_SECTION_ENTRY code_section_temp; return(6); } + /* Read section headers as raw ELF bytes, then decode each + fixed-width field into host-side values. */ /* Allocate memory for the section header(s). */ - allocation_size = sizeof(ELF_SECTION_HEADER)*header.elf_header_section_header_entries; - section_header = malloc(allocation_size); + allocation_size = MODULE_ELF32_SECTION_HEADER_SIZE*header.elf_header_section_header_entries; + raw_section_header_table = malloc(allocation_size); /* Determine if the memory allocation was successful. */ - if ((section_header == NULL) && (allocation_size != 0)) + if (raw_section_header_table == NULL) { /* Print an error message out. */ @@ -318,7 +317,7 @@ CODE_SECTION_ENTRY code_section_temp; } /* Read the section header(s). */ - if (elf_object_read(header.elf_header_section_header_offset, section_header, allocation_size) != 0) + if (elf_object_read(header.elf_header_section_header_offset, raw_section_header_table, allocation_size) != 0) { /* Print an error message out. */ @@ -330,6 +329,28 @@ CODE_SECTION_ENTRY code_section_temp; return(6); } + /* Allocate host-side section records and decode each ELF32 entry. */ + allocation_size = sizeof(ELF_SECTION_HEADER)*header.elf_header_section_header_entries; + section_header = malloc(allocation_size); + if (section_header == NULL) + { + + printf("**** Error: memory allocation failed for decoded section headers **** \n"); + converter_cleanup(); + return(5); + } + + for (table_index = 0; table_index < header.elf_header_section_header_entries; table_index++) + { + + raw_section_entry = raw_section_header_table + + (table_index*MODULE_ELF32_SECTION_HEADER_SIZE); + module_elf32_decode_section_header(raw_section_entry, §ion_header[table_index]); + } + + free(raw_section_header_table); + raw_section_header_table = NULL; + /* Determine if the section string table index supplied by the ELF header is inside the section header area that was just read. */ if (header.elf_header_section_string_index >= header.elf_header_section_header_entries) diff --git a/test/tx/cmake/module_manager/CMakeLists.txt b/test/tx/cmake/module_manager/CMakeLists.txt index 6989a2a0f..0b75ea859 100644 --- a/test/tx/cmake/module_manager/CMakeLists.txt +++ b/test/tx/cmake/module_manager/CMakeLists.txt @@ -440,3 +440,32 @@ foreach(a35_port cortex_a35/gnu cortex_a35/ac6 cortex_a35_smp/gnu cortex_a35_smp add_test(${CMAKE_BUILD_TYPE}::${a35_target} ${a35_target}) endforeach() + +# Use native LP64 targets to exercise ELF32 conversion with a 64-bit long. +# The linker wrappers let the same instrumented executables exercise I/O failures. +find_package(Python3 QUIET COMPONENTS Interpreter) +if(Python3_Interpreter_FOUND AND CMAKE_SYSTEM_NAME STREQUAL "Linux" AND + CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|amd64|AMD64)$") + set(module_converter_utility_dir ${module_manager_dir}/utilities) + + foreach(converter IN ITEMS module_to_binary module_to_c_array) + set(target threadx_${converter}_elf32_test) + add_executable(${target} + ${module_converter_utility_dir}/${converter}.c + ${SOURCE_DIR}/module_converter_faults.c) + target_compile_options(${target} PRIVATE -m64) + target_link_options(${target} PRIVATE -m64 + -Wl,--wrap=malloc,--wrap=fseek,--wrap=ftell,--wrap=fgetc) + if(TX_COVERAGE OR CMAKE_BUILD_TYPE MATCHES "_coverage$") + target_compile_options(${target} PRIVATE --coverage) + target_link_options(${target} PRIVATE --coverage) + endif() + endforeach() + + add_test( + NAME ${CMAKE_BUILD_TYPE}::threadx_module_converter_elf32_test + COMMAND ${Python3_EXECUTABLE} + ${SOURCE_DIR}/module_converter_elf32_test.py + $ + $) +endif() diff --git a/test/tx/module_manager/module_converter_elf32_test.py b/test/tx/module_manager/module_converter_elf32_test.py new file mode 100644 index 000000000..76a144f6c --- /dev/null +++ b/test/tx/module_manager/module_converter_elf32_test.py @@ -0,0 +1,344 @@ +#!/usr/bin/env python3 +# +# Copyright (c) 2026 Eclipse ThreadX contributors +# +# This program and the accompanying materials are made available under the +# terms of the MIT License which is available at +# https://opensource.org/licenses/MIT. +# +# AI Disclosure: This file was largely AI-generated by OpenAI Codex (GPT-6). +# The AI-generated portions may be considered public domain (CC0-1.0) +# and not subject to the project's licence. The human contributor must +# review and verify the code before submission. +# +# SPDX-License-Identifier: MIT and CC0-1.0 +# +"""Command-line regression tests for the Module Manager ELF converters. + +The fixtures are deliberately small synthetic ELF32 files. They let the test +exercise malformed offsets and headers that a normal linker would never emit. +Only Python's standard library is required. +""" + +import os +import re +import shutil +import struct +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + + +ELF_HEADER_SIZE = 52 +PROGRAM_HEADER_SIZE = 32 +SECTION_HEADER_SIZE = 40 +ELF_IDENT = b"\x7fELF" + bytes((1, 1, 1, 0, 0)) + bytes(7) +SHSTRTAB = b"\x00.text\x00.text2\x00.shstrtab\x00" +TEXT_NAME = 1 +TEXT2_NAME = 7 +SHSTRTAB_NAME = 14 +CONVERTER_ARGUMENTS = [] + + +def pack_ehdr(*, endian="<", phnum=1, phoff=ELF_HEADER_SIZE, + shoff=None, shnum=3, shstrndx=2, phentsize=PROGRAM_HEADER_SIZE, + shentsize=SECTION_HEADER_SIZE, ehsize=ELF_HEADER_SIZE, + ident=None, version=1, ident_version=1): + if shoff is None: + shoff = 0 + if ident is None: + ident = bytearray(ELF_IDENT) + else: + ident = bytearray(ident) + ident[6] = ident_version + return struct.pack( + endian + "16sHHIIIIIHHHHHH", bytes(ident), 2, 40, version, 0, + phoff, shoff, 0, ehsize, phentsize, phnum, shentsize, shnum, + shstrndx) + + +def pack_phdr(endian="<"): + # PT_LOAD; its contents are not interpreted by these utilities. + return struct.pack(endian + "IIIIIIII", 1, ELF_HEADER_SIZE + PROGRAM_HEADER_SIZE, + 0, 0, 0, 0, 5, 4) + + +def pack_shdr(endian="<", name=0, section_type=0, flags=0, address=0, + offset=0, size=0, link=0, info=0, align=1, entsize=0): + return struct.pack(endian + "IIIIIIIIII", name, section_type, flags, + address, offset, size, link, info, align, entsize) + + +def make_elf(*, sections=None, phnum=1, endian="<", ident=None, + ident_version=1, header_overrides=None): + """Create an ELF32 input with section specs (name, vaddr, bytes).""" + if sections is None: + sections = [(".text", 0x1000, b"\x11\x22\x33\x44")] + + program = pack_phdr(endian) if phnum else b"" + data = bytearray(ELF_HEADER_SIZE + len(program)) + data[ELF_HEADER_SIZE:] = program + section_headers = [pack_shdr(endian)] + name_offsets = {".text": TEXT_NAME, ".text2": TEXT2_NAME} + for name, address, contents in sections: + section_offset = len(data) + data.extend(contents) + section_headers.append(pack_shdr( + endian, name=name_offsets[name], section_type=1, flags=0x6, + address=address, offset=section_offset, size=len(contents), align=4)) + + names_offset = len(data) + data.extend(SHSTRTAB) + section_headers.append(pack_shdr( + endian, name=SHSTRTAB_NAME, section_type=3, offset=names_offset, + size=len(SHSTRTAB), align=1)) + shoff = len(data) + data.extend(b"".join(section_headers)) + ehdr = pack_ehdr(endian=endian, phnum=phnum, + phoff=ELF_HEADER_SIZE if phnum else 0, + shoff=shoff, shnum=len(section_headers), + shstrndx=len(section_headers) - 1, + ident=ident, ident_version=ident_version) + data[:ELF_HEADER_SIZE] = ehdr + + for offset, value, fmt in (header_overrides or []): + struct.pack_into(endian + fmt, data, offset, value) + return bytes(data) + + +def run_converter(executable, input_path, output_path, *, env=None): + return subprocess.run([str(executable), str(input_path), str(output_path)], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, env=env, check=False) + + +def c_array_bytes(path): + text = path.read_text(encoding="utf-8") + text = re.sub(r"/\*.*?\*/", "", text, flags=re.DOTALL) + match = re.search(r"module_code\[\]\s*=\s*\{(.*?)\};", text, + flags=re.DOTALL) + if not match: + raise AssertionError("module_code array was not emitted") + return bytes(int(value, 16) for value in + re.findall(r"0x([0-9A-Fa-f]{1,2})\b", match.group(1))) + + +# Exercise both converter programs against valid and hostile +# ELF fixtures, including deterministic allocation-failure injection. +class ModuleConverterELF32Tests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.binary_converter = Path(CONVERTER_ARGUMENTS[0]).resolve() + cls.array_converter = Path(CONVERTER_ARGUMENTS[1]).resolve() + + def setUp(self): + self.temp = tempfile.TemporaryDirectory(prefix="threadx-elf32-") + self.directory = Path(self.temp.name) + self.input_path = self.directory / "fixture.elf" + + def tearDown(self): + self.temp.cleanup() + + def write_fixture(self, contents): + self.input_path.write_bytes(contents) + return self.input_path + + def assert_both_succeed(self, contents, expected): + self.write_fixture(contents) + binary_path = self.directory / "module.bin" + array_path = self.directory / "module.c" + for converter, output in ((self.binary_converter, binary_path), + (self.array_converter, array_path)): + result = run_converter(converter, self.input_path, output) + self.assertEqual(result.returncode, 0, + msg=result.stdout + result.stderr) + self.assertEqual(binary_path.read_bytes(), expected) + self.assertEqual(c_array_bytes(array_path), expected) + + def assert_both_reject(self, contents): + self.write_fixture(contents) + for converter, output in ( + (self.binary_converter, self.directory / "rejected.bin"), + (self.array_converter, self.directory / "rejected.c")): + result = run_converter(converter, self.input_path, output) + self.assertEqual(result.returncode, 6, + msg=result.stdout + result.stderr) + + def test_v1_valid_elf32_little_endian(self): + self.assert_both_succeed(make_elf(), b"\x11\x22\x33\x44") + + def test_v2_sections_are_sorted_and_gap_is_zero_filled(self): + contents = make_elf(sections=[ + (".text2", 0x1006, b"\xA1\xA2"), + (".text", 0x1000, b"\x01\x02\x03")]) + self.assert_both_succeed( + contents, b"\x01\x02\x03\x00\x00\x00\xA1\xA2") + + def test_v3_zero_program_headers(self): + self.assert_both_succeed(make_elf(phnum=0), b"\x11\x22\x33\x44") + + @unittest.skipUnless(shutil.which("readelf") or shutil.which("llvm-readelf"), + "readelf/llvm-readelf is not installed") + def test_v4_readelf_independent_header_and_section_cross_check(self): + self.write_fixture(make_elf(sections=[ + (".text", 0x1000, b"\x11\x22"), + (".text2", 0x1008, b"\x33")])) + readelf = shutil.which("readelf") or shutil.which("llvm-readelf") + result = subprocess.run([readelf, "-h", "-S", + str(self.input_path)], stdout=subprocess.PIPE, + stderr=subprocess.PIPE, text=True, check=False) + self.assertEqual(result.returncode, 0, msg=result.stderr) + self.assertIn("ELF32", result.stdout) + self.assertIn("little endian", result.stdout.lower()) + self.assertRegex(result.stdout, r"\.text\s+PROGBITS\s+(?:0x)?0*1000\b") + self.assertRegex(result.stdout, r"\.text2\s+PROGBITS\s+(?:0x)?0*1008\b") + self.assertIn(".shstrtab", result.stdout) + self.assertRegex(result.stdout, r"Number of section headers:\s+4\b") + self.assertRegex(result.stdout, r"Size of section headers:\s+40\b") + + def test_r1_bad_and_missing_magic(self): + for magic in (b"\x00ELF", b"\x7f?LF", b"\x7fE?F", b"\x7fEL?"): + contents = bytearray(make_elf()) + contents[:4] = magic + with self.subTest(magic=magic): + self.assert_both_reject(bytes(contents)) + + def test_r2_elf64_class_rejected(self): + contents = bytearray(make_elf()) + contents[4] = 2 + self.assert_both_reject(bytes(contents)) + + def test_r3_big_endian_elf32_rejected(self): + ident = bytearray(ELF_IDENT) + ident[5] = 2 + self.assert_both_reject(make_elf(endian=">", ident=ident)) + + def test_r4_invalid_ident_and_header_versions_rejected(self): + cases = [make_elf(ident_version=0), + make_elf(header_overrides=[(20, 0, "I")])] + for contents in cases: + with self.subTest(version=contents[6]): + self.assert_both_reject(contents) + + def test_r5_wrong_elf_record_sizes_rejected(self): + for offset, value in ((40, 51), (42, 31), (46, 39)): + contents = bytearray(make_elf()) + struct.pack_into(" +#include +#include +#include + +/* MISRA C:2023 Rules 21.2 and 21.8 deviations: GNU ld requires the reserved + wrapper names, and the host test reads the fault selection with getenv. */ +void *__real_malloc(size_t size); +int __real_fseek(FILE *stream, long offset, int origin); +long __real_ftell(FILE *stream); +int __real_fgetc(FILE *stream); + +/* Select the failing invocation of the named function for this process. */ +static bool fault_selected(const char *function_name, unsigned long *calls) +{ + const char *name = getenv("THREADX_MODULE_TEST_FAIL_CALL"); + const char *index = getenv("THREADX_MODULE_TEST_FAIL_INDEX"); + bool selected = false; + + if ((name != NULL) && (index != NULL) && (strcmp(name, function_name) == 0)) + { + ++(*calls); + selected = (*calls == strtoul(index, NULL, 10)); + } + + return(selected); +} + +/* Delegate allocations except when the test requests a failure. */ +void *__wrap_malloc(size_t size) +{ + static unsigned long calls; + + return(fault_selected("malloc", &calls) ? NULL : __real_malloc(size)); +} + +/* Delegate seeks except when the test requests a failure. */ +int __wrap_fseek(FILE *stream, long offset, int origin) +{ + static unsigned long calls; + + return(fault_selected("fseek", &calls) ? -1 : __real_fseek(stream, offset, origin)); +} + +/* Delegate position queries except when the test requests a failure. */ +long __wrap_ftell(FILE *stream) +{ + static unsigned long calls; + + return(fault_selected("ftell", &calls) ? -1L : __real_ftell(stream)); +} + +/* Simulate an interrupted or truncated input read. */ +int __wrap_fgetc(FILE *stream) +{ + static unsigned long calls; + + return(fault_selected("fgetc", &calls) ? EOF : __real_fgetc(stream)); +}