add overflow check for vaddr

This commit is contained in:
mos 2024-04-19 11:23:48 +02:00
parent a1ece95459
commit 767804233f
2 changed files with 13 additions and 7 deletions

View File

@ -12,6 +12,7 @@ pub enum Error {
BadMagic,
BadType,
BadMachine,
BadAddr,
}
struct Phdr {
@ -101,15 +102,19 @@ pub fn load(elf: Vec<u8>, mem: &mut [u8]) -> Result<u32, Error> {
continue;
}
let vaddr = (phdr.vaddr - RAM_BASE) as usize;
let memsz = phdr.memsz as usize;
if let Some(vaddr) = phdr.vaddr.checked_sub(RAM_BASE) {
let vaddr = vaddr as usize;
let memsz = phdr.memsz as usize;
let pos = rdr.position();
rdr.set_position(phdr.offset as u64);
if rdr.read_exact(&mut mem[vaddr..vaddr + memsz]).is_err() {
return Err(Error::Eof);
let pos = rdr.position();
rdr.set_position(phdr.offset as u64);
if rdr.read_exact(&mut mem[vaddr..vaddr + memsz]).is_err() {
return Err(Error::Eof);
}
rdr.set_position(pos);
} else {
return Err(Error::BadAddr);
}
rdr.set_position(pos);
}
Ok(entry)

View File

@ -336,6 +336,7 @@ pub fn run(path: String) -> Result<()> {
elf::Error::BadMagic => bail!("bad magic"),
elf::Error::BadType => bail!("invalid executable"),
elf::Error::BadMachine => bail!("foreign elf architecture"),
elf::Error::BadAddr => bail!("bad virt address offset"),
},
};