bfd: Fix undefined shift in common symbol alignment handling
Prevents undefined behavior in bfd when handling common symbols with large alignments by capping shift counts.
This patch addresses a bug in binutils’ bfd library where common symbols with very large or non-power-of-two st_value could lead to undefined behavior due to an excessive shift count. The fix caps the alignment result from bfd_log2 at 63 and casts shift operands to bfd_vma to ensure safety across different architectures and to prevent potential crashes or incorrect symbol alignment.
- proposer
Submitted a v2 patch to fix undefined behavior in common symbol alignment handling within the bfd library.
“A common symbol (SHN_COMMON) with a very large or non-power-of-two st_value can cause bfd_log2 to return 64, which then triggers undefined behaviour when used as a shift count:”
In Details
This patch targets bfd/elflink.c and bfd/linker.c to resolve an issue related to common symbol alignment. When st_value exceeds $2^{63}$, bfd_log2 returns 64. This value, when used as a shift count for alignment calculations (e.g., 1 << alignment_power), results in undefined behavior on 32-bit and 64-bit systems. The fix caps the alignment power at 63 and ensures shifts are performed using bfd_vma to prevent overflows and UB.
- common symbol
- A symbol that represents a declaration of an uninitialized global variable. The linker resolves these symbols by allocating storage for them.
- st_value
- The 'value' field in an ELF symbol table entry. For common symbols, it represents the alignment requirement.
- bfd_log2
- A BFD library function that calculates the base-2 logarithm of a number, often used to determine the power of 2 for alignment.
- undefined behavior
- Behavior that occurs when a C or C++ program attempts an operation that is not defined by the C/C++ standards, leading to unpredictable results or crashes.
- bfd_vma
- BFD's generic virtual memory address type, typically unsigned long long on 64-bit systems, used to represent memory addresses.