wasmtime_jit/
code_memory.rs

1//! Memory management for executable code.
2
3use 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
13/// Management of executable memory within a `MmapVec`
14///
15/// This type consumes ownership of a region of memory and will manage the
16/// executable permissions of the contained JIT code as necessary.
17pub struct CodeMemory {
18    // NB: these are `ManuallyDrop` because `unwind_registration` must be
19    // dropped first since it refers to memory owned by `mmap`.
20    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    // Ranges within `self.mmap` of where the particular sections lie.
28    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        // Drop `unwind_registration` before `self.mmap`
41        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    /// Creates a new `CodeMemory` by taking ownership of the provided
55    /// `MmapVec`.
56    ///
57    /// The returned `CodeMemory` manages the internal `MmapVec` and the
58    /// `publish` method is used to actually make the memory executable.
59    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            // Double-check that sections are all aligned properly.
79            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                    // The text section might have relocations for things like
98                    // libcalls which need to be applied, so handle those here.
99                    //
100                    // Note that only a small subset of possible relocations are
101                    // handled. Only those required by the compiler side of
102                    // things are processed.
103                    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    /// Returns a reference to the underlying `MmapVec` this memory owns.
150    #[inline]
151    pub fn mmap(&self) -> &MmapVec {
152        &self.mmap
153    }
154
155    /// Returns the contents of the text section of the ELF executable this
156    /// represents.
157    #[inline]
158    pub fn text(&self) -> &[u8] {
159        &self.mmap[self.text.clone()]
160    }
161
162    /// Returns the contents of the `ELF_WASMTIME_DWARF` section.
163    #[inline]
164    pub fn dwarf(&self) -> &[u8] {
165        &self.mmap[self.dwarf.clone()]
166    }
167
168    /// Returns the data in the `ELF_NAME_DATA` section.
169    #[inline]
170    pub fn func_name_data(&self) -> &[u8] {
171        &self.mmap[self.func_name_data.clone()]
172    }
173
174    /// Returns the concatenated list of all data associated with this wasm
175    /// module.
176    ///
177    /// This is used for initialization of memories and all data ranges stored
178    /// in a `Module` are relative to the slice returned here.
179    #[inline]
180    pub fn wasm_data(&self) -> &[u8] {
181        &self.mmap[self.wasm_data.clone()]
182    }
183
184    /// Returns the encoded address map section used to pass to
185    /// `wasmtime_environ::lookup_file_pos`.
186    #[inline]
187    pub fn address_map_data(&self) -> &[u8] {
188        &self.mmap[self.address_map_data.clone()]
189    }
190
191    /// Returns the contents of the `ELF_WASMTIME_INFO` section, or an empty
192    /// slice if it wasn't found.
193    #[inline]
194    pub fn wasmtime_info(&self) -> &[u8] {
195        &self.mmap[self.info_data.clone()]
196    }
197
198    /// Returns the contents of the `ELF_WASMTIME_TRAPS` section, or an empty
199    /// slice if it wasn't found.
200    #[inline]
201    pub fn trap_data(&self) -> &[u8] {
202        &self.mmap[self.trap_data.clone()]
203    }
204
205    /// Publishes the internal ELF image to be ready for execution.
206    ///
207    /// This method can only be called once and will panic if called twice. This
208    /// will parse the ELF image from the original `MmapVec` and do everything
209    /// necessary to get it ready for execution, including:
210    ///
211    /// * Change page protections from read/write to read/execute.
212    /// * Register unwinding information with the OS
213    ///
214    /// After this function executes all JIT code should be ready to execute.
215    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        // The unsafety here comes from a few things:
224        //
225        // * We're actually updating some page protections to executable memory.
226        //
227        // * We're registering unwinding information which relies on the
228        //   correctness of the information in the first place. This applies to
229        //   both the actual unwinding tables as well as the validity of the
230        //   pointers we pass in itself.
231        unsafe {
232            // First, if necessary, apply relocations. This can happen for
233            // things like libcalls which happen late in the lowering process
234            // that don't go through the Wasm-based libcalls layer that's
235            // indirected through the `VMContext`. Note that most modules won't
236            // have relocations, so this typically doesn't do anything.
237            self.apply_relocations()?;
238
239            // Next freeze the contents of this image by making all of the
240            // memory readonly. Nothing after this point should ever be modified
241            // so commit everything. For a compiled-in-memory image this will
242            // mean IPIs to evict writable mappings from other cores. For
243            // loaded-from-disk images this shouldn't result in IPIs so long as
244            // there weren't any relocations because nothing should have
245            // otherwise written to the image at any point either.
246            self.mmap.make_readonly(0..self.mmap.len())?;
247
248            let text = self.text();
249
250            // Clear the newly allocated code from cache if the processor requires it
251            //
252            // Do this before marking the memory as R+X, technically we should be able to do it after
253            // but there are some CPU's that have had errata about doing this with read only memory.
254            icache_coherence::clear_cache(text.as_ptr().cast(), text.len())
255                .expect("Failed cache clear");
256
257            // Switch the executable portion from readonly to read/execute.
258            self.mmap
259                .make_executable(self.text.clone(), self.enable_branch_protection)
260                .context("unable to make memory executable")?;
261
262            // Flush any in-flight instructions from the pipeline
263            icache_coherence::pipeline_flush_mt().expect("Failed pipeline flush");
264
265            // With all our memory set up use the platform-specific
266            // `UnwindRegistration` implementation to inform the general
267            // runtime that there's unwinding information available for all
268            // our just-published JIT functions.
269            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}