use crate::{
coff::{
CoffFile, CoffSection,
constants::{
IMAGE_SCN_ALIGN_16BYTES, IMAGE_SCN_ALIGN_MASK,
IMAGE_SIZEOF_TLS_DIRECTORY64,
},
layout::TLS_DIR_SIZE,
pe::{DataDirectory, TlsDirectory64},
},
endian::{U32, U64},
util::trim_nul,
};
const INDEX_OFF: u32 = TLS_STRUCT_SIZE + 8;
const CALLBACKS_OFF: u32 = TLS_STRUCT_SIZE;
#[allow(clippy::cast_possible_truncation)]
pub const TLS_STRUCT_SIZE: u32 = IMAGE_SIZEOF_TLS_DIRECTORY64 as u32;
pub struct TlsPlan {
template_size: u32,
zero_fill: u32,
align_chars: u32,
bytes: Vec<u8>,
directory: DataDirectory,
template_rva: u32,
index_rva: u32,
}
pub fn has_tls(inputs: &[CoffFile<'_>]) -> bool {
inputs
.iter()
.any(|f| f.sections().iter().any(is_tls_section))
}
fn is_tls_section(section: &CoffSection<'_>) -> bool {
trim_nul(section.name).starts_with(b".tls$")
}
impl TlsPlan {
pub fn new(
inputs: &[CoffFile<'_>],
template_size: u32,
zero_fill: u32,
) -> Self {
let align_chars = alignment_of(inputs);
let bytes = vec![0u8; usize::try_from(TLS_DIR_SIZE).unwrap_or(0)];
Self {
template_size,
zero_fill,
align_chars,
bytes,
directory: DataDirectory::default(),
template_rva: 0,
index_rva: 0,
}
}
pub const fn size(&self) -> u32 {
TLS_DIR_SIZE
}
pub fn finalize(
&mut self,
template_rva: u32,
meta_rva: u32,
image_base: u64,
) {
self.template_rva = template_rva;
self.index_rva = meta_rva.wrapping_add(INDEX_OFF);
let start = image_base.wrapping_add(u64::from(template_rva));
let end = start.wrapping_add(u64::from(self.template_size));
let index_va = image_base.wrapping_add(u64::from(self.index_rva));
let callbacks_va = image_base
.wrapping_add(u64::from(meta_rva.wrapping_add(CALLBACKS_OFF)));
let dir = TlsDirectory64 {
start_address_of_raw_data: U64::new(start),
end_address_of_raw_data: U64::new(end),
address_of_index: U64::new(index_va),
address_of_call_backs: U64::new(callbacks_va),
size_of_zero_fill: U32::new(self.zero_fill),
characteristics: U32::new(self.align_chars),
};
let src = bytemuck::bytes_of(&dir);
if let Some(slot) = self.bytes.get_mut(..src.len()) {
slot.copy_from_slice(src);
}
self.directory = DataDirectory {
virtual_address: U32::new(meta_rva),
size: U32::new(TLS_STRUCT_SIZE),
};
}
pub fn index_va(&self, image_base: u64) -> u64 {
image_base.wrapping_add(u64::from(self.index_rva))
}
pub fn directory(&self) -> DataDirectory {
self.directory
}
pub fn bytes(&self) -> &[u8] {
&self.bytes
}
pub const fn template_rva(&self) -> u32 {
self.template_rva
}
}
pub fn directory_fixup_rvas(meta_rva: u32) -> [u32; 4] {
[
meta_rva,
meta_rva.wrapping_add(8),
meta_rva.wrapping_add(16),
meta_rva.wrapping_add(24),
]
}
fn alignment_of(inputs: &[CoffFile<'_>]) -> u32 {
inputs
.iter()
.flat_map(CoffFile::sections)
.filter(|section| is_tls_section(section))
.map(|section| section.characteristics & IMAGE_SCN_ALIGN_MASK)
.max()
.unwrap_or(IMAGE_SCN_ALIGN_16BYTES)
}