cole14 / rust-elf

Library for parsing ELF files for Rust
Other
234 stars 45 forks source link

Implement core::error::Error for ParsingError #27

Closed jlxip closed 1 year ago

jlxip commented 1 year ago

First, let me say that I have no idea what I'm talking about. I've been learning Rust since the past month or so, so I don't understand the intricate details of it.

I'm writing a kernel and I'm using this project as the ELF parser. My program loader returns a Result with a runtime error type, since it can be either ParsingError or any other thing (such as an issue during page allocation). I can't unwrap() the Result of minimal_parse() since it's not always desirable to throw a kernel panic.

pub fn load(addr: u64, size: usize) -> Result<PID, Box<dyn error::Error>> {
    // ... stuff ...
}

Apparently I can't do:

let file = ElfBytes::<AnyEndian>::minimal_parse(slice)?;

since in !#[no_std] environments, where the std external crate isn't present, but core is, according to this line, the error::Error trait is not implemented, so ParsingError can't downcast to it.

If I understood everything correctly, std::error::Error is just a re-export of core::error::Error, which doesn't really need any std-ish functionality. Would it be possible to substitute the impl of std::error::Error trait for the core one, and thus remove the need for the std feature to be enabled in the crate?

Thanks a lot, and sorry if I'm not understanding something fundamental.

cole14 commented 1 year ago

Ahh yes, that seems like what should be happening there. I don't see a reason for the behavior that's implemented today and I think I just overlooked that detail when putting together the no_std support.

Like you suggested, it looks like the impl should be changed to core::error::Error with the cfg line removed on that impl block. If you change that with a local checkout of the elf source, does it let you do what you're hoping for? If so, would you be interested in putting together a PR for this?