wasmtime_jit/
code_memory.rs1use crate::subslice_range;
4use anyhow::{anyhow, bail, Context, Result};
5use object::read::{File, Object, ObjectSection};
6use object::ObjectSymbol;
7use std::mem::ManuallyDrop;
8use std::ops::Range;
9use wasmtime_environ::obj;
10use wasmtime_jit_icache_coherence as icache_coherence;
11use wasmtime_runtime::{libcalls, MmapVec, UnwindRegistration};
12
13pub struct CodeMemory {
18 mmap: ManuallyDrop<MmapVec>,
21 unwind_registration: ManuallyDrop<Option<UnwindRegistration>>,
22 published: bool,
23 enable_branch_protection: bool,
24
25 relocations: Vec<(usize, obj::LibCall)>,
26
27 text: Range<usize>,
29 unwind: Range<usize>,
30 trap_data: Range<usize>,
31 wasm_data: Range<usize>,
32 address_map_data: Range<usize>,
33 func_name_data: Range<usize>,
34 info_data: Range<usize>,
35 dwarf: Range<usize>,
36}
37
38impl Drop for CodeMemory {
39 fn drop(&mut self) {
40 unsafe {
42 ManuallyDrop::drop(&mut self.unwind_registration);
43 ManuallyDrop::drop(&mut self.mmap);
44 }
45 }
46}
47
48fn _assert() {
49 fn _assert_send_sync<T: Send + Sync>() {}
50 _assert_send_sync::<CodeMemory>();
51}
52
53impl CodeMemory {
54 pub fn new(mmap: MmapVec) -> Result<Self> {
60 let obj = File::parse(&mmap[..])
61 .with_context(|| "failed to parse internal compilation artifact")?;
62
63 let mut relocations = Vec::new();
64 let mut text = 0..0;
65 let mut unwind = 0..0;
66 let mut enable_branch_protection = None;
67 let mut trap_data = 0..0;
68 let mut wasm_data = 0..0;
69 let mut address_map_data = 0..0;
70 let mut func_name_data = 0..0;
71 let mut info_data = 0..0;
72 let mut dwarf = 0..0;
73 for section in obj.sections() {
74 let data = section.data()?;
75 let name = section.name()?;
76 let range = subslice_range(data, &mmap);
77
78 if section.align() != 0 && data.len() != 0 {
80 if (data.as_ptr() as u64 - mmap.as_ptr() as u64) % section.align() != 0 {
81 bail!(
82 "section `{}` isn't aligned to {:#x}",
83 section.name().unwrap_or("ERROR"),
84 section.align()
85 );
86 }
87 }
88
89 match name {
90 obj::ELF_WASM_BTI => match data.len() {
91 1 => enable_branch_protection = Some(data[0] != 0),
92 _ => bail!("invalid `{name}` section"),
93 },
94 ".text" => {
95 text = range;
96
97 for (offset, reloc) in section.relocations() {
104 assert_eq!(reloc.kind(), object::RelocationKind::Absolute);
105 assert_eq!(reloc.encoding(), object::RelocationEncoding::Generic);
106 assert_eq!(usize::from(reloc.size()), std::mem::size_of::<usize>());
107 assert_eq!(reloc.addend(), 0);
108 let sym = match reloc.target() {
109 object::RelocationTarget::Symbol(id) => id,
110 other => panic!("unknown relocation target {other:?}"),
111 };
112 let sym = obj.symbol_by_index(sym).unwrap().name().unwrap();
113 let libcall = obj::LibCall::from_str(sym)
114 .unwrap_or_else(|| panic!("unknown symbol relocation: {sym}"));
115
116 let offset = usize::try_from(offset).unwrap();
117 relocations.push((offset, libcall));
118 }
119 }
120 UnwindRegistration::SECTION_NAME => unwind = range,
121 obj::ELF_WASM_DATA => wasm_data = range,
122 obj::ELF_WASMTIME_ADDRMAP => address_map_data = range,
123 obj::ELF_WASMTIME_TRAPS => trap_data = range,
124 obj::ELF_NAME_DATA => func_name_data = range,
125 obj::ELF_WASMTIME_INFO => info_data = range,
126 obj::ELF_WASMTIME_DWARF => dwarf = range,
127
128 _ => log::debug!("ignoring section {name}"),
129 }
130 }
131 Ok(Self {
132 mmap: ManuallyDrop::new(mmap),
133 unwind_registration: ManuallyDrop::new(None),
134 published: false,
135 enable_branch_protection: enable_branch_protection
136 .ok_or_else(|| anyhow!("missing `{}` section", obj::ELF_WASM_BTI))?,
137 text,
138 unwind,
139 trap_data,
140 address_map_data,
141 func_name_data,
142 dwarf,
143 info_data,
144 wasm_data,
145 relocations,
146 })
147 }
148
149 #[inline]
151 pub fn mmap(&self) -> &MmapVec {
152 &self.mmap
153 }
154
155 #[inline]
158 pub fn text(&self) -> &[u8] {
159 &self.mmap[self.text.clone()]
160 }
161
162 #[inline]
164 pub fn dwarf(&self) -> &[u8] {
165 &self.mmap[self.dwarf.clone()]
166 }
167
168 #[inline]
170 pub fn func_name_data(&self) -> &[u8] {
171 &self.mmap[self.func_name_data.clone()]
172 }
173
174 #[inline]
180 pub fn wasm_data(&self) -> &[u8] {
181 &self.mmap[self.wasm_data.clone()]
182 }
183
184 #[inline]
187 pub fn address_map_data(&self) -> &[u8] {
188 &self.mmap[self.address_map_data.clone()]
189 }
190
191 #[inline]
194 pub fn wasmtime_info(&self) -> &[u8] {
195 &self.mmap[self.info_data.clone()]
196 }
197
198 #[inline]
201 pub fn trap_data(&self) -> &[u8] {
202 &self.mmap[self.trap_data.clone()]
203 }
204
205 pub fn publish(&mut self) -> Result<()> {
216 assert!(!self.published);
217 self.published = true;
218
219 if self.text().is_empty() {
220 return Ok(());
221 }
222
223 unsafe {
232 self.apply_relocations()?;
238
239 self.mmap.make_readonly(0..self.mmap.len())?;
247
248 let text = self.text();
249
250 icache_coherence::clear_cache(text.as_ptr().cast(), text.len())
255 .expect("Failed cache clear");
256
257 self.mmap
259 .make_executable(self.text.clone(), self.enable_branch_protection)
260 .context("unable to make memory executable")?;
261
262 icache_coherence::pipeline_flush_mt().expect("Failed pipeline flush");
264
265 self.register_unwind_info()?;
270 }
271
272 Ok(())
273 }
274
275 unsafe fn apply_relocations(&mut self) -> Result<()> {
276 if self.relocations.is_empty() {
277 return Ok(());
278 }
279
280 for (offset, libcall) in self.relocations.iter() {
281 let offset = self.text.start + offset;
282 let libcall = match libcall {
283 obj::LibCall::FloorF32 => libcalls::relocs::floorf32 as usize,
284 obj::LibCall::FloorF64 => libcalls::relocs::floorf64 as usize,
285 obj::LibCall::NearestF32 => libcalls::relocs::nearestf32 as usize,
286 obj::LibCall::NearestF64 => libcalls::relocs::nearestf64 as usize,
287 obj::LibCall::CeilF32 => libcalls::relocs::ceilf32 as usize,
288 obj::LibCall::CeilF64 => libcalls::relocs::ceilf64 as usize,
289 obj::LibCall::TruncF32 => libcalls::relocs::truncf32 as usize,
290 obj::LibCall::TruncF64 => libcalls::relocs::truncf64 as usize,
291 obj::LibCall::FmaF32 => libcalls::relocs::fmaf32 as usize,
292 obj::LibCall::FmaF64 => libcalls::relocs::fmaf64 as usize,
293 #[cfg(target_arch = "x86_64")]
294 obj::LibCall::X86Pshufb => libcalls::relocs::x86_pshufb as usize,
295 #[cfg(not(target_arch = "x86_64"))]
296 obj::LibCall::X86Pshufb => unreachable!(),
297 };
298 self.mmap
299 .as_mut_ptr()
300 .add(offset)
301 .cast::<usize>()
302 .write_unaligned(libcall);
303 }
304 Ok(())
305 }
306
307 unsafe fn register_unwind_info(&mut self) -> Result<()> {
308 if self.unwind.len() == 0 {
309 return Ok(());
310 }
311 let text = self.text();
312 let unwind_info = &self.mmap[self.unwind.clone()];
313 let registration =
314 UnwindRegistration::new(text.as_ptr(), unwind_info.as_ptr(), unwind_info.len())
315 .context("failed to create unwind info registration")?;
316 *self.unwind_registration = Some(registration);
317 Ok(())
318 }
319}