On Wed Jan 14, 2026 at 3:18 AM GMT, John Hubbard wrote:
> On 1/13/26 5:57 AM, Gary Guo wrote:
>> On Wed Dec 3, 2025 at 5:59 AM GMT, John Hubbard wrote:
> ...
>> What I would do is to provide a helper function to be obtain a NUL-terminated
>> string from ELF:
>> 
>> fn elf_str(elf: &[u8], offset: u64) -> Option<&str> {
>>     // Note that you have a more efficient `from_bytes_until_nul`, you don't
>>     // need to iterate yourself!
>>     
>> CStr::from_bytes_until_nul(elf.get(usize::try_from(idx)?..)).ok()?.to_str().ok()
>> }
>> 
>> and then you can do
>> 
>> strtab_offset.checked_add(name_offest.into()).and_then(|idx| elf_str(elf, 
>> idx)).is_some_and(|s| s == target)
>> 
>
> OK, will do. (I keep thinking we have found all of the older places
> that should be updated to use CStr::from_bytes_until_nul(), but still
> not there yet.)
>
>> 
>>> +
>>>      /// Tries to extract section with name `name` from the ELF64 image 
>>> `elf`, and returns it.
>>>      pub(super) fn elf64_section<'a, 'b>(elf: &'a [u8], name: &'b str) -> 
>>> Option<&'a [u8]> {
>>>          let hdr = &elf
>>> @@ -298,26 +316,7 @@ pub(super) fn elf64_section<'a, 'b>(elf: &'a [u8], 
>>> name: &'b str) -> Option<&'a
>>>                  return false;
>>>              };
>>>  
>>> -            let Some(name_idx) = strhdr
>>> -                .0
>>> -                .sh_offset
>>> -                .checked_add(u64::from(hdr.0.sh_name))
>> 
>> I think the change is making the code hide the error when ELF is malformed. 
>> The
>> old code fails early which is arguably better?
>
> OK, so something like this would be easier to debug, but I'm not
> sure if it is as Rust-idiomatic as it should be?
>
>         // Find the section which name matches `name` and return it.
>         shdr_iter.find_map(|sh_bytes| {
>             let sh = S::from_bytes(sh_bytes)?;
>
>             // Compute the name offset; fail early if the ELF is malformed.
>             let Some(name_offset) = 
> strhdr.offset().checked_add(u64::from(sh.name())) else {
>                 return None;
>             };

I don't think this really needs to be functional use of iterators. Using just a
for loop might be easier so you can just use `?` inside.

If you just have your function return `Result<Option<..>>`, and turn this into a
loop, you could just use `?` or `.ok_or(EINVAL)?`.

Best,
Gary

>
>             // Get section name; skip if we can't read it.
>             let Some(section_name) = elf_str(elf, name_offset) else {
>                 return None;
>             };
>
>             // Check if the section name matches.
>             if section_name != name {
>                 return None;
>             }
>
>             let start = usize::try_from(sh.offset()).ok()?;
>             let end = usize::try_from(sh.size())
>                 .ok()
>                 .and_then(|sz| start.checked_add(sz))?;
>             elf.get(start..end)
>         })
>

Reply via email to