From f77f1d304f1a7a4dc03662ed5e42203c4b0cb660 Mon Sep 17 00:00:00 2001 From: aniketkb28 Date: Sun, 8 Nov 2026 12:37:55 +0530 Subject: [PATCH 01/10] Fixed module converter ELF parsing on 64-bit hosts (#585) --- .../utilities/module_converter_elf32.h | 200 ++++++++++ .../utilities/module_to_binary.c | 203 ++++++---- .../utilities/module_to_c_array.c | 202 ++++++---- test/tx/cmake/module_manager/CMakeLists.txt | 23 ++ .../module_converter_elf32_test.py | 358 ++++++++++++++++++ 5 files changed, 818 insertions(+), 168 deletions(-) create mode 100644 common_modules/module_manager/utilities/module_converter_elf32.h create mode 100644 test/tx/module_manager/module_converter_elf32_test.py 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..d156f162d --- /dev/null +++ b/common_modules/module_manager/utilities/module_converter_elf32.h @@ -0,0 +1,200 @@ +/*************************************************************************** + * 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 + +/* ISSUE #585: 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; + +/* ISSUE #585: 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]; + +/* ISSUE #585: decode raw file bytes explicitly; do not cast file data to a + host structure, because host endianness and alignment may differ. */ +static uint16_t module_elf32_read_u16_le(const uint8_t *bytes) +{ + + return((uint16_t)((uint16_t)bytes[0] | ((uint16_t)bytes[1] << 8))); +} + +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)); +} + +static int module_elf32_decode_header(const uint8_t *bytes, + size_t bytes_size, + ELF_HEADER *header) +{ + + size_t index; + + if ((bytes == NULL) || (header == NULL) || + (bytes_size < MODULE_ELF32_HEADER_SIZE)) + { + + return(1); + } + + /* 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); +} + +static int module_elf32_decode_section_header(const uint8_t *bytes, + size_t bytes_size, + ELF_SECTION_HEADER *header) +{ + + if ((bytes == NULL) || (header == NULL) || + (bytes_size < MODULE_ELF32_SECTION_HEADER_SIZE)) + { + + return(1); + } + + 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]); + + return(0); +} + +#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..d196d5bed 100644 --- a/common_modules/module_manager/utilities/module_to_binary.c +++ b/common_modules/module_manager/utilities/module_to_binary.c @@ -14,6 +14,9 @@ #include #include #include +#include + +#include "module_converter_elf32.h" /* MISRA C:2012 Rule 21.3 and Dir 4.12 deviation: dynamic memory is used in this @@ -32,70 +35,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 +49,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 +63,51 @@ CODE_SECTION_ENTRY *code_section_array; /* Define helper functions. */ -int elf_object_read(unsigned long offset, void *object_address, int object_size) +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; + + /* ISSUE #585: 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 ((source_file_size < 0) || (offset > (unsigned long)LONG_MAX) || + (offset > (unsigned long)source_file_size)) + { + + return(1); + } + + remaining_bytes = (unsigned long)source_file_size - offset; + if (object_size > remaining_bytes) + { + + return(1); + } + + if (object_address == NULL) + { + + 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++) @@ -181,6 +155,9 @@ static void converter_cleanup(void) is supplied a NULL pointer, so no test is required here. */ free(program_header); program_header = NULL; + /* ISSUE #585: 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); @@ -198,6 +175,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 +211,33 @@ unsigned char zero_value; return(2); } - /* Attempt to open the binary file for writing. */ - binary_file = fopen(argv[2], "wb"); + /* ISSUE #585: 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, sizeof(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 +245,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 +291,14 @@ unsigned char zero_value; return(6); } + /* ISSUE #585: 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) && (allocation_size != 0)) { /* Print an error message out. */ @@ -306,7 +311,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 +323,36 @@ 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) && (allocation_size != 0)) + { + + 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); + if (module_elf32_decode_section_header(raw_section_entry, + MODULE_ELF32_SECTION_HEADER_SIZE, + §ion_header[table_index]) != 0) + { + + printf("**** Error: invalid ELF32 section header **** \n"); + converter_cleanup(); + return(6); + } + } + + 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..1cef559d0 100644 --- a/common_modules/module_manager/utilities/module_to_c_array.c +++ b/common_modules/module_manager/utilities/module_to_c_array.c @@ -14,6 +14,9 @@ #include #include #include +#include + +#include "module_converter_elf32.h" /* MISRA C:2012 Rule 21.3 and Dir 4.12 deviation: dynamic memory is used in this @@ -32,70 +35,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 +49,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 +63,51 @@ CODE_SECTION_ENTRY *code_section_array; /* Define helper functions. */ -int elf_object_read(unsigned long offset, void *object_address, int object_size) +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; + + /* ISSUE #585: 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 ((source_file_size < 0) || (offset > (unsigned long)LONG_MAX) || + (offset > (unsigned long)source_file_size)) + { + + return(1); + } + + remaining_bytes = (unsigned long)source_file_size - offset; + if (object_size > remaining_bytes) + { + + return(1); + } + + if (object_address == NULL) + { + + 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++) @@ -181,6 +155,9 @@ static void converter_cleanup(void) is supplied a NULL pointer, so no test is required here. */ free(program_header); program_header = NULL; + /* ISSUE #585: 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); @@ -199,6 +176,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 +211,33 @@ CODE_SECTION_ENTRY code_section_temp; return(2); } - /* Attempt to open the dump file for writing. */ - array_file = fopen(argv[2], "w"); + /* ISSUE #585: 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, sizeof(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 +245,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 +272,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 +302,14 @@ CODE_SECTION_ENTRY code_section_temp; return(6); } + /* ISSUE #585: 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) && (allocation_size != 0)) { /* Print an error message out. */ @@ -318,7 +322,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 +334,36 @@ 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) && (allocation_size != 0)) + { + + 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); + if (module_elf32_decode_section_header(raw_section_entry, + MODULE_ELF32_SECTION_HEADER_SIZE, + §ion_header[table_index]) != 0) + { + + printf("**** Error: invalid ELF32 section header **** \n"); + converter_cleanup(); + return(6); + } + } + + 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 d5fef5290..ad29b62fc 100644 --- a/test/tx/cmake/module_manager/CMakeLists.txt +++ b/test/tx/cmake/module_manager/CMakeLists.txt @@ -393,3 +393,26 @@ target_compile_options( add_test(${CMAKE_BUILD_TYPE}::threadx_module_manager_load_bounds_test threadx_module_manager_load_bounds_test) + +# ISSUE #585 TESTS: The ELF-to-binary and ELF-to-C-array utilities are host +# programs, so run them as command-line tools against synthetic ELF inputs. +# Python is optional for the normal ThreadX test build; when present, this driver +# checks valid and malformed ELF32 files through both real executables. +find_package(Python3 QUIET COMPONENTS Interpreter) +if(Python3_Interpreter_FOUND) + set(module_converter_utility_dir ${module_manager_dir}/utilities) + + add_executable(threadx_module_to_binary_elf32_test + ${module_converter_utility_dir}/module_to_binary.c) + add_executable(threadx_module_to_c_array_elf32_test + ${module_converter_utility_dir}/module_to_c_array.c) + + add_test( + ${CMAKE_BUILD_TYPE}::threadx_module_converter_elf32_test + ${Python3_EXECUTABLE} + ${SOURCE_DIR}/module_converter_elf32_test.py + $ + $ + ${module_converter_utility_dir}/module_to_binary.c + ${module_converter_utility_dir}/module_to_c_array.c) +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..51fda53f0 --- /dev/null +++ b/test/tx/module_manager/module_converter_elf32_test.py @@ -0,0 +1,358 @@ +#!/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))) + + +# ISSUE #585 TESTS: 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() + cls.source_binary = Path(CONVERTER_ARGUMENTS[2]).resolve() + cls.source_array = Path(CONVERTER_ARGUMENTS[3]).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.assertNotEqual(result.returncode, 0, + msg="converter unexpectedly accepted fixture") + + 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"NOPE", b"\x00\x00\x00\x00"): + 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("\n" + "#include \n" + "#include \n" + "static unsigned long calls;\n" + "void *module_test_malloc(size_t size) {\n" + " const char *setting = getenv(\"MODULE_TEST_FAIL_MALLOC_AT\");\n" + " unsigned long fail_at = setting ? strtoul(setting, NULL, 10) : 0;\n" + " calls++;\n" + " if (fail_at == calls) return NULL;\n" + " return malloc(size);\n" + "}\n", encoding="utf-8") + fixture = self.write_fixture(make_elf(sections=[ + (".text", 0x1000, b"\x01\x02"), + (".text2", 0x1004, b"\x03\x04")])) + + for source in (self.source_binary, self.source_array): + obj = self.directory / (source.stem + ".o") + injected = self.directory / (source.stem + "_malloc_fail") + compile_source = subprocess.run( + [compiler, "-std=c99", "-Dmalloc=module_test_malloc", "-c", + str(source), "-o", str(obj)], stdout=subprocess.PIPE, + stderr=subprocess.PIPE, text=True, check=False) + self.assertEqual(compile_source.returncode, 0, + msg=compile_source.stdout + compile_source.stderr) + compile_shim = subprocess.run( + [compiler, "-std=c99", "-c", str(shim), "-o", + str(self.directory / "malloc_fail.o")], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, check=False) + self.assertEqual(compile_shim.returncode, 0, + msg=compile_shim.stdout + compile_shim.stderr) + link = subprocess.run( + [compiler, str(obj), str(self.directory / "malloc_fail.o"), + "-o", str(injected)], stdout=subprocess.PIPE, + stderr=subprocess.PIPE, text=True, check=False) + self.assertEqual(link.returncode, 0, msg=link.stdout + link.stderr) + + # The valid fixture causes seven allocations: program headers, + # raw/decoded section tables, string table, section list and two + # section buffers. Each forced failure must be handled as an error. + for allocation_index in range(1, 8): + output = self.directory / (source.stem + "_failure.out") + env = os.environ.copy() + env["MODULE_TEST_FAIL_MALLOC_AT"] = str(allocation_index) + result = run_converter(injected, fixture, output, env=env) + self.assertNotEqual(result.returncode, 0, + msg=f"allocation {allocation_index} was not rejected") + self.assertIn("memory allocation failed", result.stdout.lower()) + + +if __name__ == "__main__": + CONVERTER_ARGUMENTS = sys.argv[1:5] + del sys.argv[1:5] + unittest.main(verbosity=2) From c48ff55c2f9990e1c53815749caeea406f7f35e0 Mon Sep 17 00:00:00 2001 From: Aniket KB Date: Sun, 8 Nov 2026 13:50:05 +0530 Subject: [PATCH 02/10] Added README-MACHZERO for ThreadX Issue #585 --- README-MACHZERO.md | 283 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 283 insertions(+) create mode 100644 README-MACHZERO.md diff --git a/README-MACHZERO.md b/README-MACHZERO.md new file mode 100644 index 000000000..349160574 --- /dev/null +++ b/README-MACHZERO.md @@ -0,0 +1,283 @@ +# MACHZERO — ThreadX Issue #585 + +**Repository:** [eclipse-threadx/threadx](https://github.com/eclipse-threadx/threadx) +**Issue:** [#585 — Module converter utilities misparse ELF files when built for a 64-bit host](https://github.com/eclipse-threadx/threadx/issues/585) + +## ROUND 1 +## 1. ISSUE + +In the original converter, ELF32 fields were represented with unsigned long, whose size can differ by host data model (commonly 4 bytes on ILP32 and 8 bytes on LP64). ELF32 itself defines fixed-width fields; the host-side C structure did not reliably match those widths. + +The raw file is directly copied onto C structures without accounting for padding, which leads to mismatch in the file layout (different offsets on different systems). + +Since this does not raise an error, garbage data is propagated upstream which might cause undefined behaviour. + +The failure occurs on the developer host system while interpreting the ELF input. It is not a scheduler defect and does not require hardware to reproduce the structure-size mismatch. + +## 2. ARCHITECTURE + +The data flow is: + +```text +ELF32 module file + ↓ +Host converter parses ELF metadata and finds code sections + ↓ +module_to_binary writes binary OR module_to_c_array writes C source code + ↓ +Firmware packages the generated module bytes + ↓ +ThreadX module manager loads the module on the target +``` + +## ROUND 2 +## 3. PLANNED SOLUTION + +We planned to eliminate compiler dependency by passing ELF file as raw bytes to the system instead of copying into the C structures. +We wanted to validate the ELF fields by checking 5 +a) Magic Bytes - Valid ELF file or not (0x7F E L F) +b) Class - If its 32 or 64 bit ELF +c) Data Encoding - Little/ big endian (the converters support ELF32 little-endian input; explicit decoding makes this independent of the host byte order) +d) Version - ELF Format +e) Machine - Target architecture (planned validation; the current implementation decodes e_machine but does not reject files based on its value) + +We planned to change the variable lengths by decoding using fixed width values (uint8_t, uint16_t, uint32_t) using library (Given as a suggested fix by the maintainer) to ensure its the same across all systems. + +Converter converts it to a binary or C array output as before. We are not modifying the core functionality of the project, just fixing the compatibility issue, making it host independent. + +We wanted to test if the code functionality remained unchanged using a few test cases: +a) Valid cases (Perfect input, ELF with gaps) +b) Invalid (Class: ELF 32/64 bit, Data Encoding: Little/ Big Endian, Table offsets, whether its a valid ELF file or not) + +## ROUND 3 +## 4. SOLUTION IMPLEMENTATION +The issue recommended changes in module_to_binary.c and module_to_c_array.c + +Our changes are in the two converter files, a shared ELF32 decoding header, the module-manager CMake test registration, and a Python regression test file. Here are some changes we implemented: + +a) ELF format fields changed to fixed width types +Unsigned char, int, long (host dependant) changed to uint8_t, uint16_t, uint32_t (host independent) + +b) Checking structure size during compile time +Use typedef checking for size of ELF fields (ELF_HEADER: 52 bytes, ELF_SECTION_HEADER: 40 bytes, ELF_PROGRAM_HEADER : 32 bytes, ELF_SYMBOL_TABLE_ENTRY: 16 bytes) + +c) Little endian decoding +Reconstruct values from individual bytes + +d) ELF Header Decoder +Validates ELF information fields (magic bytes, class, data encoding, identification version, ELF header version, and expected record sizes). It decodes the machine field but does not validate its value. + +e) Section Header Processing +Instead of copying the layout of ELF file to C structures, we follow the planned solution + +f) Program Header Allocation +Using ELF32 (not dependent on host) + +g) Improved Input Safety +Record input file size and validate every request (offset and length must remain within the file) + +h) Updated Cleanup Routine +Release additional raw byte buffer introduced by our parsing changes + + +## CODE CHANGES — OLD AND UPDATED + +The examples below show the relevant old pattern beside the implemented pattern. The old examples are from the original converter approach; the updated examples are shortened excerpts from the current code so the main difference is easy to see. + +### 1. ELF fields: host-dependent widths changed to fixed-width types + +**Old code pattern:** + +```c +typedef struct ELF_HEADER_STRUCT +{ + unsigned char id[16]; + unsigned short file_type; + unsigned short machine_type; + unsigned long version; + unsigned long entry_address; + unsigned long program_header_offset; + unsigned long section_header_offset; + /* More unsigned long and unsigned short fields. */ +} ELF_HEADER; +``` + +**Updated code pattern in `module_converter_elf32.h`:** + +```c +typedef struct ELF_HEADER_STRUCT +{ + uint8_t elf_header_id_string[16]; + 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; +``` + +The same fixed-width approach is used for program headers, section headers, and symbol-table entries. The size checks are compile-time guards against accidentally changing those decoded-value structures: + +```c +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]; +``` + +### 2. Raw file bytes: direct structure reads changed to explicit decoding + +**Old code pattern:** + +```c +/* Treat bytes read from the file as an ELF_HEADER object. */ +elf_object_read(0, &header, sizeof(header)); +``` + +This relied on the host structure's field sizes, padding, and byte order matching the on-disk ELF layout. + +**Updated code pattern:** + +```c +unsigned char raw_header[MODULE_ELF32_HEADER_SIZE]; + +if ((elf_object_read(0, raw_header, sizeof(raw_header)) != 0) || + (module_elf32_decode_header(raw_header, sizeof(raw_header), &header) != 0)) +{ + /* Report invalid or unsupported ELF input and clean up. */ +} +``` + +The decoder checks ELF magic, ELF32, little-endian encoding, identification version, header version, and expected structure sizes. It then reads each field from its specified byte offset. The `e_machine` value is decoded into the host record, but its value is not currently checked against a particular target architecture. + +### 3. Little-endian numbers: host byte interpretation changed to explicit assembly + +**Old code pattern:** + +```c +/* A multi-byte field was obtained through the host structure layout. */ +header.elf_header_entry_address = raw_header_field; +``` + +**Updated code pattern:** + +```c +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)); +} + +header->elf_header_entry_address = module_elf32_read_u32_le(&bytes[24]); +``` + +For bytes `78 56 34 12`, the function produces the numeric value `0x12345678`. This gives the same decoded value whether the converter itself runs on a little-endian or big-endian host. + +### 4. Reads: unchecked seek/read changed to file-range checked reads + +**Old code pattern:** + +```c +fseek(source_file, offset, SEEK_SET); +for (i = 0; i < object_size; i++) +{ + alpha = fgetc(source_file); + if (alpha == EOF) + return(1); + buffer[i] = (unsigned char)alpha; +} +``` + +**Updated code pattern in both converter files:** + +```c +if ((source_file_size < 0) || (offset > (unsigned long)LONG_MAX) || + (offset > (unsigned long)source_file_size)) +{ + return(1); +} + +remaining_bytes = (unsigned long)source_file_size - offset; +if (object_size > remaining_bytes) +{ + return(1); +} + +if (fseek(source_file, (long)offset, SEEK_SET) != 0) +{ + return(1); +} +``` + +The range check happens before seeking and reading. Subtracting the offset from the known file size first avoids relying on an unchecked `offset + length` calculation that could overflow. A zero-length read is accepted so empty tables can be handled without treating them as an error. + +### 5. Section table: raw table overlay changed to entry-by-entry decode + +**Old code pattern:** + +```c +section_header = malloc(sizeof(ELF_SECTION_HEADER) * entry_count); +elf_object_read(table_offset, section_header, + sizeof(ELF_SECTION_HEADER) * entry_count); +``` + +**Updated code pattern:** + +```c +raw_section_header_table = malloc(raw_table_size); +elf_object_read(table_offset, raw_section_header_table, raw_table_size); + +for (table_index = 0; table_index < entry_count; table_index++) +{ + raw_section_entry = raw_section_header_table + + (table_index * MODULE_ELF32_SECTION_HEADER_SIZE); + module_elf32_decode_section_header(raw_section_entry, + MODULE_ELF32_SECTION_HEADER_SIZE, + §ion_header[table_index]); +} +``` + +Each record is decoded from its ELF-defined 40-byte representation. The converter's later logic still receives `ELF_SECTION_HEADER` values and continues sorting/selecting sections and producing the same output format. + +### 6. Output and cleanup: validate input before creating output + +The converters now read and validate the input header before opening the output file. This prevents an invalid header from leaving a newly created empty output file. A shared cleanup routine closes any file that was opened and frees any allocated buffers; it safely handles pointers that are still `NULL`. The same parsing and cleanup approach is present in both `module_to_binary.c` and `module_to_c_array.c`. + +## SCREENSHOTS — VALIDATION RUNS + +These screenshots are evidence from the team's host run. The commands and results shown are described below; the screenshots do not show the compiler version or the full automated test-suite output. + +### Valid 32-bit ELF conversion on two host builds + +![Comparison of 64-bit-host and 32-bit-host converter outputs](README-MACHZERO-compatibility.png) + +test32.o is the exact file where the old conv64 (old module_to_binary.c) failed with read failed on the program header(s). +The old 64-bit tool failed on this file with no output. The new one succeeds. +The 64-bit and 32-bit builds now agree, so the word size no longer changes the result. That is the whole bug. +The new 64-bit output also matches the old 32-bit output byte for byte. The old 32-bit build was the correct one, so the 64-bit build now does what it should. + +### Building the 32-bit ELF fixture and comparing converter outputs + +![Compiling a small test.c source into a 32-bit object and comparing outputs](README-MACHZERO-test-compile-compare.png) + +This screenshot shows how the valid input fixture was prepared: `test.c` contains a small `add` function, and `gcc -m32 -c test.c -o test32.o` compiles it into a 32-bit ELF object without linking it. The converters then process that same object. The 64-bit-host and 32-bit-host converter runs both succeed and produce 103-byte outputs; `cmp` reports identical bytes, and the 64-bit-host output also matches the saved known-good 32-bit output. This demonstrates compatibility for this particular fixture. It does not establish that every ELF32 file or toolchain configuration produces identical output. + +### Unsupported and malformed input rejection + +![Unsupported and malformed ELF inputs are rejected](README-MACHZERO-rejections.png) + +There are four kinds of bad input. The old code accepted all of them without checking and misparsed them. +The four files fail for different reasons but print the same message. test64.o fails because it’s ELF64. The other three (24, 30 and 0 bytes) are shorter than the 52-byte header and fail the size check before the decoder runs. + + +ENVIRONMENT SPECIFICATIONS: Linux MacBookPro 6.17.0-42-generic #42-Ubuntu SMP PREEMPT_DYNAMIC x86_64 x86_64 x86_64 GNU/Linux From 03a5c927bab7f2d32fd22fd403aeca014448a628 Mon Sep 17 00:00:00 2001 From: Aniket KB Date: Sun, 8 Nov 2026 13:55:21 +0530 Subject: [PATCH 03/10] Refine README for validation runs and input handling --- README-MACHZERO.md | 46 +++++++++++++++++++++++++++++++++------------- 1 file changed, 33 insertions(+), 13 deletions(-) diff --git a/README-MACHZERO.md b/README-MACHZERO.md index 349160574..5d8911e79 100644 --- a/README-MACHZERO.md +++ b/README-MACHZERO.md @@ -253,30 +253,50 @@ Each record is decoded from its ELF-defined 40-byte representation. The converte The converters now read and validate the input header before opening the output file. This prevents an invalid header from leaving a newly created empty output file. A shared cleanup routine closes any file that was opened and frees any allocated buffers; it safely handles pointers that are still `NULL`. The same parsing and cleanup approach is present in both `module_to_binary.c` and `module_to_c_array.c`. -## SCREENSHOTS — VALIDATION RUNS - -These screenshots are evidence from the team's host run. The commands and results shown are described below; the screenshots do not show the compiler version or the full automated test-suite output. +## VALIDATION RUNS ### Valid 32-bit ELF conversion on two host builds -![Comparison of 64-bit-host and 32-bit-host converter outputs](README-MACHZERO-compatibility.png) +`test32.o` was the input where the old 64-bit converter failed while reading program headers. The updated converter succeeds, and its output matches the known-good output from the 32-bit build byte for byte. -test32.o is the exact file where the old conv64 (old module_to_binary.c) failed with read failed on the program header(s). -The old 64-bit tool failed on this file with no output. The new one succeeds. -The 64-bit and 32-bit builds now agree, so the word size no longer changes the result. That is the whole bug. -The new 64-bit output also matches the old 32-bit output byte for byte. The old 32-bit build was the correct one, so the 64-bit build now does what it should. +```text +$ ./new64 test32.o a64.bin +-> exit=0 output: 103 bytes +$ ./new32 test32.o a32.bin +-> exit=0 output: 103 bytes +$ cmp a64.bin a32.bin && echo SAME +SAME +$ cmp a64.bin out32.bin && echo "SAME as the old known-good 32-bit output" +SAME as the old known-good 32-bit output +``` -### Building the 32-bit ELF fixture and comparing converter outputs +### Building the 32-bit ELF fixture -![Compiling a small test.c source into a 32-bit object and comparing outputs](README-MACHZERO-test-compile-compare.png) +The fixture source contains a small `add` function. It is compiled as a 32-bit object file without linking, then used as the converter input. -This screenshot shows how the valid input fixture was prepared: `test.c` contains a small `add` function, and `gcc -m32 -c test.c -o test32.o` compiles it into a 32-bit ELF object without linking it. The converters then process that same object. The 64-bit-host and 32-bit-host converter runs both succeed and produce 103-byte outputs; `cmp` reports identical bytes, and the 64-bit-host output also matches the saved known-good 32-bit output. This demonstrates compatibility for this particular fixture. It does not establish that every ELF32 file or toolchain configuration produces identical output. +```text +$ printf 'int add(int a,int b){return a+b;}\n' > test.c +$ gcc -m32 -c test.c -o test32.o +``` ### Unsupported and malformed input rejection -![Unsupported and malformed ELF inputs are rejected](README-MACHZERO-rejections.png) +The ELF64 object, text file, truncated ELF header, and empty file are each rejected. The converter exits with status 6 and does not create the output file. The text, truncated, and empty inputs are shorter than the 52-byte ELF32 header; the ELF64 input is rejected as an unsupported class. -There are four kinds of bad input. The old code accepted all of them without checking and misparsed them. +```text +$ ./new64 test64.o c.bin +**** Error: invalid or unsupported ELF32 little-endian header **** +-> exit=6 output: not created bytes +$ ./new64 notelf.txt c.bin +**** Error: invalid or unsupported ELF32 little-endian header **** +-> exit=6 output: not created bytes +$ ./new64 trunc_hdr.elf c.bin +**** Error: invalid or unsupported ELF32 little-endian header **** +-> exit=6 output: not created bytes +$ ./new64 empty.elf c.bin +**** Error: invalid or unsupported ELF32 little-endian header **** +-> exit=6 output: not created bytes +``` The four files fail for different reasons but print the same message. test64.o fails because it’s ELF64. The other three (24, 30 and 0 bytes) are shorter than the 52-byte header and fail the size check before the decoder runs. From 4f4e8c6eb432bd40386fcca225d41db63ace9e49 Mon Sep 17 00:00:00 2001 From: Aniket KB Date: Sun, 8 Nov 2026 14:11:16 +0530 Subject: [PATCH 04/10] renamed ReadMe-MachZero-Team3.md file --- README-MACHZERO.md => ReadMe-MachZero-Team3.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename README-MACHZERO.md => ReadMe-MachZero-Team3.md (100%) diff --git a/README-MACHZERO.md b/ReadMe-MachZero-Team3.md similarity index 100% rename from README-MACHZERO.md rename to ReadMe-MachZero-Team3.md From 0e3a6214e141c771c308eca4d0db2a8b880a595a Mon Sep 17 00:00:00 2001 From: Aniket KB Date: Sun, 8 Nov 2026 14:16:32 +0530 Subject: [PATCH 05/10] added links to screenshots and test reproduction instructions --- ReadMe-MachZero-Team3.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/ReadMe-MachZero-Team3.md b/ReadMe-MachZero-Team3.md index 5d8911e79..fb5987f78 100644 --- a/ReadMe-MachZero-Team3.md +++ b/ReadMe-MachZero-Team3.md @@ -257,6 +257,12 @@ The converters now read and validate the input header before opening the output ### Valid 32-bit ELF conversion on two host builds +this link contains the output screenshots of initial (failure) and fixed code (success) +https://drive.google.com/drive/folders/1-717-yVBiul7tpWoPQbeeNmXZexUx02P?usp=sharing + +this file contains the instructions to reproduce the test cases obtained above +https://docs.google.com/document/d/19U9uNcRZ8nxyY5OsScYqIZUblecu7yh-KiVe43n9f9Y/edit?usp=sharing + `test32.o` was the input where the old 64-bit converter failed while reading program headers. The updated converter succeeds, and its output matches the known-good output from the 32-bit build byte for byte. ```text @@ -300,4 +306,5 @@ $ ./new64 empty.elf c.bin The four files fail for different reasons but print the same message. test64.o fails because it’s ELF64. The other three (24, 30 and 0 bytes) are shorter than the 52-byte header and fail the size check before the decoder runs. + ENVIRONMENT SPECIFICATIONS: Linux MacBookPro 6.17.0-42-generic #42-Ubuntu SMP PREEMPT_DYNAMIC x86_64 x86_64 x86_64 GNU/Linux From d9b04cf481a61f12d46350488f9a5226c0a274b9 Mon Sep 17 00:00:00 2001 From: aniketkb28 Date: Wed, 11 Nov 2026 22:02:02 +0530 Subject: [PATCH 06/10] Removed issue-number tags from converter comments Issue-specific tags described the task rather than the code. Removed those tags while keeping the comments focused on behavior. Assisted-by: Codex (GPT-6) --- .../module_manager/utilities/module_converter_elf32.h | 6 +++--- .../module_manager/utilities/module_to_binary.c | 8 ++++---- .../module_manager/utilities/module_to_c_array.c | 8 ++++---- test/tx/cmake/module_manager/CMakeLists.txt | 2 +- test/tx/module_manager/module_converter_elf32_test.py | 2 +- 5 files changed, 13 insertions(+), 13 deletions(-) diff --git a/common_modules/module_manager/utilities/module_converter_elf32.h b/common_modules/module_manager/utilities/module_converter_elf32.h index d156f162d..463ca614e 100644 --- a/common_modules/module_manager/utilities/module_converter_elf32.h +++ b/common_modules/module_manager/utilities/module_converter_elf32.h @@ -19,7 +19,7 @@ #include #include -/* ISSUE #585: ELF32 field layouts and little-endian byte decoding. */ +/* 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 @@ -85,7 +85,7 @@ typedef struct ELF_SYMBOL_TABLE_ENTRY_STRUCT uint16_t elf_symbol_table_entry_shndx; } ELF_SYMBOL_TABLE_ENTRY; -/* ISSUE #585: C99-compatible layout checks keep host-side values predictable. +/* 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[ @@ -97,7 +97,7 @@ typedef char module_elf32_section_header_size_check[ typedef char module_elf32_symbol_table_entry_size_check[ (sizeof(ELF_SYMBOL_TABLE_ENTRY) == MODULE_ELF32_SYMBOL_TABLE_ENTRY_SIZE) ? 1 : -1]; -/* ISSUE #585: decode raw file bytes explicitly; do not cast file data to a +/* Decode raw file bytes explicitly; do not cast file data to a host structure, because host endianness and alignment may differ. */ static uint16_t module_elf32_read_u16_le(const uint8_t *bytes) { diff --git a/common_modules/module_manager/utilities/module_to_binary.c b/common_modules/module_manager/utilities/module_to_binary.c index d196d5bed..8c1726631 100644 --- a/common_modules/module_manager/utilities/module_to_binary.c +++ b/common_modules/module_manager/utilities/module_to_binary.c @@ -71,7 +71,7 @@ int alpha; unsigned char *buffer; unsigned long remaining_bytes; - /* ISSUE #585: accept empty tables and reject reads outside the input file. */ + /* Accept empty tables and reject reads outside the input file. */ if (object_size == 0) { @@ -155,7 +155,7 @@ static void converter_cleanup(void) is supplied a NULL pointer, so no test is required here. */ free(program_header); program_header = NULL; - /* ISSUE #585: release the temporary on-disk section-header bytes. */ + /* Release the temporary on-disk section-header bytes. */ free(raw_section_header_table); raw_section_header_table = NULL; free(section_header); @@ -211,7 +211,7 @@ unsigned char zero_value; return(2); } - /* ISSUE #585: Record file length, then validate/decode raw ELF header bytes + /* 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) @@ -291,7 +291,7 @@ unsigned char zero_value; return(6); } - /* ISSUE #585: Read section headers as raw ELF bytes, then decode each + /* 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 = MODULE_ELF32_SECTION_HEADER_SIZE*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 1cef559d0..147aec1da 100644 --- a/common_modules/module_manager/utilities/module_to_c_array.c +++ b/common_modules/module_manager/utilities/module_to_c_array.c @@ -71,7 +71,7 @@ int alpha; unsigned char *buffer; unsigned long remaining_bytes; - /* ISSUE #585: accept empty tables and reject reads outside the input file. */ + /* Accept empty tables and reject reads outside the input file. */ if (object_size == 0) { @@ -155,7 +155,7 @@ static void converter_cleanup(void) is supplied a NULL pointer, so no test is required here. */ free(program_header); program_header = NULL; - /* ISSUE #585: release the temporary on-disk section-header bytes. */ + /* Release the temporary on-disk section-header bytes. */ free(raw_section_header_table); raw_section_header_table = NULL; free(section_header); @@ -211,7 +211,7 @@ CODE_SECTION_ENTRY code_section_temp; return(2); } - /* ISSUE #585: Record file length, then validate/decode raw ELF header bytes + /* 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) @@ -302,7 +302,7 @@ CODE_SECTION_ENTRY code_section_temp; return(6); } - /* ISSUE #585: Read section headers as raw ELF bytes, then decode each + /* 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 = MODULE_ELF32_SECTION_HEADER_SIZE*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 ad29b62fc..55ebaf82a 100644 --- a/test/tx/cmake/module_manager/CMakeLists.txt +++ b/test/tx/cmake/module_manager/CMakeLists.txt @@ -394,7 +394,7 @@ target_compile_options( add_test(${CMAKE_BUILD_TYPE}::threadx_module_manager_load_bounds_test threadx_module_manager_load_bounds_test) -# ISSUE #585 TESTS: The ELF-to-binary and ELF-to-C-array utilities are host +# The ELF-to-binary and ELF-to-C-array utilities are host # programs, so run them as command-line tools against synthetic ELF inputs. # Python is optional for the normal ThreadX test build; when present, this driver # checks valid and malformed ELF32 files through both real executables. diff --git a/test/tx/module_manager/module_converter_elf32_test.py b/test/tx/module_manager/module_converter_elf32_test.py index 51fda53f0..15fb57259 100644 --- a/test/tx/module_manager/module_converter_elf32_test.py +++ b/test/tx/module_manager/module_converter_elf32_test.py @@ -125,7 +125,7 @@ def c_array_bytes(path): re.findall(r"0x([0-9A-Fa-f]{1,2})\b", match.group(1))) -# ISSUE #585 TESTS: exercise both converter programs against valid and hostile +# Exercise both converter programs against valid and hostile # ELF fixtures, including deterministic allocation-failure injection. class ModuleConverterELF32Tests(unittest.TestCase): @classmethod From ddb18b57fb34bba79ab1c3fe6c157e81d1737fb8 Mon Sep 17 00:00:00 2001 From: aniketkb28 Date: Thu, 12 Nov 2026 09:27:51 +0530 Subject: [PATCH 07/10] Fixed ELF converter test command registration CTest passed the unexpanded TARGET_FILE expressions to the Python test driver. Updated the test registration to use NAME and COMMAND. The focused CMake harness passed 16 tests; the optional readelf check was skipped because readelf was unavailable. Assisted-by: Codex (GPT-6) --- test/tx/cmake/module_manager/CMakeLists.txt | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/test/tx/cmake/module_manager/CMakeLists.txt b/test/tx/cmake/module_manager/CMakeLists.txt index 55ebaf82a..4ff5fb3c0 100644 --- a/test/tx/cmake/module_manager/CMakeLists.txt +++ b/test/tx/cmake/module_manager/CMakeLists.txt @@ -408,11 +408,11 @@ if(Python3_Interpreter_FOUND) ${module_converter_utility_dir}/module_to_c_array.c) add_test( - ${CMAKE_BUILD_TYPE}::threadx_module_converter_elf32_test - ${Python3_EXECUTABLE} - ${SOURCE_DIR}/module_converter_elf32_test.py - $ - $ - ${module_converter_utility_dir}/module_to_binary.c - ${module_converter_utility_dir}/module_to_c_array.c) + NAME ${CMAKE_BUILD_TYPE}::threadx_module_converter_elf32_test + COMMAND ${Python3_EXECUTABLE} + ${SOURCE_DIR}/module_converter_elf32_test.py + $ + $ + ${module_converter_utility_dir}/module_to_binary.c + ${module_converter_utility_dir}/module_to_c_array.c) endif() From 845b44d5c6dc47b82aa1f20bfabcf786591db37a Mon Sep 17 00:00:00 2001 From: Bhargava G <109810322+bhargavaa-g@users.noreply.github.com> Date: Thu, 12 Nov 2026 09:31:51 +0530 Subject: [PATCH 08/10] Removed temporary readme --- ReadMe-MachZero-Team3.md | 310 --------------------------------------- 1 file changed, 310 deletions(-) delete mode 100644 ReadMe-MachZero-Team3.md diff --git a/ReadMe-MachZero-Team3.md b/ReadMe-MachZero-Team3.md deleted file mode 100644 index fb5987f78..000000000 --- a/ReadMe-MachZero-Team3.md +++ /dev/null @@ -1,310 +0,0 @@ -# MACHZERO — ThreadX Issue #585 - -**Repository:** [eclipse-threadx/threadx](https://github.com/eclipse-threadx/threadx) -**Issue:** [#585 — Module converter utilities misparse ELF files when built for a 64-bit host](https://github.com/eclipse-threadx/threadx/issues/585) - -## ROUND 1 -## 1. ISSUE - -In the original converter, ELF32 fields were represented with unsigned long, whose size can differ by host data model (commonly 4 bytes on ILP32 and 8 bytes on LP64). ELF32 itself defines fixed-width fields; the host-side C structure did not reliably match those widths. - -The raw file is directly copied onto C structures without accounting for padding, which leads to mismatch in the file layout (different offsets on different systems). - -Since this does not raise an error, garbage data is propagated upstream which might cause undefined behaviour. - -The failure occurs on the developer host system while interpreting the ELF input. It is not a scheduler defect and does not require hardware to reproduce the structure-size mismatch. - -## 2. ARCHITECTURE - -The data flow is: - -```text -ELF32 module file - ↓ -Host converter parses ELF metadata and finds code sections - ↓ -module_to_binary writes binary OR module_to_c_array writes C source code - ↓ -Firmware packages the generated module bytes - ↓ -ThreadX module manager loads the module on the target -``` - -## ROUND 2 -## 3. PLANNED SOLUTION - -We planned to eliminate compiler dependency by passing ELF file as raw bytes to the system instead of copying into the C structures. -We wanted to validate the ELF fields by checking 5 -a) Magic Bytes - Valid ELF file or not (0x7F E L F) -b) Class - If its 32 or 64 bit ELF -c) Data Encoding - Little/ big endian (the converters support ELF32 little-endian input; explicit decoding makes this independent of the host byte order) -d) Version - ELF Format -e) Machine - Target architecture (planned validation; the current implementation decodes e_machine but does not reject files based on its value) - -We planned to change the variable lengths by decoding using fixed width values (uint8_t, uint16_t, uint32_t) using library (Given as a suggested fix by the maintainer) to ensure its the same across all systems. - -Converter converts it to a binary or C array output as before. We are not modifying the core functionality of the project, just fixing the compatibility issue, making it host independent. - -We wanted to test if the code functionality remained unchanged using a few test cases: -a) Valid cases (Perfect input, ELF with gaps) -b) Invalid (Class: ELF 32/64 bit, Data Encoding: Little/ Big Endian, Table offsets, whether its a valid ELF file or not) - -## ROUND 3 -## 4. SOLUTION IMPLEMENTATION -The issue recommended changes in module_to_binary.c and module_to_c_array.c - -Our changes are in the two converter files, a shared ELF32 decoding header, the module-manager CMake test registration, and a Python regression test file. Here are some changes we implemented: - -a) ELF format fields changed to fixed width types -Unsigned char, int, long (host dependant) changed to uint8_t, uint16_t, uint32_t (host independent) - -b) Checking structure size during compile time -Use typedef checking for size of ELF fields (ELF_HEADER: 52 bytes, ELF_SECTION_HEADER: 40 bytes, ELF_PROGRAM_HEADER : 32 bytes, ELF_SYMBOL_TABLE_ENTRY: 16 bytes) - -c) Little endian decoding -Reconstruct values from individual bytes - -d) ELF Header Decoder -Validates ELF information fields (magic bytes, class, data encoding, identification version, ELF header version, and expected record sizes). It decodes the machine field but does not validate its value. - -e) Section Header Processing -Instead of copying the layout of ELF file to C structures, we follow the planned solution - -f) Program Header Allocation -Using ELF32 (not dependent on host) - -g) Improved Input Safety -Record input file size and validate every request (offset and length must remain within the file) - -h) Updated Cleanup Routine -Release additional raw byte buffer introduced by our parsing changes - - -## CODE CHANGES — OLD AND UPDATED - -The examples below show the relevant old pattern beside the implemented pattern. The old examples are from the original converter approach; the updated examples are shortened excerpts from the current code so the main difference is easy to see. - -### 1. ELF fields: host-dependent widths changed to fixed-width types - -**Old code pattern:** - -```c -typedef struct ELF_HEADER_STRUCT -{ - unsigned char id[16]; - unsigned short file_type; - unsigned short machine_type; - unsigned long version; - unsigned long entry_address; - unsigned long program_header_offset; - unsigned long section_header_offset; - /* More unsigned long and unsigned short fields. */ -} ELF_HEADER; -``` - -**Updated code pattern in `module_converter_elf32.h`:** - -```c -typedef struct ELF_HEADER_STRUCT -{ - uint8_t elf_header_id_string[16]; - 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; -``` - -The same fixed-width approach is used for program headers, section headers, and symbol-table entries. The size checks are compile-time guards against accidentally changing those decoded-value structures: - -```c -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]; -``` - -### 2. Raw file bytes: direct structure reads changed to explicit decoding - -**Old code pattern:** - -```c -/* Treat bytes read from the file as an ELF_HEADER object. */ -elf_object_read(0, &header, sizeof(header)); -``` - -This relied on the host structure's field sizes, padding, and byte order matching the on-disk ELF layout. - -**Updated code pattern:** - -```c -unsigned char raw_header[MODULE_ELF32_HEADER_SIZE]; - -if ((elf_object_read(0, raw_header, sizeof(raw_header)) != 0) || - (module_elf32_decode_header(raw_header, sizeof(raw_header), &header) != 0)) -{ - /* Report invalid or unsupported ELF input and clean up. */ -} -``` - -The decoder checks ELF magic, ELF32, little-endian encoding, identification version, header version, and expected structure sizes. It then reads each field from its specified byte offset. The `e_machine` value is decoded into the host record, but its value is not currently checked against a particular target architecture. - -### 3. Little-endian numbers: host byte interpretation changed to explicit assembly - -**Old code pattern:** - -```c -/* A multi-byte field was obtained through the host structure layout. */ -header.elf_header_entry_address = raw_header_field; -``` - -**Updated code pattern:** - -```c -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)); -} - -header->elf_header_entry_address = module_elf32_read_u32_le(&bytes[24]); -``` - -For bytes `78 56 34 12`, the function produces the numeric value `0x12345678`. This gives the same decoded value whether the converter itself runs on a little-endian or big-endian host. - -### 4. Reads: unchecked seek/read changed to file-range checked reads - -**Old code pattern:** - -```c -fseek(source_file, offset, SEEK_SET); -for (i = 0; i < object_size; i++) -{ - alpha = fgetc(source_file); - if (alpha == EOF) - return(1); - buffer[i] = (unsigned char)alpha; -} -``` - -**Updated code pattern in both converter files:** - -```c -if ((source_file_size < 0) || (offset > (unsigned long)LONG_MAX) || - (offset > (unsigned long)source_file_size)) -{ - return(1); -} - -remaining_bytes = (unsigned long)source_file_size - offset; -if (object_size > remaining_bytes) -{ - return(1); -} - -if (fseek(source_file, (long)offset, SEEK_SET) != 0) -{ - return(1); -} -``` - -The range check happens before seeking and reading. Subtracting the offset from the known file size first avoids relying on an unchecked `offset + length` calculation that could overflow. A zero-length read is accepted so empty tables can be handled without treating them as an error. - -### 5. Section table: raw table overlay changed to entry-by-entry decode - -**Old code pattern:** - -```c -section_header = malloc(sizeof(ELF_SECTION_HEADER) * entry_count); -elf_object_read(table_offset, section_header, - sizeof(ELF_SECTION_HEADER) * entry_count); -``` - -**Updated code pattern:** - -```c -raw_section_header_table = malloc(raw_table_size); -elf_object_read(table_offset, raw_section_header_table, raw_table_size); - -for (table_index = 0; table_index < entry_count; table_index++) -{ - raw_section_entry = raw_section_header_table + - (table_index * MODULE_ELF32_SECTION_HEADER_SIZE); - module_elf32_decode_section_header(raw_section_entry, - MODULE_ELF32_SECTION_HEADER_SIZE, - §ion_header[table_index]); -} -``` - -Each record is decoded from its ELF-defined 40-byte representation. The converter's later logic still receives `ELF_SECTION_HEADER` values and continues sorting/selecting sections and producing the same output format. - -### 6. Output and cleanup: validate input before creating output - -The converters now read and validate the input header before opening the output file. This prevents an invalid header from leaving a newly created empty output file. A shared cleanup routine closes any file that was opened and frees any allocated buffers; it safely handles pointers that are still `NULL`. The same parsing and cleanup approach is present in both `module_to_binary.c` and `module_to_c_array.c`. - -## VALIDATION RUNS - -### Valid 32-bit ELF conversion on two host builds - -this link contains the output screenshots of initial (failure) and fixed code (success) -https://drive.google.com/drive/folders/1-717-yVBiul7tpWoPQbeeNmXZexUx02P?usp=sharing - -this file contains the instructions to reproduce the test cases obtained above -https://docs.google.com/document/d/19U9uNcRZ8nxyY5OsScYqIZUblecu7yh-KiVe43n9f9Y/edit?usp=sharing - -`test32.o` was the input where the old 64-bit converter failed while reading program headers. The updated converter succeeds, and its output matches the known-good output from the 32-bit build byte for byte. - -```text -$ ./new64 test32.o a64.bin --> exit=0 output: 103 bytes -$ ./new32 test32.o a32.bin --> exit=0 output: 103 bytes -$ cmp a64.bin a32.bin && echo SAME -SAME -$ cmp a64.bin out32.bin && echo "SAME as the old known-good 32-bit output" -SAME as the old known-good 32-bit output -``` - -### Building the 32-bit ELF fixture - -The fixture source contains a small `add` function. It is compiled as a 32-bit object file without linking, then used as the converter input. - -```text -$ printf 'int add(int a,int b){return a+b;}\n' > test.c -$ gcc -m32 -c test.c -o test32.o -``` - -### Unsupported and malformed input rejection - -The ELF64 object, text file, truncated ELF header, and empty file are each rejected. The converter exits with status 6 and does not create the output file. The text, truncated, and empty inputs are shorter than the 52-byte ELF32 header; the ELF64 input is rejected as an unsupported class. - -```text -$ ./new64 test64.o c.bin -**** Error: invalid or unsupported ELF32 little-endian header **** --> exit=6 output: not created bytes -$ ./new64 notelf.txt c.bin -**** Error: invalid or unsupported ELF32 little-endian header **** --> exit=6 output: not created bytes -$ ./new64 trunc_hdr.elf c.bin -**** Error: invalid or unsupported ELF32 little-endian header **** --> exit=6 output: not created bytes -$ ./new64 empty.elf c.bin -**** Error: invalid or unsupported ELF32 little-endian header **** --> exit=6 output: not created bytes -``` -The four files fail for different reasons but print the same message. test64.o fails because it’s ELF64. The other three (24, 30 and 0 bytes) are shorter than the 52-byte header and fail the size check before the decoder runs. - - - -ENVIRONMENT SPECIFICATIONS: Linux MacBookPro 6.17.0-42-generic #42-Ubuntu SMP PREEMPT_DYNAMIC x86_64 x86_64 x86_64 GNU/Linux From 9141788a349d636c5bacae44fd28fdc67d91dd36 Mon Sep 17 00:00:00 2001 From: aniketkb28 Date: Thu, 12 Nov 2026 10:11:33 +0530 Subject: [PATCH 09/10] Document ELF converter functions Added short descriptions and release identifiers to the modified converter functions and ELF decoding helpers. git diff --check passed; no tests were rerun because these are comment-only changes. Assisted-by: Codex (GPT-6) --- .../module_manager/utilities/module_converter_elf32.h | 4 ++++ common_modules/module_manager/utilities/module_to_binary.c | 4 ++++ common_modules/module_manager/utilities/module_to_c_array.c | 4 ++++ 3 files changed, 12 insertions(+) diff --git a/common_modules/module_manager/utilities/module_converter_elf32.h b/common_modules/module_manager/utilities/module_converter_elf32.h index 463ca614e..72ef4d1be 100644 --- a/common_modules/module_manager/utilities/module_converter_elf32.h +++ b/common_modules/module_manager/utilities/module_converter_elf32.h @@ -99,12 +99,14 @@ typedef char module_elf32_symbol_table_entry_size_check[ /* 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) { @@ -114,6 +116,7 @@ static uint32_t module_elf32_read_u32_le(const uint8_t *bytes) ((uint32_t)bytes[3] << 24)); } +/* Validate and decode an ELF32 little-endian file header. Version: 6.5.2. */ static int module_elf32_decode_header(const uint8_t *bytes, size_t bytes_size, ELF_HEADER *header) @@ -171,6 +174,7 @@ static int module_elf32_decode_header(const uint8_t *bytes, return(0); } +/* Decode one ELF32 section-header record from raw bytes. Version: 6.5.2. */ static int module_elf32_decode_section_header(const uint8_t *bytes, size_t bytes_size, ELF_SECTION_HEADER *header) diff --git a/common_modules/module_manager/utilities/module_to_binary.c b/common_modules/module_manager/utilities/module_to_binary.c index 8c1726631..da798078d 100644 --- a/common_modules/module_manager/utilities/module_to_binary.c +++ b/common_modules/module_manager/utilities/module_to_binary.c @@ -63,6 +63,8 @@ CODE_SECTION_ENTRY *code_section_array; /* Define helper functions. */ +/* Read a byte range from the input ELF file after checking its bounds. + Version: 6.5.2. */ int elf_object_read(unsigned long offset, void *object_address, size_t object_size) { @@ -130,6 +132,7 @@ unsigned long remaining_bytes; 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) { @@ -167,6 +170,7 @@ static void converter_cleanup(void) } +/* Convert an ELF32 module into a binary file. Version: 6.5.2. */ int main(int argc, char* argv[]) { 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 147aec1da..e91797ecb 100644 --- a/common_modules/module_manager/utilities/module_to_c_array.c +++ b/common_modules/module_manager/utilities/module_to_c_array.c @@ -63,6 +63,8 @@ CODE_SECTION_ENTRY *code_section_array; /* Define helper functions. */ +/* Read a byte range from the input ELF file after checking its bounds. + Version: 6.5.2. */ int elf_object_read(unsigned long offset, void *object_address, size_t object_size) { @@ -130,6 +132,7 @@ unsigned long remaining_bytes; 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) { @@ -167,6 +170,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[]) { From 4995c205db9e13b38f226a92dadebfec44385cbe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Desbiens?= Date: Tue, 1 Dec 2026 09:06:01 -0500 Subject: [PATCH 10/10] Covered ELF32 conversion on native 64-bit Linux hosts The converter regression targets inherited the kernel suite's 32-bit flags, and allocation failures ran through separate executables whose coverage was not recorded. Built both converters at native LP64 width and injected allocation and I/O failures through their registered tests. Kept bounds checks at the file reads and decoded complete records without redundant checks on private buffers. Reject ELF files with no section headers before opening the output. GCC 14 passed all 20 converter cases in the default and trace profiles, with 100% line and branch coverage for the changed production code. The default Linux suite passed 136/136 tests and the trace Module Manager and converter tests passed 18/18. Assisted-by: Codex (GPT-6.2-Sol) --- .../utilities/module_converter_elf32.h | 33 ++----- .../utilities/module_to_binary.c | 31 ++---- .../utilities/module_to_c_array.c | 31 ++---- test/tx/cmake/module_manager/CMakeLists.txt | 30 +++--- .../module_converter_elf32_test.py | 98 ++++++++----------- .../module_manager/module_converter_faults.c | 74 ++++++++++++++ 6 files changed, 155 insertions(+), 142 deletions(-) create mode 100644 test/tx/module_manager/module_converter_faults.c diff --git a/common_modules/module_manager/utilities/module_converter_elf32.h b/common_modules/module_manager/utilities/module_converter_elf32.h index 72ef4d1be..af82bcc75 100644 --- a/common_modules/module_manager/utilities/module_converter_elf32.h +++ b/common_modules/module_manager/utilities/module_converter_elf32.h @@ -116,21 +116,13 @@ static uint32_t module_elf32_read_u32_le(const uint8_t *bytes) ((uint32_t)bytes[3] << 24)); } -/* Validate and decode an ELF32 little-endian file header. Version: 6.5.2. */ -static int module_elf32_decode_header(const uint8_t *bytes, - size_t bytes_size, - ELF_HEADER *header) +/* 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; - if ((bytes == NULL) || (header == NULL) || - (bytes_size < MODULE_ELF32_HEADER_SIZE)) - { - - return(1); - } - /* 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') || @@ -164,8 +156,8 @@ static int module_elf32_decode_header(const uint8_t *bytes, (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))) + (header -> elf_header_section_header_entries == 0U) || + (header -> elf_header_section_header_size != MODULE_ELF32_SECTION_HEADER_SIZE)) { return(1); @@ -174,19 +166,10 @@ static int module_elf32_decode_header(const uint8_t *bytes, return(0); } -/* Decode one ELF32 section-header record from raw bytes. Version: 6.5.2. */ -static int module_elf32_decode_section_header(const uint8_t *bytes, - size_t bytes_size, - ELF_SECTION_HEADER *header) +/* 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) { - if ((bytes == NULL) || (header == NULL) || - (bytes_size < MODULE_ELF32_SECTION_HEADER_SIZE)) - { - - return(1); - } - 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]); @@ -197,8 +180,6 @@ static int module_elf32_decode_section_header(const uint8_t *bytes, 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]); - - return(0); } #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 da798078d..ca368dfca 100644 --- a/common_modules/module_manager/utilities/module_to_binary.c +++ b/common_modules/module_manager/utilities/module_to_binary.c @@ -14,7 +14,6 @@ #include #include #include -#include #include "module_converter_elf32.h" @@ -63,9 +62,8 @@ CODE_SECTION_ENTRY *code_section_array; /* Define helper functions. */ -/* Read a byte range from the input ELF file after checking its bounds. - Version: 6.5.2. */ -int elf_object_read(unsigned long offset, void *object_address, size_t 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) { size_t i; @@ -81,8 +79,7 @@ unsigned long remaining_bytes; } /* Reject offsets or lengths outside the opened source file. */ - if ((source_file_size < 0) || (offset > (unsigned long)LONG_MAX) || - (offset > (unsigned long)source_file_size)) + if (offset > (unsigned long)source_file_size) { return(1); @@ -95,12 +92,6 @@ unsigned long remaining_bytes; return(1); } - if (object_address == NULL) - { - - return(1); - } - /* Setup the buffer pointer. */ buffer = (unsigned char *) object_address; @@ -237,7 +228,7 @@ unsigned char zero_value; /* 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, sizeof(raw_header), &header) != 0)) + (module_elf32_decode_header(raw_header, &header) != 0)) { /* Print an error message out. */ @@ -302,7 +293,7 @@ unsigned char zero_value; raw_section_header_table = malloc(allocation_size); /* Determine if the memory allocation was successful. */ - if ((raw_section_header_table == NULL) && (allocation_size != 0)) + if (raw_section_header_table == NULL) { /* Print an error message out. */ @@ -330,7 +321,7 @@ unsigned char zero_value; /* 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) && (allocation_size != 0)) + if (section_header == NULL) { printf("**** Error: memory allocation failed for decoded section headers **** \n"); @@ -343,15 +334,7 @@ unsigned char zero_value; raw_section_entry = raw_section_header_table + (table_index*MODULE_ELF32_SECTION_HEADER_SIZE); - if (module_elf32_decode_section_header(raw_section_entry, - MODULE_ELF32_SECTION_HEADER_SIZE, - §ion_header[table_index]) != 0) - { - - printf("**** Error: invalid ELF32 section header **** \n"); - converter_cleanup(); - return(6); - } + module_elf32_decode_section_header(raw_section_entry, §ion_header[table_index]); } free(raw_section_header_table); 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 e91797ecb..8f0cc3102 100644 --- a/common_modules/module_manager/utilities/module_to_c_array.c +++ b/common_modules/module_manager/utilities/module_to_c_array.c @@ -14,7 +14,6 @@ #include #include #include -#include #include "module_converter_elf32.h" @@ -63,9 +62,8 @@ CODE_SECTION_ENTRY *code_section_array; /* Define helper functions. */ -/* Read a byte range from the input ELF file after checking its bounds. - Version: 6.5.2. */ -int elf_object_read(unsigned long offset, void *object_address, size_t 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) { size_t i; @@ -81,8 +79,7 @@ unsigned long remaining_bytes; } /* Reject offsets or lengths outside the opened source file. */ - if ((source_file_size < 0) || (offset > (unsigned long)LONG_MAX) || - (offset > (unsigned long)source_file_size)) + if (offset > (unsigned long)source_file_size) { return(1); @@ -95,12 +92,6 @@ unsigned long remaining_bytes; return(1); } - if (object_address == NULL) - { - - return(1); - } - /* Setup the buffer pointer. */ buffer = (unsigned char *) object_address; @@ -237,7 +228,7 @@ CODE_SECTION_ENTRY code_section_temp; /* 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, sizeof(raw_header), &header) != 0)) + (module_elf32_decode_header(raw_header, &header) != 0)) { /* Print an error message out. */ @@ -313,7 +304,7 @@ CODE_SECTION_ENTRY code_section_temp; raw_section_header_table = malloc(allocation_size); /* Determine if the memory allocation was successful. */ - if ((raw_section_header_table == NULL) && (allocation_size != 0)) + if (raw_section_header_table == NULL) { /* Print an error message out. */ @@ -341,7 +332,7 @@ CODE_SECTION_ENTRY code_section_temp; /* 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) && (allocation_size != 0)) + if (section_header == NULL) { printf("**** Error: memory allocation failed for decoded section headers **** \n"); @@ -354,15 +345,7 @@ CODE_SECTION_ENTRY code_section_temp; raw_section_entry = raw_section_header_table + (table_index*MODULE_ELF32_SECTION_HEADER_SIZE); - if (module_elf32_decode_section_header(raw_section_entry, - MODULE_ELF32_SECTION_HEADER_SIZE, - §ion_header[table_index]) != 0) - { - - printf("**** Error: invalid ELF32 section header **** \n"); - converter_cleanup(); - return(6); - } + module_elf32_decode_section_header(raw_section_entry, §ion_header[table_index]); } free(raw_section_header_table); diff --git a/test/tx/cmake/module_manager/CMakeLists.txt b/test/tx/cmake/module_manager/CMakeLists.txt index f1206100f..0b75ea859 100644 --- a/test/tx/cmake/module_manager/CMakeLists.txt +++ b/test/tx/cmake/module_manager/CMakeLists.txt @@ -441,25 +441,31 @@ 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() -# The ELF-to-binary and ELF-to-C-array utilities are host -# programs, so run them as command-line tools against synthetic ELF inputs. -# Python is optional for the normal ThreadX test build; when present, this driver -# checks valid and malformed ELF32 files through both real executables. +# 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) +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) - add_executable(threadx_module_to_binary_elf32_test - ${module_converter_utility_dir}/module_to_binary.c) - add_executable(threadx_module_to_c_array_elf32_test - ${module_converter_utility_dir}/module_to_c_array.c) + 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 $ - $ - ${module_converter_utility_dir}/module_to_binary.c - ${module_converter_utility_dir}/module_to_c_array.c) + $) endif() diff --git a/test/tx/module_manager/module_converter_elf32_test.py b/test/tx/module_manager/module_converter_elf32_test.py index 15fb57259..76a144f6c 100644 --- a/test/tx/module_manager/module_converter_elf32_test.py +++ b/test/tx/module_manager/module_converter_elf32_test.py @@ -132,8 +132,6 @@ class ModuleConverterELF32Tests(unittest.TestCase): def setUpClass(cls): cls.binary_converter = Path(CONVERTER_ARGUMENTS[0]).resolve() cls.array_converter = Path(CONVERTER_ARGUMENTS[1]).resolve() - cls.source_binary = Path(CONVERTER_ARGUMENTS[2]).resolve() - cls.source_array = Path(CONVERTER_ARGUMENTS[3]).resolve() def setUp(self): self.temp = tempfile.TemporaryDirectory(prefix="threadx-elf32-") @@ -165,8 +163,8 @@ def assert_both_reject(self, contents): (self.binary_converter, self.directory / "rejected.bin"), (self.array_converter, self.directory / "rejected.c")): result = run_converter(converter, self.input_path, output) - self.assertNotEqual(result.returncode, 0, - msg="converter unexpectedly accepted fixture") + 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") @@ -201,7 +199,7 @@ def test_v4_readelf_independent_header_and_section_cross_check(self): self.assertRegex(result.stdout, r"Size of section headers:\s+40\b") def test_r1_bad_and_missing_magic(self): - for magic in (b"NOPE", b"\x00\x00\x00\x00"): + 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): @@ -297,62 +295,50 @@ def test_r12_invalid_source_and_output_paths_report_failure(self): self.assertNotEqual(output_result.returncode, 0) self.assertIn("open failed", output_result.stdout.lower()) - def test_r13_allocation_failure_injection(self): - """Rebuild with a malloc shim and fail each observed allocation.""" - compiler = os.environ.get("CC", "cc") - shim = self.directory / "malloc_fail.c" - shim.write_text( - "#include \n" - "#include \n" - "#include \n" - "static unsigned long calls;\n" - "void *module_test_malloc(size_t size) {\n" - " const char *setting = getenv(\"MODULE_TEST_FAIL_MALLOC_AT\");\n" - " unsigned long fail_at = setting ? strtoul(setting, NULL, 10) : 0;\n" - " calls++;\n" - " if (fail_at == calls) return NULL;\n" - " return malloc(size);\n" - "}\n", encoding="utf-8") - fixture = self.write_fixture(make_elf(sections=[ + def assert_fault_reported(self, function, call, message): + env = os.environ.copy() + env["THREADX_MODULE_TEST_FAIL_CALL"] = function + env["THREADX_MODULE_TEST_FAIL_INDEX"] = str(call) + for converter in (self.binary_converter, self.array_converter): + with self.subTest(converter=converter.name, function=function, call=call): + output = self.directory / "fault.out" + result = run_converter(converter, self.input_path, output, env=env) + self.assertNotEqual(result.returncode, 0) + self.assertIn(message, result.stdout.lower()) + + def test_r13_allocation_failure(self): + self.write_fixture(make_elf(sections=[ (".text", 0x1000, b"\x01\x02"), (".text2", 0x1004, b"\x03\x04")])) - for source in (self.source_binary, self.source_array): - obj = self.directory / (source.stem + ".o") - injected = self.directory / (source.stem + "_malloc_fail") - compile_source = subprocess.run( - [compiler, "-std=c99", "-Dmalloc=module_test_malloc", "-c", - str(source), "-o", str(obj)], stdout=subprocess.PIPE, - stderr=subprocess.PIPE, text=True, check=False) - self.assertEqual(compile_source.returncode, 0, - msg=compile_source.stdout + compile_source.stderr) - compile_shim = subprocess.run( - [compiler, "-std=c99", "-c", str(shim), "-o", - str(self.directory / "malloc_fail.o")], - stdout=subprocess.PIPE, stderr=subprocess.PIPE, - text=True, check=False) - self.assertEqual(compile_shim.returncode, 0, - msg=compile_shim.stdout + compile_shim.stderr) - link = subprocess.run( - [compiler, str(obj), str(self.directory / "malloc_fail.o"), - "-o", str(injected)], stdout=subprocess.PIPE, - stderr=subprocess.PIPE, text=True, check=False) - self.assertEqual(link.returncode, 0, msg=link.stdout + link.stderr) - - # The valid fixture causes seven allocations: program headers, - # raw/decoded section tables, string table, section list and two - # section buffers. Each forced failure must be handled as an error. - for allocation_index in range(1, 8): - output = self.directory / (source.stem + "_failure.out") + # Program headers, raw and decoded section tables, string table, + # section list and two section buffers. + for call in range(1, 8): + self.assert_fault_reported("malloc", call, "memory allocation failed") + + def test_r14_empty_optional_allocations(self): + self.write_fixture(make_elf(phnum=0)) + for converter in (self.binary_converter, self.array_converter): + with self.subTest(converter=converter.name): env = os.environ.copy() - env["MODULE_TEST_FAIL_MALLOC_AT"] = str(allocation_index) - result = run_converter(injected, fixture, output, env=env) - self.assertNotEqual(result.returncode, 0, - msg=f"allocation {allocation_index} was not rejected") - self.assertIn("memory allocation failed", result.stdout.lower()) + env["THREADX_MODULE_TEST_FAIL_CALL"] = "malloc" + env["THREADX_MODULE_TEST_FAIL_INDEX"] = "1" + result = run_converter( + converter, self.input_path, self.directory / "empty.out", env=env) + self.assertEqual(result.returncode, 0, msg=result.stdout + result.stderr) + + def test_r15_file_io_failures(self): + self.write_fixture(make_elf()) + for function, call in (("fseek", 1), ("ftell", 1), ("fseek", 2)): + self.assert_fault_reported(function, call, "unable to determine source elf file size") + for function, call in (("fseek", 3), ("fgetc", 1)): + self.assert_fault_reported(function, call, "invalid or unsupported elf32") + + def test_r16_no_section_headers(self): + self.assert_both_reject(make_elf(header_overrides=[(48, 0, "H")])) if __name__ == "__main__": - CONVERTER_ARGUMENTS = sys.argv[1:5] - del sys.argv[1:5] + CONVERTER_ARGUMENTS = sys.argv[1:3] + del sys.argv[1:3] unittest.main(verbosity=2) diff --git a/test/tx/module_manager/module_converter_faults.c b/test/tx/module_manager/module_converter_faults.c new file mode 100644 index 000000000..751146ad6 --- /dev/null +++ b/test/tx/module_manager/module_converter_faults.c @@ -0,0 +1,74 @@ +/*************************************************************************** + * 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 Codex (GPT-6.2-Sol). + * The AI-generated portions may be considered public domain (CC0-1.0) + * and not subject to the project's licence. The human contributor has + * reviewed and verified that the code is correct. + * + * SPDX-License-Identifier: MIT and CC0-1.0 + **************************************************************************/ + +#include +#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)); +}