Skip to content

Commit 7c50d74

Browse files
johnhubbardGnurou
authored andcommitted
gpu: nova-core: firmware: factor out an elf_str() function
Factor out a chunk of complexity into a new subroutine. This is an incremental step in adding ELF32 support to the existing ELF64 section support, for handling GPU firmware. Signed-off-by: John Hubbard <jhubbard@nvidia.com> Acked-by: Danilo Krummrich <dakr@kernel.org> Link: https://patch.msgid.link/20260326013902.588242-9-jhubbard@nvidia.com [acourbot: use fuller prefix in commit message.] Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
1 parent b3d2426 commit 7c50d74

1 file changed

Lines changed: 15 additions & 25 deletions

File tree

drivers/gpu/nova-core/firmware.rs

Lines changed: 15 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -484,6 +484,13 @@ mod elf {
484484
// SAFETY: all bit patterns are valid for this type, and it doesn't use interior mutability.
485485
unsafe impl FromBytes for Elf64SHdr {}
486486

487+
/// Returns a NULL-terminated string from the ELF image at `offset`.
488+
fn elf_str(elf: &[u8], offset: u64) -> Option<&str> {
489+
let idx = usize::try_from(offset).ok()?;
490+
let bytes = elf.get(idx..)?;
491+
CStr::from_bytes_until_nul(bytes).ok()?.to_str().ok()
492+
}
493+
487494
/// Tries to extract section with name `name` from the ELF64 image `elf`, and returns it.
488495
pub(super) fn elf64_section<'a, 'b>(elf: &'a [u8], name: &'b str) -> Option<&'a [u8]> {
489496
let hdr = &elf
@@ -510,32 +517,15 @@ mod elf {
510517
.and_then(Elf64SHdr::from_bytes)?;
511518

512519
// Find the section which name matches `name` and return it.
513-
shdr.find(|&sh| {
514-
let Some(hdr) = Elf64SHdr::from_bytes(sh) else {
515-
return false;
516-
};
517-
518-
let Some(name_idx) = strhdr
519-
.0
520-
.sh_offset
521-
.checked_add(u64::from(hdr.0.sh_name))
522-
.and_then(|idx| usize::try_from(idx).ok())
523-
else {
524-
return false;
525-
};
526-
527-
// Get the start of the name.
528-
elf.get(name_idx..)
529-
.and_then(|nstr| CStr::from_bytes_until_nul(nstr).ok())
530-
// Convert into str.
531-
.and_then(|c_str| c_str.to_str().ok())
532-
// Check that the name matches.
533-
.map(|str| str == name)
534-
.unwrap_or(false)
535-
})
536-
// Return the slice containing the section.
537-
.and_then(|sh| {
520+
shdr.find_map(|sh| {
538521
let hdr = Elf64SHdr::from_bytes(sh)?;
522+
let name_offset = strhdr.0.sh_offset.checked_add(u64::from(hdr.0.sh_name))?;
523+
let section_name = elf_str(elf, name_offset)?;
524+
525+
if section_name != name {
526+
return None;
527+
}
528+
539529
let start = usize::try_from(hdr.0.sh_offset).ok()?;
540530
let end = usize::try_from(hdr.0.sh_size)
541531
.ok()

0 commit comments

Comments
 (0)