pe_parser/lib.rs
1//! # pe-parser: Blazing-fast, safe, Portable Executable parsing.
2//!
3//! `pe-parser` provides a safe Rust-y way to parse Portable Executables quickly.
4//! - Everything parsed to native documented structs
5//! - Secondary parsing functions raw data into native Rust types
6//! - Every section can be printed with ease
7//!
8//! ## Examples
9//! ```
10//! # use std::{fs, io};
11//! use pe_parser::pe::parse_portable_executable;
12//!
13//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
14//! # let path_to_pe = "tests/pe/64_pe/64_pe_checksum_non_zero.dat";
15//! // Read the binary from a file
16//! let binary = fs::read(path_to_pe)?;
17//!
18//! // Parse it!
19//! let pe = parse_portable_executable(binary.as_slice())?;
20//! // Print all that technical goodness
21//! print!("{}", pe);
22//! # Ok(())
23//! # }
24//! ```
25
26#![warn(missing_docs)]
27#![cfg_attr(not(feature = "std"), no_std)]
28
29extern crate alloc;
30use crate::prelude::*;
31use core::fmt;
32
33/// COFF file header definitions and helper functions
34pub mod coff;
35/// COFF relocation definitions and helper functions
36pub mod relocation;
37/// Optional header definitions and helper functions
38pub mod optional;
39/// Section header definitions and helper functions
40pub mod section;
41/// Monolith struct containing all the information
42/// you will ever need
43pub mod pe;
44mod prelude;
45
46/// Error parsing a PE binary.
47#[derive(Debug)]
48pub enum Error {
49 /// Failed to read data; premature EOF.
50 OffsetOutOfRange,
51 /// Failed to parse a header for an optional.
52 BadOptionalHeader,
53 /// Failed to parse a String.
54 BadString(alloc::string::FromUtf8Error),
55 /// Missing PE header.
56 MissingPeHeader,
57 /// Missing COFF header.
58 MissingCoffHeader,
59 /// Missing magic number from header.
60 MissingMagicNumber,
61}
62
63impl fmt::Display for Error {
64 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65 match self {
66 Error::OffsetOutOfRange => f.write_str("Offset out of range!"),
67 Error::BadOptionalHeader => f.write_str("Failed to parse optional header!"),
68 Error::BadString(e) => f.write_fmt(format_args!("Failed to parse string: {}!", e)),
69 Error::MissingPeHeader => f.write_str("Missing PE header!"),
70 Error::MissingCoffHeader => f.write_str("Missing COFF header!"),
71 Error::MissingMagicNumber => f.write_str("Missing magic number!"),
72 }
73 }
74}
75
76#[cfg(feature = "std")]
77impl std::error::Error for Error {}