1 use core::{ 2 cmp::min, 3 intrinsics::{likely, unlikely}, 4 ops::Range, 5 }; 6 7 use alloc::vec::Vec; 8 use elf::{endian::AnyEndian, file::FileHeader, segment::ProgramHeader}; 9 10 use crate::{ 11 arch::MMArch, 12 driver::base::block::SeekFrom, 13 kerror, 14 libs::align::page_align_up, 15 mm::{ 16 allocator::page_frame::{PageFrameCount, VirtPageFrame}, 17 syscall::{MapFlags, ProtFlags}, 18 ucontext::InnerAddressSpace, 19 MemoryManagementArch, VirtAddr, 20 }, 21 process::{ 22 abi::AtType, 23 exec::{BinaryLoader, BinaryLoaderResult, ExecError, ExecLoadMode, ExecParam}, 24 ProcessManager, 25 }, 26 syscall::{ 27 user_access::{clear_user, copy_to_user}, 28 SystemError, 29 }, 30 }; 31 32 use super::rwlock::RwLockWriteGuard; 33 34 #[derive(Debug)] 35 pub struct ElfLoader; 36 37 pub const ELF_LOADER: ElfLoader = ElfLoader::new(); 38 39 impl ElfLoader { 40 #[cfg(target_arch = "x86_64")] 41 pub const ELF_PAGE_SIZE: usize = MMArch::PAGE_SIZE; 42 43 /// 读取文件的缓冲区大小 44 pub const FILE_READ_BUF_SIZE: usize = 512 * 1024; 45 46 pub const fn new() -> Self { 47 Self 48 } 49 50 #[cfg(target_arch = "x86_64")] 51 pub fn probe_x86_64( 52 &self, 53 param: &ExecParam, 54 ehdr: &FileHeader<AnyEndian>, 55 ) -> Result<(), ExecError> { 56 // 只支持 64 位的 ELF 文件 57 if ehdr.class != elf::file::Class::ELF64 { 58 return Err(ExecError::WrongArchitecture); 59 } 60 61 // 判断架构是否匹配 62 if ElfMachine::from(ehdr.e_machine) != ElfMachine::X86_64 { 63 return Err(ExecError::WrongArchitecture); 64 } 65 66 // 判断是否以可执行文件的形式加载 67 if param.load_mode() == ExecLoadMode::Exec { 68 // 检查文件类型是否为可执行文件 69 if ElfType::from(ehdr.e_type) != ElfType::Executable { 70 return Err(ExecError::NotExecutable); 71 } 72 } else { 73 return Err(ExecError::NotSupported); 74 } 75 76 return Ok(()); 77 } 78 79 /// 设置用户堆空间,映射[start, end)区间的虚拟地址,并把brk指针指向end 80 /// 81 /// ## 参数 82 /// 83 /// - `user_vm_guard` - 用户虚拟地址空间 84 /// - `start` - 本次映射的起始地址 85 /// - `end` - 本次映射的结束地址(不包含) 86 /// - `prot_flags` - 本次映射的权限 87 fn set_elf_brk( 88 &self, 89 user_vm_guard: &mut RwLockWriteGuard<'_, InnerAddressSpace>, 90 start: VirtAddr, 91 end: VirtAddr, 92 prot_flags: ProtFlags, 93 ) -> Result<(), ExecError> { 94 let start = self.elf_page_start(start); 95 let end = self.elf_page_align_up(end); 96 97 if end > start { 98 let r = user_vm_guard.map_anonymous( 99 start, 100 end - start, 101 prot_flags, 102 MapFlags::MAP_ANONYMOUS | MapFlags::MAP_FIXED_NOREPLACE, 103 false, 104 ); 105 if r.is_err() { 106 kerror!("set_elf_brk: map_anonymous failed, err={:?}", r); 107 return Err(ExecError::OutOfMemory); 108 } 109 } 110 user_vm_guard.elf_brk_start = end; 111 user_vm_guard.elf_brk = end; 112 return Ok(()); 113 } 114 115 /// 计算addr在ELF PAGE内的偏移 116 fn elf_page_offset(&self, addr: VirtAddr) -> usize { 117 addr.data() & (Self::ELF_PAGE_SIZE - 1) 118 } 119 120 fn elf_page_start(&self, addr: VirtAddr) -> VirtAddr { 121 VirtAddr::new(addr.data() & (!(Self::ELF_PAGE_SIZE - 1))) 122 } 123 124 fn elf_page_align_up(&self, addr: VirtAddr) -> VirtAddr { 125 VirtAddr::new((addr.data() + Self::ELF_PAGE_SIZE - 1) & (!(Self::ELF_PAGE_SIZE - 1))) 126 } 127 128 /// 根据ELF的p_flags生成对应的ProtFlags 129 fn make_prot(&self, p_flags: u32, _has_interpreter: bool, _is_interpreter: bool) -> ProtFlags { 130 let mut prot = ProtFlags::empty(); 131 if p_flags & elf::abi::PF_R != 0 { 132 prot |= ProtFlags::PROT_READ; 133 } 134 if p_flags & elf::abi::PF_W != 0 { 135 prot |= ProtFlags::PROT_WRITE; 136 } 137 if p_flags & elf::abi::PF_X != 0 { 138 prot |= ProtFlags::PROT_EXEC; 139 } 140 141 // todo: 增加与架构相关的处理 142 // ref: https://opengrok.ringotek.cn/xref/linux-5.19.10/fs/binfmt_elf.c?r=&mo=22652&fi=824#572 143 144 return prot; 145 } 146 147 /// 加载ELF文件到用户空间 148 /// 149 /// 参考Linux的elf_map函数 150 /// https://opengrok.ringotek.cn/xref/linux-5.19.10/fs/binfmt_elf.c?r=&mo=22652&fi=824#365 151 /// ## 参数 152 /// 153 /// - `user_vm_guard`:用户空间地址空间 154 /// - `param`:执行参数 155 /// - `phent`:ELF文件的ProgramHeader 156 /// - `addr_to_map`:当前段应该被加载到的内存地址 157 /// - `prot`:保护标志 158 /// - `map_flags`:映射标志 159 /// - `total_size`:ELF文件的总大小 160 /// 161 /// ## 返回值 162 /// 163 /// - `Ok((VirtAddr, bool))`:如果成功加载,则bool值为true,否则为false. VirtAddr为加载的地址 164 fn load_elf_segment( 165 &self, 166 user_vm_guard: &mut RwLockWriteGuard<'_, InnerAddressSpace>, 167 param: &mut ExecParam, 168 phent: &ProgramHeader, 169 mut addr_to_map: VirtAddr, 170 prot: &ProtFlags, 171 map_flags: &MapFlags, 172 total_size: usize, 173 ) -> Result<(VirtAddr, bool), SystemError> { 174 // kdebug!("load_elf_segment: addr_to_map={:?}", addr_to_map); 175 176 // 映射位置的偏移量(页内偏移) 177 let beginning_page_offset = self.elf_page_offset(addr_to_map); 178 addr_to_map = self.elf_page_start(addr_to_map); 179 // 计算要映射的内存的大小 180 let map_size = phent.p_filesz as usize + beginning_page_offset; 181 let map_size = self.elf_page_align_up(VirtAddr::new(map_size)).data(); 182 // 当前段在文件中的大小 183 let seg_in_file_size = phent.p_filesz as usize; 184 // 当前段在文件中的偏移量 185 let file_offset = phent.p_offset as usize; 186 187 // 如果当前段的大小为0,则直接返回. 188 // 段在文件中的大小为0,是合法的,但是段在内存中的大小不能为0 189 if map_size == 0 { 190 return Ok((addr_to_map, true)); 191 } 192 193 let map_err_handler = |err: SystemError| { 194 if err == SystemError::EEXIST { 195 kerror!( 196 "Pid: {:?}, elf segment at {:p} overlaps with existing mapping", 197 ProcessManager::current_pcb().pid(), 198 addr_to_map.as_ptr::<u8>() 199 ); 200 } 201 err 202 }; 203 // 由于后面需要把ELF文件的内容加载到内存,因此暂时把当前段的权限设置为可写 204 let tmp_prot = if !prot.contains(ProtFlags::PROT_WRITE) { 205 *prot | ProtFlags::PROT_WRITE 206 } else { 207 *prot 208 }; 209 210 // 映射到的虚拟地址。请注意,这个虚拟地址是user_vm_guard这个地址空间的虚拟地址。不一定是当前进程地址空间的 211 let map_addr: VirtAddr; 212 213 // total_size is the size of the ELF (interpreter) image. 214 // The _first_ mmap needs to know the full size, otherwise 215 // randomization might put this image into an overlapping 216 // position with the ELF binary image. (since size < total_size) 217 // So we first map the 'big' image - and unmap the remainder at 218 // the end. (which unmap is needed for ELF images with holes.) 219 if total_size != 0 { 220 let total_size = self.elf_page_align_up(VirtAddr::new(total_size)).data(); 221 222 // kdebug!("total_size={}", total_size); 223 224 map_addr = user_vm_guard 225 .map_anonymous(addr_to_map, total_size, tmp_prot, *map_flags, false) 226 .map_err(map_err_handler)? 227 .virt_address(); 228 // kdebug!("map ok: addr_to_map={:?}", addr_to_map); 229 230 let to_unmap = map_addr + map_size; 231 let to_unmap_size = total_size - map_size; 232 233 // kdebug!("to_unmap={:?}, to_unmap_size={}", to_unmap, to_unmap_size); 234 user_vm_guard.munmap( 235 VirtPageFrame::new(to_unmap), 236 PageFrameCount::from_bytes(to_unmap_size).unwrap(), 237 )?; 238 239 // 加载文件到内存 240 self.do_load_file( 241 map_addr + beginning_page_offset, 242 seg_in_file_size, 243 file_offset, 244 param, 245 )?; 246 if tmp_prot != *prot { 247 user_vm_guard.mprotect( 248 VirtPageFrame::new(map_addr), 249 PageFrameCount::from_bytes(page_align_up(map_size)).unwrap(), 250 *prot, 251 )?; 252 } 253 } else { 254 // kdebug!("total size = 0"); 255 256 map_addr = user_vm_guard 257 .map_anonymous(addr_to_map, map_size, tmp_prot, *map_flags, false)? 258 .virt_address(); 259 // kdebug!( 260 // "map ok: addr_to_map={:?}, map_addr={map_addr:?},beginning_page_offset={beginning_page_offset:?}", 261 // addr_to_map 262 // ); 263 264 // 加载文件到内存 265 self.do_load_file( 266 map_addr + beginning_page_offset, 267 seg_in_file_size, 268 file_offset, 269 param, 270 )?; 271 272 if tmp_prot != *prot { 273 user_vm_guard.mprotect( 274 VirtPageFrame::new(map_addr), 275 PageFrameCount::from_bytes(page_align_up(map_size)).unwrap(), 276 *prot, 277 )?; 278 } 279 } 280 // kdebug!("load_elf_segment OK: map_addr={:?}", map_addr); 281 return Ok((map_addr, true)); 282 } 283 284 /// 加载ELF文件到用户空间 285 /// 286 /// ## 参数 287 /// 288 /// - `vaddr`:要加载到的虚拟地址 289 /// - `size`:要加载的大小 290 /// - `offset_in_file`:在文件内的偏移量 291 /// - `param`:执行参数 292 fn do_load_file( 293 &self, 294 mut vaddr: VirtAddr, 295 size: usize, 296 offset_in_file: usize, 297 param: &mut ExecParam, 298 ) -> Result<(), SystemError> { 299 let file = param.file_mut(); 300 if (file.metadata()?.size as usize) < offset_in_file + size { 301 return Err(SystemError::ENOEXEC); 302 } 303 let buf_size = min(size, Self::FILE_READ_BUF_SIZE); 304 let mut buf = vec![0u8; buf_size]; 305 306 let mut remain = size; 307 308 file.lseek(SeekFrom::SeekSet(offset_in_file as i64))?; 309 310 while remain > 0 { 311 let read_size = min(remain, buf_size); 312 file.read(read_size, &mut buf[..read_size])?; 313 // kdebug!("copy_to_user: vaddr={:?}, read_size = {read_size}", vaddr); 314 unsafe { 315 copy_to_user(vaddr, &buf[..read_size]).map_err(|_| SystemError::EFAULT)?; 316 } 317 318 vaddr += read_size; 319 remain -= read_size; 320 } 321 return Ok(()); 322 } 323 324 /// 我们需要显式的把数据段之后剩余的内存页都清零。 325 fn pad_zero(&self, elf_bss: VirtAddr) -> Result<(), SystemError> { 326 let nbyte = self.elf_page_offset(elf_bss); 327 if nbyte > 0 { 328 let nbyte = Self::ELF_PAGE_SIZE - nbyte; 329 unsafe { clear_user(elf_bss, nbyte).map_err(|_| SystemError::EFAULT) }?; 330 } 331 return Ok(()); 332 } 333 334 /// 创建auxv 335 /// 336 /// ## 参数 337 /// 338 /// - `param`:执行参数 339 /// - `entrypoint_vaddr`:程序入口地址 340 /// - `phdr_vaddr`:程序头表地址 341 /// - `elf_header`:ELF文件头 342 fn create_auxv( 343 &self, 344 param: &mut ExecParam, 345 entrypoint_vaddr: VirtAddr, 346 phdr_vaddr: Option<VirtAddr>, 347 ehdr: &elf::file::FileHeader<AnyEndian>, 348 ) -> Result<(), ExecError> { 349 let phdr_vaddr = phdr_vaddr.unwrap_or(VirtAddr::new(0)); 350 351 let init_info = param.init_info_mut(); 352 init_info 353 .auxv 354 .insert(AtType::PhEnt as u8, ehdr.e_phentsize as usize); 355 init_info 356 .auxv 357 .insert(AtType::PageSize as u8, MMArch::PAGE_SIZE); 358 init_info.auxv.insert(AtType::Phdr as u8, phdr_vaddr.data()); 359 init_info 360 .auxv 361 .insert(AtType::PhNum as u8, ehdr.e_phnum as usize); 362 init_info 363 .auxv 364 .insert(AtType::Entry as u8, entrypoint_vaddr.data()); 365 366 return Ok(()); 367 } 368 369 /// 解析文件的ehdr 370 fn parse_ehdr(data: &[u8]) -> Result<FileHeader<AnyEndian>, elf::ParseError> { 371 let ident_buf = data.get_bytes(0..elf::abi::EI_NIDENT)?; 372 let ident = elf::file::parse_ident::<AnyEndian>(ident_buf)?; 373 374 let tail_start = elf::abi::EI_NIDENT; 375 let tail_end = match ident.1 { 376 elf::file::Class::ELF32 => tail_start + elf::file::ELF32_EHDR_TAILSIZE, 377 elf::file::Class::ELF64 => tail_start + elf::file::ELF64_EHDR_TAILSIZE, 378 }; 379 let tail_buf = data.get_bytes(tail_start..tail_end)?; 380 381 let ehdr: FileHeader<_> = FileHeader::parse_tail(ident, tail_buf)?; 382 return Ok(ehdr); 383 } 384 385 /// 解析文件的program header table 386 /// 387 /// ## 参数 388 /// 389 /// - `param`:执行参数 390 /// - `ehdr`:文件头 391 /// - `data_buf`:用于缓存SegmentTable的Vec。 392 /// 这是因为SegmentTable的生命周期与data_buf一致。初始化这个Vec的大小为0即可。 393 /// 394 /// ## 说明 395 /// 396 /// 这个函数由elf库的`elf::elf_bytes::find_phdrs`修改而来。 397 fn parse_segments<'a>( 398 param: &mut ExecParam, 399 ehdr: &FileHeader<AnyEndian>, 400 data_buf: &'a mut Vec<u8>, 401 ) -> Result<Option<elf::segment::SegmentTable<'a, AnyEndian>>, elf::ParseError> { 402 // It's Ok to have no program headers 403 if ehdr.e_phoff == 0 { 404 return Ok(None); 405 } 406 let file = param.file_mut(); 407 // If the number of segments is greater than or equal to PN_XNUM (0xffff), 408 // e_phnum is set to PN_XNUM, and the actual number of program header table 409 // entries is contained in the sh_info field of the section header at index 0. 410 let mut phnum = ehdr.e_phnum as usize; 411 if phnum == elf::abi::PN_XNUM as usize { 412 let shoff: usize = ehdr.e_shoff.try_into()?; 413 414 // 从磁盘读取shdr的前2个entry 415 file.lseek(SeekFrom::SeekSet(shoff as i64)) 416 .map_err(|_| elf::ParseError::BadOffset(shoff as u64))?; 417 let shdr_buf_size = ehdr.e_shentsize * 2; 418 let mut shdr_buf = vec![0u8; shdr_buf_size as usize]; 419 file.read(shdr_buf_size as usize, &mut shdr_buf) 420 .map_err(|_| elf::ParseError::BadOffset(shoff as u64))?; 421 422 let mut offset = 0; 423 let shdr0 = <elf::section::SectionHeader as elf::parse::ParseAt>::parse_at( 424 ehdr.endianness, 425 ehdr.class, 426 &mut offset, 427 &shdr_buf, 428 )?; 429 phnum = shdr0.sh_info.try_into()?; 430 } 431 432 // Validate phentsize before trying to read the table so that we can error early for corrupted files 433 let entsize = <ProgramHeader as elf::parse::ParseAt>::validate_entsize( 434 ehdr.class, 435 ehdr.e_phentsize as usize, 436 )?; 437 let phoff: usize = ehdr.e_phoff.try_into()?; 438 let size = entsize 439 .checked_mul(phnum) 440 .ok_or(elf::ParseError::IntegerOverflow)?; 441 phoff 442 .checked_add(size) 443 .ok_or(elf::ParseError::IntegerOverflow)?; 444 445 // 读取program header table 446 447 file.lseek(SeekFrom::SeekSet(phoff as i64)) 448 .map_err(|_| elf::ParseError::BadOffset(phoff as u64))?; 449 data_buf.clear(); 450 data_buf.resize(size, 0); 451 452 file.read(size, data_buf) 453 .expect("read program header table failed"); 454 let buf = data_buf.get_bytes(0..size)?; 455 456 return Ok(Some(elf::segment::SegmentTable::new( 457 ehdr.endianness, 458 ehdr.class, 459 buf, 460 ))); 461 } 462 } 463 464 impl BinaryLoader for ElfLoader { 465 fn probe(self: &'static Self, param: &ExecParam, buf: &[u8]) -> Result<(), ExecError> { 466 // let elf_bytes = 467 // ElfBytes::<AnyEndian>::minimal_parse(buf).map_err(|_| ExecError::NotExecutable)?; 468 469 let ehdr = Self::parse_ehdr(buf).map_err(|_| ExecError::NotExecutable)?; 470 471 #[cfg(target_arch = "x86_64")] 472 return self.probe_x86_64(param, &ehdr); 473 474 #[cfg(not(target_arch = "x86_64"))] 475 unimplemented!("Unsupported architecture"); 476 } 477 478 fn load( 479 self: &'static Self, 480 param: &mut ExecParam, 481 head_buf: &[u8], 482 ) -> Result<BinaryLoaderResult, ExecError> { 483 // 解析elf文件头 484 let ehdr = Self::parse_ehdr(head_buf).map_err(|_| ExecError::NotExecutable)?; 485 486 // 参考linux-5.19的load_elf_binary函数 487 // https://opengrok.ringotek.cn/xref/linux-5.19.10/fs/binfmt_elf.c?r=&mo=22652&fi=824#1034 488 489 let elf_type = ElfType::from(ehdr.e_type); 490 // kdebug!("ehdr = {:?}", ehdr); 491 492 let binding = param.vm().clone(); 493 let mut user_vm = binding.write(); 494 495 // todo: 增加对user stack上的内存是否具有可执行权限的处理(方法:寻找phdr里面的PT_GNU_STACK段) 496 497 // todo: 增加对动态链接的处理 498 499 // kdebug!("to parse segments"); 500 // 加载ELF文件并映射到用户空间 501 let mut phdr_buf = Vec::new(); 502 let loadable_sections = Self::parse_segments(param, &ehdr, &mut phdr_buf) 503 .map_err(|_| ExecError::ParseError)? 504 .ok_or(ExecError::ParseError)? 505 .iter() 506 .filter(|seg| seg.p_type == elf::abi::PT_LOAD); 507 508 // kdebug!("loadable_sections = {:?}", loadable_sections); 509 510 let mut elf_brk = VirtAddr::new(0); 511 let mut elf_bss = VirtAddr::new(0); 512 let mut start_code: Option<VirtAddr> = None; 513 let mut end_code: Option<VirtAddr> = None; 514 let mut start_data: Option<VirtAddr> = None; 515 let mut end_data: Option<VirtAddr> = None; 516 517 // 加载的时候的偏移量(这个偏移量在加载动态链接段的时候产生,由于还没有动态链接,因此暂时不可变。) 518 // 请不要删除load_bias! 以免到时候写动态链接的时候忘记了。 519 let load_bias = 0usize; 520 let mut bss_prot_flags = ProtFlags::empty(); 521 // 是否是第一个加载的段 522 let mut first_pt_load = true; 523 // program header的虚拟地址 524 let mut phdr_vaddr: Option<VirtAddr> = None; 525 for seg_to_load in loadable_sections { 526 // kdebug!("seg_to_load = {:?}", seg_to_load); 527 if unlikely(elf_brk > elf_bss) { 528 // kdebug!( 529 // "to set brk, elf_brk = {:?}, elf_bss = {:?}", 530 // elf_brk, 531 // elf_bss 532 // ); 533 self.set_elf_brk( 534 &mut user_vm, 535 elf_bss + load_bias, 536 elf_brk + load_bias, 537 bss_prot_flags, 538 )?; 539 let nbyte = self.elf_page_offset(elf_bss); 540 if nbyte > 0 { 541 let nbyte = min(Self::ELF_PAGE_SIZE - nbyte, elf_brk - elf_bss); 542 unsafe { 543 // This bss-zeroing can fail if the ELF file specifies odd protections. 544 // So we don't check the return value. 545 clear_user(elf_bss + load_bias, nbyte).ok(); 546 } 547 } 548 } 549 550 // 生成ProtFlags. 551 // TODO: 当有了动态链接之后,需要根据情况设置这里的has_interpreter 552 let elf_prot_flags = self.make_prot(seg_to_load.p_flags, false, false); 553 554 let mut elf_map_flags = MapFlags::MAP_PRIVATE; 555 556 let vaddr = VirtAddr::new(seg_to_load.p_vaddr as usize); 557 558 if !first_pt_load { 559 elf_map_flags.insert(MapFlags::MAP_FIXED_NOREPLACE); 560 } else if elf_type == ElfType::Executable { 561 /* 562 * This logic is run once for the first LOAD Program 563 * Header for ET_EXEC binaries. No special handling 564 * is needed. 565 */ 566 elf_map_flags.insert(MapFlags::MAP_FIXED_NOREPLACE); 567 } else if elf_type == ElfType::DSO { 568 // TODO: 支持动态链接 569 unimplemented!("DragonOS currently does not support dynamic linking!"); 570 } 571 572 // 加载这个段到用户空间 573 // todo: 引入动态链接后,这里的total_size要按照实际的填写,而不一定是0 574 575 let e = self 576 .load_elf_segment( 577 &mut user_vm, 578 param, 579 &seg_to_load, 580 vaddr + load_bias, 581 &elf_prot_flags, 582 &elf_map_flags, 583 0, 584 ) 585 .map_err(|e| match e { 586 SystemError::EFAULT => ExecError::BadAddress(None), 587 SystemError::ENOMEM => ExecError::OutOfMemory, 588 _ => ExecError::Other(format!("load_elf_segment failed: {:?}", e)), 589 })?; 590 591 // 如果地址不对,那么就报错 592 if !e.1 { 593 return Err(ExecError::BadAddress(Some(e.0))); 594 } 595 596 if first_pt_load { 597 first_pt_load = false; 598 if elf_type == ElfType::DSO { 599 // todo: 在这里增加对load_bias和reloc_func_desc的更新代码 600 todo!() 601 } 602 } 603 604 // kdebug!("seg_to_load.p_offset={}", seg_to_load.p_offset); 605 // kdebug!("e_phoff={}", ehdr.e_phoff); 606 // kdebug!("seg_to_load.p_filesz={}", seg_to_load.p_filesz); 607 // Figure out which segment in the file contains the Program Header Table, 608 // and map to the associated virtual address. 609 if (seg_to_load.p_offset <= ehdr.e_phoff) 610 && (ehdr.e_phoff < (seg_to_load.p_offset + seg_to_load.p_filesz)) 611 { 612 phdr_vaddr = Some(VirtAddr::new( 613 (ehdr.e_phoff - seg_to_load.p_offset + seg_to_load.p_vaddr) as usize, 614 )); 615 } 616 617 let p_vaddr = VirtAddr::new(seg_to_load.p_vaddr as usize); 618 if (seg_to_load.p_flags & elf::abi::PF_X) != 0 { 619 if start_code.is_none() || start_code.as_ref().unwrap() > &p_vaddr { 620 start_code = Some(p_vaddr); 621 } 622 } 623 624 if start_data.is_none() 625 || (start_data.is_some() && start_data.as_ref().unwrap() > &p_vaddr) 626 { 627 start_data = Some(p_vaddr); 628 } 629 630 // 如果程序段要加载的目标地址不在用户空间内,或者是其他不合法的情况,那么就报错 631 if !p_vaddr.check_user() 632 || seg_to_load.p_filesz > seg_to_load.p_memsz 633 || seg_to_load.p_memsz > MMArch::USER_END_VADDR.data() as u64 634 { 635 // kdebug!("ERR: p_vaddr={p_vaddr:?}"); 636 return Err(ExecError::InvalidParemeter); 637 } 638 639 drop(p_vaddr); 640 641 // end vaddr of this segment(code+data+bss) 642 let seg_end_vaddr_f = self.elf_page_align_up(VirtAddr::new( 643 (seg_to_load.p_vaddr + seg_to_load.p_filesz) as usize, 644 )); 645 646 if seg_end_vaddr_f > elf_bss { 647 elf_bss = seg_end_vaddr_f; 648 } 649 650 if ((seg_to_load.p_flags & elf::abi::PF_X) != 0) 651 && (end_code.is_none() 652 || (end_code.is_some() && end_code.as_ref().unwrap() < &seg_end_vaddr_f)) 653 { 654 end_code = Some(seg_end_vaddr_f); 655 } 656 657 if end_data.is_none() 658 || (end_data.is_some() && end_data.as_ref().unwrap() < &seg_end_vaddr_f) 659 { 660 end_data = Some(seg_end_vaddr_f); 661 } 662 663 drop(seg_end_vaddr_f); 664 665 let seg_end_vaddr = VirtAddr::new((seg_to_load.p_vaddr + seg_to_load.p_memsz) as usize); 666 667 if seg_end_vaddr > elf_brk { 668 bss_prot_flags = elf_prot_flags; 669 elf_brk = seg_end_vaddr; 670 } 671 } 672 // kdebug!("elf load: phdr_vaddr={phdr_vaddr:?}"); 673 let program_entrypoint = VirtAddr::new(ehdr.e_entry as usize + load_bias); 674 let phdr_vaddr = if phdr_vaddr.is_some() { 675 Some(phdr_vaddr.unwrap() + load_bias) 676 } else { 677 None 678 }; 679 680 elf_bss += load_bias; 681 elf_brk += load_bias; 682 start_code = start_code.map(|v| v + load_bias); 683 end_code = end_code.map(|v| v + load_bias); 684 start_data = start_data.map(|v| v + load_bias); 685 end_data = end_data.map(|v| v + load_bias); 686 687 // kdebug!( 688 // "to set brk: elf_bss: {:?}, elf_brk: {:?}, bss_prot_flags: {:?}", 689 // elf_bss, 690 // elf_brk, 691 // bss_prot_flags 692 // ); 693 self.set_elf_brk(&mut user_vm, elf_bss, elf_brk, bss_prot_flags)?; 694 695 if likely(elf_bss != elf_brk) && unlikely(self.pad_zero(elf_bss).is_err()) { 696 // kdebug!("elf_bss = {elf_bss:?}, elf_brk = {elf_brk:?}"); 697 return Err(ExecError::BadAddress(Some(elf_bss))); 698 } 699 // todo: 动态链接:增加加载interpreter的代码 700 // kdebug!("to create auxv"); 701 702 self.create_auxv(param, program_entrypoint, phdr_vaddr, &ehdr)?; 703 704 // kdebug!("auxv create ok"); 705 user_vm.start_code = start_code.unwrap_or(VirtAddr::new(0)); 706 user_vm.end_code = end_code.unwrap_or(VirtAddr::new(0)); 707 user_vm.start_data = start_data.unwrap_or(VirtAddr::new(0)); 708 user_vm.end_data = end_data.unwrap_or(VirtAddr::new(0)); 709 710 let result = BinaryLoaderResult::new(program_entrypoint); 711 // kdebug!("elf load OK!!!"); 712 return Ok(result); 713 } 714 } 715 716 /// Elf机器架构,对应于e_machine字段。在ABI中,以EM_开头的常量是e_machine字段的值。 717 #[derive(Debug, Eq, PartialEq)] 718 pub enum ElfMachine { 719 I386, 720 AArch32, 721 AArch64, 722 X86_64, 723 RiscV, 724 /// 龙芯架构 725 LoongArch, 726 /// 未知架构 727 Unknown, 728 } 729 730 impl From<u16> for ElfMachine { 731 fn from(machine: u16) -> Self { 732 match machine { 733 0x03 => Self::I386, 734 0x28 => Self::AArch32, 735 0xb7 => Self::AArch64, 736 0x3e => Self::X86_64, 737 0xf3 => Self::RiscV, 738 0x102 => Self::LoongArch, 739 // 未知架构 740 _ => Self::Unknown, 741 } 742 } 743 } 744 745 /// Elf文件类型,对应于e_type字段。在ABI中,以ET_开头的常量是e_type字段的值。 746 #[derive(Debug, Eq, PartialEq)] 747 pub enum ElfType { 748 /// 可重定位文件 749 Relocatable, 750 /// 可执行文件 751 Executable, 752 /// 动态链接库 753 DSO, 754 /// 核心转储文件 755 Core, 756 /// 未知类型 757 Unknown, 758 } 759 760 impl From<u16> for ElfType { 761 fn from(elf_type: u16) -> Self { 762 match elf_type { 763 0x01 => Self::Relocatable, 764 0x02 => Self::Executable, 765 0x03 => Self::DSO, 766 0x04 => Self::Core, 767 _ => Self::Unknown, 768 } 769 } 770 } 771 772 // Simple convenience extension trait to wrap get() with .ok_or(SliceReadError) 773 trait ReadBytesExt<'data> { 774 fn get_bytes(self, range: Range<usize>) -> Result<&'data [u8], elf::ParseError>; 775 } 776 impl<'data> ReadBytesExt<'data> for &'data [u8] { 777 fn get_bytes(self, range: Range<usize>) -> Result<&'data [u8], elf::ParseError> { 778 let start = range.start; 779 let end = range.end; 780 self.get(range) 781 .ok_or(elf::ParseError::SliceReadError((start, end))) 782 } 783 } 784