authorgravatar for rbatiati@gmail.comRafael Batiati <rbatiati@gmail.com> 2025-02-11 18:12:44-03:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2025-02-11 21:12:44+00:00
log33f0d458cf1ff8450297274f2e69afd64abbe816
treeb4a36bbc3e5bbb5690cf93c4bb4a216cddb2a8e1
parent5c39ccdddaa0a601e233aad9a146561bb8ac6b82
signaturebadge-check Signed by PGP key B5690EEEBB952194

std.elf: fix panic while parsing header

When parsing an invalid (e.g., corrupted) ELF header, `@enumFromInt` can panic casting the exhaustive enum `ET`.

1 files changed, 6 insertions(+), 0 deletions(-)

lib/std/elf.zig+6
...@@ -462,6 +462,8 @@ pub const ET = enum(u16) {...@@ -462,6 +462,8 @@ pub const ET = enum(u16) {
462 /// Core file462 /// Core file
463 CORE = 4,463 CORE = 4,
464464
465 _,
466
465 /// Beginning of OS-specific codes467 /// Beginning of OS-specific codes
466 pub const LOOS = 0xfe00;468 pub const LOOS = 0xfe00;
467469
...@@ -532,17 +534,21 @@ pub const Header = struct {...@@ -532,17 +534,21 @@ pub const Header = struct {
532 };534 };
533 const need_bswap = endian != native_endian;535 const need_bswap = endian != native_endian;
534536
537 // Converting integers to exhaustive enums using `@enumFromInt` could cause a panic.
538 comptime assert(!@typeInfo(OSABI).@"enum".is_exhaustive);
535 const os_abi: OSABI = @enumFromInt(hdr32.e_ident[EI_OSABI]);539 const os_abi: OSABI = @enumFromInt(hdr32.e_ident[EI_OSABI]);
536540
537 // The meaning of this value depends on `os_abi` so just make it available as `u8`.541 // The meaning of this value depends on `os_abi` so just make it available as `u8`.
538 const abi_version = hdr32.e_ident[EI_ABIVERSION];542 const abi_version = hdr32.e_ident[EI_ABIVERSION];
539543
540 const @"type" = if (need_bswap) blk: {544 const @"type" = if (need_bswap) blk: {
545 comptime assert(!@typeInfo(ET).@"enum".is_exhaustive);
541 const value = @intFromEnum(hdr32.e_type);546 const value = @intFromEnum(hdr32.e_type);
542 break :blk @as(ET, @enumFromInt(@byteSwap(value)));547 break :blk @as(ET, @enumFromInt(@byteSwap(value)));
543 } else hdr32.e_type;548 } else hdr32.e_type;
544549
545 const machine = if (need_bswap) blk: {550 const machine = if (need_bswap) blk: {
551 comptime assert(!@typeInfo(EM).@"enum".is_exhaustive);
546 const value = @intFromEnum(hdr32.e_machine);552 const value = @intFromEnum(hdr32.e_machine);
547 break :blk @as(EM, @enumFromInt(@byteSwap(value)));553 break :blk @as(EM, @enumFromInt(@byteSwap(value)));
548 } else hdr32.e_machine;554 } else hdr32.e_machine;