1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
/*!
TLS Directory.

# Examples

```
# #![allow(unused_variables)]
use pelite::pe64::{Pe, PeFile};

# #[allow(dead_code)]
fn example(file: PeFile<'_>) -> pelite::Result<()> {
	// Access the TLS directory
	let tls = file.tls()?;

	// Access the initialized thread local data
	let raw_data = tls.raw_data()?;

	// Access the TLS slot
	let slot = tls.slot()?;

	// Access the TLS callbacks
	let callbacks = tls.callbacks()?;

	Ok(())
}
```
*/

use std::fmt;

use crate::{Error, Result};

use super::image::*;
use super::Pe;

//----------------------------------------------------------------

/// TLS Directory.
///
/// For more information see the [module-level documentation](index.html).
#[derive(Copy, Clone)]
pub struct Tls<'a, P> {
	pe: P,
	image: &'a IMAGE_TLS_DIRECTORY,
}
impl<'a, P: Pe<'a>> Tls<'a, P> {
	pub(crate) fn try_from(pe: P) -> Result<Tls<'a, P>> {
		let datadir = pe.data_directory().get(IMAGE_DIRECTORY_ENTRY_TLS).ok_or(Error::Bounds)?;
		let image = pe.derva(datadir.VirtualAddress)?;
		Ok(Tls { pe, image })
	}
	/// Gets the PE instance.
	pub fn pe(&self) -> P {
		self.pe
	}
	/// Returns the underlying TLS directory image.
	pub fn image(&self) -> &'a IMAGE_TLS_DIRECTORY {
		self.image
	}
	/// Gets the raw TLS initialization data.
	pub fn raw_data(&self) -> Result<&'a [u8]> {
		if self.image.StartAddressOfRawData > self.image.EndAddressOfRawData {
			return Err(Error::Invalid);
		}
		// FIXME! truncation warning on 32bit...
		let len = (self.image.EndAddressOfRawData - self.image.StartAddressOfRawData) as usize;
		self.pe.deref_slice(self.image.StartAddressOfRawData.into(), len)
	}
	/// Gets the TLS slot location.
	pub fn slot(&self) -> Result<&'a u32> {
		self.pe.deref(self.image.AddressOfIndex.into())
	}
	/// Gets the TLS initialization callbacks.
	pub fn callbacks(&self) -> Result<&'a [Va]> {
		self.pe.deref_slice_s(self.image.AddressOfCallBacks.into(), 0)
	}
}
impl<'a, P: Pe<'a>> fmt::Debug for Tls<'a, P> {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		f.debug_struct("Tls")
			.field("raw_data.len", &format_args!("{:?}", self.raw_data().map(|raw_data| raw_data.len())))
			.field("callbacks.len", &format_args!("{:?}", &self.callbacks().map(|cbs| cbs.len())))
			.finish()
	}
}

//----------------------------------------------------------------

#[cfg(feature = "serde")]
mod serde {
	use crate::util::serde_helper::*;
	use super::{Pe, Tls};

	impl<'a, P: Pe<'a>> Serialize for Tls<'a, P> {
		fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
			let is_human_readable = serializer.is_human_readable();
			let mut state = serializer.serialize_struct("Tls", 2)?;
			if cfg!(feature = "data-encoding") && is_human_readable {
				#[cfg(feature = "data-encoding")]
				state.serialize_field("raw_data",
					&self.raw_data().ok().map(|data| data_encoding::BASE64.encode(data)))?;
			}
			else {
				state.serialize_field("raw_data", &self.raw_data().ok())?;
			}
			state.serialize_field("callbacks", &self.callbacks().ok())?;
			state.end()
		}
	}
}

//----------------------------------------------------------------

#[cfg(test)]
pub(crate) fn test<'a, P: Pe<'a>>(pe: P) -> Result<()> {
	let tls = pe.tls()?;
	let _ = format!("{:?}", tls);
	let _raw_data = tls.raw_data();
	let _slot = tls.slot();
	let _callbacks = tls.callbacks();
	Ok(())
}