pelite\pe64/
load_config.rs

1/*!
2Load Config Directory.
3
4# Examples
5
6```
7# #![allow(unused_variables)]
8use pelite::pe64::{Pe, PeFile};
9
10# #[allow(dead_code)]
11fn example(file: PeFile<'_>) -> pelite::Result<()> {
12	// Access the load config directory
13	let load_config = file.load_config()?;
14
15	// The only bits of interest here
16	let security_cookie = load_config.security_cookie()?;
17	let se_handler_table = load_config.se_handler_table()?;
18
19	Ok(())
20}
21```
22*/
23
24use std::fmt;
25
26use crate::{Error, Result};
27
28use super::image::*;
29use super::Pe;
30
31/// Load Config Directory.
32///
33/// For more information see the [module-level documentation](index.html).
34#[derive(Copy, Clone)]
35pub struct LoadConfig<'a, P> {
36	pe: P,
37	image: &'a IMAGE_LOAD_CONFIG_DIRECTORY,
38}
39impl<'a, P: Pe<'a>> LoadConfig<'a, P> {
40	pub(crate) fn try_from(pe: P) -> Result<LoadConfig<'a, P>> {
41		let datadir = pe.data_directory().get(IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG).ok_or(Error::Bounds)?;
42		let image = pe.derva(datadir.VirtualAddress)?;
43		Ok(LoadConfig { pe, image })
44	}
45	/// Gets the PE instance.
46	pub fn pe(&self) -> P {
47		self.pe
48	}
49	/// Returns the underlying load config directory image.
50	pub fn image(&self) -> &'a IMAGE_LOAD_CONFIG_DIRECTORY {
51		self.image
52	}
53	/// Gets the default security cookie for the image.
54	pub fn security_cookie(&self) -> Result<&'a u32> {
55		self.pe.deref(self.image.SecurityCookie.into())
56	}
57	/// Gets the structured exception handler table.
58	pub fn se_handler_table(&self) -> Result<&'a [Va]> {
59		self.pe.deref_slice(self.image.SEHandlerTable.into(), self.image.SEHandlerCount as usize)
60	}
61}
62impl<'a, P: Pe<'a>> fmt::Debug for LoadConfig<'a, P> {
63	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
64		f.debug_struct("LoadConfig")
65			.field("security_cookie", &format_args!("{:x?}", self.security_cookie()))
66			.field("se_handler_table.len", &format_args!("{:?}", self.se_handler_table().map(|seh| seh.len())))
67			.finish()
68	}
69}
70
71#[cfg(feature = "serde")]
72mod serde {
73	use crate::util::serde_helper::*;
74	use super::{Pe, LoadConfig};
75
76	impl<'a, P: Pe<'a>> Serialize for LoadConfig<'a, P> {
77		fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
78			let mut state = serializer.serialize_struct("LoadConfig", 2)?;
79			state.serialize_field("security_cookie", &self.security_cookie().ok())?;
80			state.serialize_field("se_handler_table", &self.se_handler_table().ok())?;
81			state.end()
82		}
83	}
84}
85
86#[cfg(test)]
87pub(crate) fn test<'a, P: Pe<'a>>(pe: P) -> Result<()> {
88	let load_config = pe.load_config()?;
89	let _ = format!("{:?}", load_config);
90	let _security_cookie = load_config.security_cookie();
91	let _se_handler_table = load_config.se_handler_table();
92	Ok(())
93}