1 //! Object file builder. 2 //! 3 //! Creates ELF image based on `Compilation` information. The ELF contains 4 //! functions and trampolines in the ".text" section. It also contains all 5 //! relocation records for the linking stage. If DWARF sections exist, their 6 //! content will be written as well. 7 //! 8 //! The object file has symbols for each function and trampoline, as well as 9 //! symbols that refer to libcalls. 10 //! 11 //! The function symbol names have format "_wasm_function_N", where N is 12 //! `FuncIndex`. The defined wasm function symbols refer to a JIT compiled 13 //! function body, the imported wasm function do not. The trampolines symbol 14 //! names have format "_trampoline_N", where N is `SignatureIndex`. 15 16 use crate::{CompiledFunction, RelocationTarget}; 17 use anyhow::Result; 18 use cranelift_codegen::binemit::Reloc; 19 use cranelift_codegen::isa::unwind::{systemv, UnwindInfo}; 20 use cranelift_codegen::TextSectionBuilder; 21 use cranelift_control::ControlPlane; 22 use gimli::write::{Address, EhFrame, EndianVec, FrameTable, Writer}; 23 use gimli::RunTimeEndian; 24 use object::write::{Object, SectionId, StandardSegment, Symbol, SymbolId, SymbolSection}; 25 use object::{Architecture, SectionKind, SymbolFlags, SymbolKind, SymbolScope}; 26 use std::collections::HashMap; 27 use std::ops::Range; 28 use wasmtime_environ::obj::LibCall; 29 use wasmtime_environ::Compiler; 30 31 const TEXT_SECTION_NAME: &[u8] = b".text"; 32 33 /// A helper structure used to assemble the final text section of an executable, 34 /// plus unwinding information and other related details. 35 /// 36 /// This builder relies on Cranelift-specific internals but assembles into a 37 /// generic `Object` which will get further appended to in a compiler-agnostic 38 /// fashion later. 39 pub struct ModuleTextBuilder<'a> { 40 /// The target that we're compiling for, used to query target-specific 41 /// information as necessary. 42 compiler: &'a dyn Compiler, 43 44 /// The object file that we're generating code into. 45 obj: &'a mut Object<'static>, 46 47 /// The WebAssembly module we're generating code for. 48 text_section: SectionId, 49 50 unwind_info: UnwindInfoBuilder<'a>, 51 52 /// In-progress text section that we're using cranelift's `MachBuffer` to 53 /// build to resolve relocations (calls) between functions. 54 text: Box<dyn TextSectionBuilder>, 55 56 /// Symbols defined in the object for libcalls that relocations are applied 57 /// against. 58 /// 59 /// Note that this isn't typically used. It's only used for SSE-disabled 60 /// builds without SIMD on x86_64 right now. 61 libcall_symbols: HashMap<LibCall, SymbolId>, 62 63 ctrl_plane: ControlPlane, 64 } 65 66 impl<'a> ModuleTextBuilder<'a> { 67 /// Creates a new builder for the text section of an executable. 68 /// 69 /// The `.text` section will be appended to the specified `obj` along with 70 /// any unwinding or such information as necessary. The `num_funcs` 71 /// parameter indicates the number of times the `append_func` function will 72 /// be called. The `finish` function will panic if this contract is not met. 73 pub fn new( 74 obj: &'a mut Object<'static>, 75 compiler: &'a dyn Compiler, 76 text: Box<dyn TextSectionBuilder>, 77 ) -> Self { 78 // Entire code (functions and trampolines) will be placed 79 // in the ".text" section. 80 let text_section = obj.add_section( 81 obj.segment_name(StandardSegment::Text).to_vec(), 82 TEXT_SECTION_NAME.to_vec(), 83 SectionKind::Text, 84 ); 85 86 Self { 87 compiler, 88 obj, 89 text_section, 90 unwind_info: Default::default(), 91 text, 92 libcall_symbols: HashMap::default(), 93 ctrl_plane: ControlPlane::default(), 94 } 95 } 96 97 /// Appends the `func` specified named `name` to this object. 98 /// 99 /// The `resolve_reloc_target` closure is used to resolve a relocation 100 /// target to an adjacent function which has already been added or will be 101 /// added to this object. The argument is the relocation target specified 102 /// within `CompiledFunction` and the return value must be an index where 103 /// the target will be defined by the `n`th call to `append_func`. 104 /// 105 /// Returns the symbol associated with the function as well as the range 106 /// that the function resides within the text section. 107 pub fn append_func( 108 &mut self, 109 name: &str, 110 compiled_func: &'a CompiledFunction, 111 resolve_reloc_target: impl Fn(wasmtime_environ::RelocationTarget) -> usize, 112 ) -> (SymbolId, Range<u64>) { 113 let body = compiled_func.buffer.data(); 114 let alignment = compiled_func.alignment; 115 let body_len = body.len() as u64; 116 let off = self 117 .text 118 .append(true, &body, alignment, &mut self.ctrl_plane); 119 120 let symbol_id = self.obj.add_symbol(Symbol { 121 name: name.as_bytes().to_vec(), 122 value: off, 123 size: body_len, 124 kind: SymbolKind::Text, 125 scope: SymbolScope::Compilation, 126 weak: false, 127 section: SymbolSection::Section(self.text_section), 128 flags: SymbolFlags::None, 129 }); 130 131 if let Some(info) = compiled_func.unwind_info() { 132 self.unwind_info.push(off, body_len, info); 133 } 134 135 for r in compiled_func.relocations() { 136 match r.reloc_target { 137 // Relocations against user-defined functions means that this is 138 // a relocation against a module-local function, typically a 139 // call between functions. The `text` field is given priority to 140 // resolve this relocation before we actually emit an object 141 // file, but if it can't handle it then we pass through the 142 // relocation. 143 RelocationTarget::Wasm(_) | RelocationTarget::Builtin(_) => { 144 let target = resolve_reloc_target(r.reloc_target); 145 if self 146 .text 147 .resolve_reloc(off + u64::from(r.offset), r.reloc, r.addend, target) 148 { 149 continue; 150 } 151 152 // At this time it's expected that all relocations are 153 // handled by `text.resolve_reloc`, and anything that isn't 154 // handled is a bug in `text.resolve_reloc` or something 155 // transitively there. If truly necessary, though, then this 156 // loop could also be updated to forward the relocation to 157 // the final object file as well. 158 panic!( 159 "unresolved relocation could not be processed against \ 160 {:?}: {r:?}", 161 r.reloc_target, 162 ); 163 } 164 165 // Relocations against libcalls are not common at this time and 166 // are only used in non-default configurations that disable wasm 167 // SIMD, disable SSE features, and for wasm modules that still 168 // use floating point operations. 169 // 170 // Currently these relocations are all expected to be absolute 171 // 8-byte relocations so that's asserted here and then encoded 172 // directly into the object as a normal object relocation. This 173 // is processed at module load time to resolve the relocations. 174 RelocationTarget::HostLibcall(call) => { 175 let symbol = *self.libcall_symbols.entry(call).or_insert_with(|| { 176 self.obj.add_symbol(Symbol { 177 name: call.symbol().as_bytes().to_vec(), 178 value: 0, 179 size: 0, 180 kind: SymbolKind::Text, 181 scope: SymbolScope::Linkage, 182 weak: false, 183 section: SymbolSection::Undefined, 184 flags: SymbolFlags::None, 185 }) 186 }); 187 let flags = match r.reloc { 188 Reloc::Abs8 => object::RelocationFlags::Generic { 189 encoding: object::RelocationEncoding::Generic, 190 kind: object::RelocationKind::Absolute, 191 size: 64, 192 }, 193 other => unimplemented!("unimplemented relocation kind {other:?}"), 194 }; 195 self.obj 196 .add_relocation( 197 self.text_section, 198 object::write::Relocation { 199 symbol, 200 flags, 201 offset: off + u64::from(r.offset), 202 addend: r.addend, 203 }, 204 ) 205 .unwrap(); 206 } 207 }; 208 } 209 (symbol_id, off..off + body_len) 210 } 211 212 /// Forces "veneers" to be used for inter-function calls in the text 213 /// section which means that in-bounds optimized addresses are never used. 214 /// 215 /// This is only useful for debugging cranelift itself and typically this 216 /// option is disabled. 217 pub fn force_veneers(&mut self) { 218 self.text.force_veneers(); 219 } 220 221 /// Appends the specified amount of bytes of padding into the text section. 222 /// 223 /// This is only useful when fuzzing and/or debugging cranelift itself and 224 /// for production scenarios `padding` is 0 and this function does nothing. 225 pub fn append_padding(&mut self, padding: usize) { 226 if padding == 0 { 227 return; 228 } 229 self.text 230 .append(false, &vec![0; padding], 1, &mut self.ctrl_plane); 231 } 232 233 /// Indicates that the text section has been written completely and this 234 /// will finish appending it to the original object. 235 /// 236 /// Note that this will also write out the unwind information sections if 237 /// necessary. 238 pub fn finish(mut self) { 239 // Finish up the text section now that we're done adding functions. 240 let text = self.text.finish(&mut self.ctrl_plane); 241 self.obj 242 .section_mut(self.text_section) 243 .set_data(text, self.compiler.page_size_align()); 244 245 // Append the unwind information for all our functions, if necessary. 246 self.unwind_info 247 .append_section(self.compiler, self.obj, self.text_section); 248 } 249 } 250 251 /// Builder used to create unwind information for a set of functions added to a 252 /// text section. 253 #[derive(Default)] 254 struct UnwindInfoBuilder<'a> { 255 windows_xdata: Vec<u8>, 256 windows_pdata: Vec<RUNTIME_FUNCTION>, 257 systemv_unwind_info: Vec<(u64, &'a systemv::UnwindInfo)>, 258 } 259 260 // This is a mirror of `RUNTIME_FUNCTION` in the Windows API, but defined here 261 // to ensure everything is always `u32` and to have it available on all 262 // platforms. Note that all of these specifiers here are relative to a "base 263 // address" which we define as the base of where the text section is eventually 264 // loaded. 265 #[allow(non_camel_case_types)] 266 struct RUNTIME_FUNCTION { 267 begin: u32, 268 end: u32, 269 unwind_address: u32, 270 } 271 272 impl<'a> UnwindInfoBuilder<'a> { 273 /// Pushes the unwind information for a function into this builder. 274 /// 275 /// The function being described must be located at `function_offset` within 276 /// the text section itself, and the function's size is specified by 277 /// `function_len`. 278 /// 279 /// The `info` should come from Cranelift. and is handled here depending on 280 /// its flavor. 281 fn push(&mut self, function_offset: u64, function_len: u64, info: &'a UnwindInfo) { 282 match info { 283 // Windows unwind information is stored in two locations: 284 // 285 // * First is the actual unwinding information which is stored 286 // in the `.xdata` section. This is where `info`'s emitted 287 // information will go into. 288 // * Second are pointers to connect all this unwind information, 289 // stored in the `.pdata` section. The `.pdata` section is an 290 // array of `RUNTIME_FUNCTION` structures. 291 // 292 // Due to how these will be loaded at runtime the `.pdata` isn't 293 // actually assembled byte-wise here. Instead that's deferred to 294 // happen later during `write_windows_unwind_info` which will apply 295 // a further offset to `unwind_address`. 296 // 297 // FIXME: in theory we could "intern" the `unwind_info` value 298 // here within the `.xdata` section. Most of our unwind 299 // information for functions is probably pretty similar in which 300 // case the `.xdata` could be quite small and `.pdata` could 301 // have multiple functions point to the same unwinding 302 // information. 303 UnwindInfo::WindowsX64(info) => { 304 let unwind_size = info.emit_size(); 305 let mut unwind_info = vec![0; unwind_size]; 306 info.emit(&mut unwind_info); 307 308 // `.xdata` entries are always 4-byte aligned 309 while self.windows_xdata.len() % 4 != 0 { 310 self.windows_xdata.push(0x00); 311 } 312 let unwind_address = self.windows_xdata.len(); 313 self.windows_xdata.extend_from_slice(&unwind_info); 314 315 // Record a `RUNTIME_FUNCTION` which this will point to. 316 self.windows_pdata.push(RUNTIME_FUNCTION { 317 begin: u32::try_from(function_offset).unwrap(), 318 end: u32::try_from(function_offset + function_len).unwrap(), 319 unwind_address: u32::try_from(unwind_address).unwrap(), 320 }); 321 } 322 323 // See https://learn.microsoft.com/en-us/cpp/build/arm64-exception-handling 324 UnwindInfo::WindowsArm64(info) => { 325 let code_words = info.code_words(); 326 let mut unwind_codes = vec![0; (code_words * 4) as usize]; 327 info.emit(&mut unwind_codes); 328 329 // `.xdata` entries are always 4-byte aligned 330 while self.windows_xdata.len() % 4 != 0 { 331 self.windows_xdata.push(0x00); 332 } 333 334 // First word: 335 // 0-17: Function Length 336 // 18-19: Version (must be 0) 337 // 20: X bit (is exception data present?) 338 // 21: E bit (has single packed epilogue?) 339 // 22-26: Epilogue count 340 // 27-31: Code words count 341 let requires_extended_counts = code_words > (1 << 5); 342 let encoded_function_len = function_len / 4; 343 assert!(encoded_function_len < (1 << 18), "function too large"); 344 let mut word1 = encoded_function_len as u32; 345 if !requires_extended_counts { 346 word1 |= (code_words as u32) << 27; 347 } 348 let unwind_address = self.windows_xdata.len(); 349 self.windows_xdata.extend_from_slice(&word1.to_le_bytes()); 350 351 if requires_extended_counts { 352 // Extended counts word: 353 // 0-15: Epilogue count 354 // 16-23: Code words count 355 let extended_counts_word = (code_words as u32) << 16; 356 self.windows_xdata 357 .extend_from_slice(&extended_counts_word.to_le_bytes()); 358 } 359 360 // Skip epilogue information: Per comment on [`UnwindInst`], we 361 // do not emit information about epilogues. 362 363 // Emit the unwind codes. 364 self.windows_xdata.extend_from_slice(&unwind_codes); 365 366 // Record a `RUNTIME_FUNCTION` which this will point to. 367 // NOTE: `end` is not used, so leave it as 0. 368 self.windows_pdata.push(RUNTIME_FUNCTION { 369 begin: u32::try_from(function_offset).unwrap(), 370 end: 0, 371 unwind_address: u32::try_from(unwind_address).unwrap(), 372 }); 373 } 374 375 // System-V is different enough that we just record the unwinding 376 // information to get processed at a later time. 377 UnwindInfo::SystemV(info) => { 378 self.systemv_unwind_info.push((function_offset, info)); 379 } 380 381 _ => panic!("some unwind info isn't handled here"), 382 } 383 } 384 385 /// Appends the unwind information section, if any, to the `obj` specified. 386 /// 387 /// This function must be called immediately after the text section was 388 /// added to a builder. The unwind information section must trail the text 389 /// section immediately. 390 /// 391 /// The `text_section`'s section identifier is passed into this function. 392 fn append_section( 393 &self, 394 compiler: &dyn Compiler, 395 obj: &mut Object<'_>, 396 text_section: SectionId, 397 ) { 398 // This write will align the text section to a page boundary and then 399 // return the offset at that point. This gives us the full size of the 400 // text section at that point, after alignment. 401 let text_section_size = 402 obj.append_section_data(text_section, &[], compiler.page_size_align()); 403 404 if self.windows_xdata.len() > 0 { 405 assert!(self.systemv_unwind_info.len() == 0); 406 // The `.xdata` section must come first to be just-after the `.text` 407 // section for the reasons documented in `write_windows_unwind_info` 408 // below. 409 let segment = obj.segment_name(StandardSegment::Data).to_vec(); 410 let xdata_id = obj.add_section(segment, b".xdata".to_vec(), SectionKind::ReadOnlyData); 411 let segment = obj.segment_name(StandardSegment::Data).to_vec(); 412 let pdata_id = obj.add_section(segment, b".pdata".to_vec(), SectionKind::ReadOnlyData); 413 self.write_windows_unwind_info(obj, xdata_id, pdata_id, text_section_size); 414 } 415 416 if self.systemv_unwind_info.len() > 0 { 417 let segment = obj.segment_name(StandardSegment::Data).to_vec(); 418 let section_id = 419 obj.add_section(segment, b".eh_frame".to_vec(), SectionKind::ReadOnlyData); 420 self.write_systemv_unwind_info(compiler, obj, section_id, text_section_size) 421 } 422 } 423 424 /// This function appends a nonstandard section to the object which is only 425 /// used during `CodeMemory::publish`. 426 /// 427 /// This custom section effectively stores a `[RUNTIME_FUNCTION; N]` into 428 /// the object file itself. This way registration of unwind info can simply 429 /// pass this slice to the OS itself and there's no need to recalculate 430 /// anything on the other end of loading a module from a precompiled object. 431 /// 432 /// Support for reading this is in `crates/jit/src/unwind/winx64.rs`. 433 fn write_windows_unwind_info( 434 &self, 435 obj: &mut Object<'_>, 436 xdata_id: SectionId, 437 pdata_id: SectionId, 438 text_section_size: u64, 439 ) { 440 // Append the `.xdata` section, or the actual unwinding information 441 // codes and such which were built as we found unwind information for 442 // functions. 443 obj.append_section_data(xdata_id, &self.windows_xdata, 4); 444 445 // Next append the `.pdata` section, or the array of `RUNTIME_FUNCTION` 446 // structures stored in the binary. 447 // 448 // This memory will be passed at runtime to `RtlAddFunctionTable` which 449 // takes a "base address" and the entries within `RUNTIME_FUNCTION` are 450 // all relative to this base address. The base address we pass is the 451 // address of the text section itself so all the pointers here must be 452 // text-section-relative. The `begin` and `end` fields for the function 453 // it describes are already text-section-relative, but the 454 // `unwind_address` field needs to be updated here since the value 455 // stored right now is `xdata`-section-relative. We know that the 456 // `xdata` section follows the `.text` section so the 457 // `text_section_size` is added in to calculate the final 458 // `.text`-section-relative address of the unwind information. 459 let xdata_rva = |address| { 460 let address = u64::from(address); 461 let address = address + text_section_size; 462 u32::try_from(address).unwrap() 463 }; 464 let pdata = match obj.architecture() { 465 Architecture::X86_64 => { 466 let mut pdata = Vec::with_capacity(self.windows_pdata.len() * 3 * 4); 467 for info in self.windows_pdata.iter() { 468 pdata.extend_from_slice(&info.begin.to_le_bytes()); 469 pdata.extend_from_slice(&info.end.to_le_bytes()); 470 pdata.extend_from_slice(&xdata_rva(info.unwind_address).to_le_bytes()); 471 } 472 pdata 473 } 474 475 Architecture::Aarch64 => { 476 // Windows Arm64 .pdata also supports packed unwind data, but 477 // we're not currently using that. 478 let mut pdata = Vec::with_capacity(self.windows_pdata.len() * 2 * 4); 479 for info in self.windows_pdata.iter() { 480 pdata.extend_from_slice(&info.begin.to_le_bytes()); 481 pdata.extend_from_slice(&xdata_rva(info.unwind_address).to_le_bytes()); 482 } 483 pdata 484 } 485 486 _ => unimplemented!("unsupported architecture for windows unwind info"), 487 }; 488 obj.append_section_data(pdata_id, &pdata, 4); 489 } 490 491 /// This function appends a nonstandard section to the object which is only 492 /// used during `CodeMemory::publish`. 493 /// 494 /// This will generate a `.eh_frame` section, but not one that can be 495 /// naively loaded. The goal of this section is that we can create the 496 /// section once here and never again does it need to change. To describe 497 /// dynamically loaded functions though each individual FDE needs to talk 498 /// about the function's absolute address that it's referencing. Naturally 499 /// we don't actually know the function's absolute address when we're 500 /// creating an object here. 501 /// 502 /// To solve this problem the FDE address encoding mode is set to 503 /// `DW_EH_PE_pcrel`. This means that the actual effective address that the 504 /// FDE describes is a relative to the address of the FDE itself. By 505 /// leveraging this relative-ness we can assume that the relative distance 506 /// between the FDE and the function it describes is constant, which should 507 /// allow us to generate an FDE ahead-of-time here. 508 /// 509 /// For now this assumes that all the code of functions will start at a 510 /// page-aligned address when loaded into memory. The eh_frame encoded here 511 /// then assumes that the text section is itself page aligned to its size 512 /// and the eh_frame will follow just after the text section. This means 513 /// that the relative offsets we're using here is the FDE going backwards 514 /// into the text section itself. 515 /// 516 /// Note that the library we're using to create the FDEs, `gimli`, doesn't 517 /// actually encode addresses relative to the FDE itself. Instead the 518 /// addresses are encoded relative to the start of the `.eh_frame` section. 519 /// This makes it much easier for us where we provide the relative offset 520 /// from the start of `.eh_frame` to the function in the text section, which 521 /// given our layout basically means the offset of the function in the text 522 /// section from the end of the text section. 523 /// 524 /// A final note is that the reason we page-align the text section's size is 525 /// so the .eh_frame lives on a separate page from the text section itself. 526 /// This allows `.eh_frame` to have different virtual memory permissions, 527 /// such as being purely read-only instead of read/execute like the code 528 /// bits. 529 fn write_systemv_unwind_info( 530 &self, 531 compiler: &dyn Compiler, 532 obj: &mut Object<'_>, 533 section_id: SectionId, 534 text_section_size: u64, 535 ) { 536 let mut cie = match compiler.create_systemv_cie() { 537 Some(cie) => cie, 538 None => return, 539 }; 540 let mut table = FrameTable::default(); 541 cie.fde_address_encoding = gimli::constants::DW_EH_PE_pcrel; 542 let cie_id = table.add_cie(cie); 543 544 for (text_section_off, unwind_info) in self.systemv_unwind_info.iter() { 545 let backwards_off = text_section_size - text_section_off; 546 let actual_offset = -i64::try_from(backwards_off).unwrap(); 547 // Note that gimli wants an unsigned 64-bit integer here, but 548 // unwinders just use this constant for a relative addition with the 549 // address of the FDE, which means that the sign doesn't actually 550 // matter. 551 let fde = unwind_info.to_fde(Address::Constant(actual_offset as u64)); 552 table.add_fde(cie_id, fde); 553 } 554 let endian = match compiler.triple().endianness().unwrap() { 555 target_lexicon::Endianness::Little => RunTimeEndian::Little, 556 target_lexicon::Endianness::Big => RunTimeEndian::Big, 557 }; 558 let mut eh_frame = EhFrame(MyVec(EndianVec::new(endian))); 559 table.write_eh_frame(&mut eh_frame).unwrap(); 560 561 // Some unwinding implementations expect a terminating "empty" length so 562 // a 0 is written at the end of the table for those implementations. 563 let mut endian_vec = (eh_frame.0).0; 564 endian_vec.write_u32(0).unwrap(); 565 obj.append_section_data(section_id, endian_vec.slice(), 1); 566 567 use gimli::constants; 568 use gimli::write::Error; 569 570 struct MyVec(EndianVec<RunTimeEndian>); 571 572 impl Writer for MyVec { 573 type Endian = RunTimeEndian; 574 575 fn endian(&self) -> RunTimeEndian { 576 self.0.endian() 577 } 578 579 fn len(&self) -> usize { 580 self.0.len() 581 } 582 583 fn write(&mut self, buf: &[u8]) -> Result<(), Error> { 584 self.0.write(buf) 585 } 586 587 fn write_at(&mut self, pos: usize, buf: &[u8]) -> Result<(), Error> { 588 self.0.write_at(pos, buf) 589 } 590 591 // FIXME(gimli-rs/gimli#576) this is the definition we want for 592 // `write_eh_pointer` but the default implementation, at the time 593 // of this writing, uses `offset - val` instead of `val - offset`. 594 // A PR has been merged to fix this but until that's published we 595 // can't use it. 596 fn write_eh_pointer( 597 &mut self, 598 address: Address, 599 eh_pe: constants::DwEhPe, 600 size: u8, 601 ) -> Result<(), Error> { 602 let val = match address { 603 Address::Constant(val) => val, 604 Address::Symbol { .. } => unreachable!(), 605 }; 606 assert_eq!(eh_pe.application(), constants::DW_EH_PE_pcrel); 607 let offset = self.len() as u64; 608 let val = val.wrapping_sub(offset); 609 self.write_eh_pointer_data(val, eh_pe.format(), size) 610 } 611 } 612 } 613 } 614