Skip to content

Commit 0492922

Browse files
authored
Merge pull request hermit-os#62 from fogti/entry-format
feat: Add format detection logic
2 parents 89bed50 + 0662b42 commit 0492922

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

src/lib.rs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,36 @@ pub use const_parse::parse_u128 as _parse_u128;
2626
#[doc(hidden)]
2727
pub use note::{_AbiTag, _Note};
2828

29+
/// GZIP magic number.
30+
///
31+
/// For details, see [10.17487/RFC1952](https://doi.org/10.17487/RFC1952).
32+
#[cfg(feature = "loader")]
33+
const GZIPMAG: &[u8; 3] = &[0x1f, 0x8b, 0x08];
34+
35+
/// Possible input formats for a Hermit loader.
36+
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
37+
#[cfg(feature = "loader")]
38+
pub enum Format {
39+
/// An ELF file, probably a Hermit kernel.
40+
Elf,
41+
/// A gzipped tar file, probably containing a config + ELF kernel image, and associated files.
42+
Gzip,
43+
}
44+
45+
/// Attempts to detect the format of an input file (using magic bytes), whether it is an ELF kernel or an image.
46+
#[cfg(feature = "loader")]
47+
pub fn detect_format(data: &[u8]) -> Option<Format> {
48+
if data.len() < 4 {
49+
None
50+
} else if data.starts_with(goblin::elf64::header::ELFMAG) {
51+
Some(Format::Elf)
52+
} else if data.starts_with(GZIPMAG) {
53+
Some(Format::Gzip)
54+
} else {
55+
None
56+
}
57+
}
58+
2959
/// Kernel entry point.
3060
///
3161
/// This is the signature of the entry point of the kernel.

0 commit comments

Comments
 (0)