140fe15e0SLoGin use core::{ 2*a02ce654SChiichen cmp::{max, min}, 3*a02ce654SChiichen fmt::Debug, 440fe15e0SLoGin intrinsics::{likely, unlikely}, 540fe15e0SLoGin ops::Range, 640fe15e0SLoGin }; 740fe15e0SLoGin 840fe15e0SLoGin use alloc::vec::Vec; 9*a02ce654SChiichen use elf::{ 10*a02ce654SChiichen abi::{PT_GNU_PROPERTY, PT_INTERP}, 11*a02ce654SChiichen endian::AnyEndian, 12*a02ce654SChiichen file::FileHeader, 13*a02ce654SChiichen segment::ProgramHeader, 14*a02ce654SChiichen }; 1591e9d4abSLoGin use system_error::SystemError; 1640fe15e0SLoGin 1740fe15e0SLoGin use crate::{ 18*a02ce654SChiichen arch::{CurrentElfArch, MMArch}, 19b087521eSChiichen driver::base::block::SeekFrom, 20*a02ce654SChiichen filesystem::vfs::file::File, 2140fe15e0SLoGin kerror, 2240fe15e0SLoGin libs::align::page_align_up, 2340fe15e0SLoGin mm::{ 2440fe15e0SLoGin allocator::page_frame::{PageFrameCount, VirtPageFrame}, 2540fe15e0SLoGin syscall::{MapFlags, ProtFlags}, 2640fe15e0SLoGin ucontext::InnerAddressSpace, 2740fe15e0SLoGin MemoryManagementArch, VirtAddr, 2840fe15e0SLoGin }, 2940fe15e0SLoGin process::{ 3040fe15e0SLoGin abi::AtType, 3140fe15e0SLoGin exec::{BinaryLoader, BinaryLoaderResult, ExecError, ExecLoadMode, ExecParam}, 32*a02ce654SChiichen ProcessFlags, ProcessManager, 3340fe15e0SLoGin }, 3491e9d4abSLoGin syscall::user_access::{clear_user, copy_to_user}, 3540fe15e0SLoGin }; 3640fe15e0SLoGin 3740fe15e0SLoGin use super::rwlock::RwLockWriteGuard; 3840fe15e0SLoGin 39*a02ce654SChiichen // 存放跟架构相关的Elf属性, 40*a02ce654SChiichen pub trait ElfArch: Clone + Copy + Debug { 41*a02ce654SChiichen const ELF_ET_DYN_BASE: usize; 42*a02ce654SChiichen const ELF_PAGE_SIZE: usize; 43*a02ce654SChiichen } 44*a02ce654SChiichen 4540fe15e0SLoGin #[derive(Debug)] 4640fe15e0SLoGin pub struct ElfLoader; 4740fe15e0SLoGin 4840fe15e0SLoGin pub const ELF_LOADER: ElfLoader = ElfLoader::new(); 4940fe15e0SLoGin 5040fe15e0SLoGin impl ElfLoader { 5140fe15e0SLoGin /// 读取文件的缓冲区大小 5240fe15e0SLoGin pub const FILE_READ_BUF_SIZE: usize = 512 * 1024; 5340fe15e0SLoGin 5440fe15e0SLoGin pub const fn new() -> Self { 5540fe15e0SLoGin Self 5640fe15e0SLoGin } 5740fe15e0SLoGin 584fda81ceSLoGin fn inner_probe_common( 5940fe15e0SLoGin &self, 6040fe15e0SLoGin param: &ExecParam, 6140fe15e0SLoGin ehdr: &FileHeader<AnyEndian>, 6240fe15e0SLoGin ) -> Result<(), ExecError> { 6340fe15e0SLoGin // 只支持 64 位的 ELF 文件 6440fe15e0SLoGin if ehdr.class != elf::file::Class::ELF64 { 6540fe15e0SLoGin return Err(ExecError::WrongArchitecture); 6640fe15e0SLoGin } 6740fe15e0SLoGin 6840fe15e0SLoGin // 判断是否以可执行文件的形式加载 6940fe15e0SLoGin if param.load_mode() == ExecLoadMode::Exec { 7040fe15e0SLoGin // 检查文件类型是否为可执行文件 71*a02ce654SChiichen if ElfType::from(ehdr.e_type) != ElfType::Executable 72*a02ce654SChiichen && ElfType::from(ehdr.e_type) != ElfType::DSO 73*a02ce654SChiichen { 7440fe15e0SLoGin return Err(ExecError::NotExecutable); 7540fe15e0SLoGin } 7640fe15e0SLoGin } else { 7740fe15e0SLoGin return Err(ExecError::NotSupported); 7840fe15e0SLoGin } 7940fe15e0SLoGin 8040fe15e0SLoGin return Ok(()); 8140fe15e0SLoGin } 8240fe15e0SLoGin 834fda81ceSLoGin #[cfg(target_arch = "x86_64")] 844fda81ceSLoGin pub fn probe_x86_64( 854fda81ceSLoGin &self, 864fda81ceSLoGin param: &ExecParam, 874fda81ceSLoGin ehdr: &FileHeader<AnyEndian>, 884fda81ceSLoGin ) -> Result<(), ExecError> { 894fda81ceSLoGin // 判断架构是否匹配 904fda81ceSLoGin if ElfMachine::from(ehdr.e_machine) != ElfMachine::X86_64 { 914fda81ceSLoGin return Err(ExecError::WrongArchitecture); 924fda81ceSLoGin } 934fda81ceSLoGin return self.inner_probe_common(param, ehdr); 944fda81ceSLoGin } 954fda81ceSLoGin 964fda81ceSLoGin #[cfg(target_arch = "riscv64")] 974fda81ceSLoGin pub fn probe_riscv( 984fda81ceSLoGin &self, 994fda81ceSLoGin param: &ExecParam, 1004fda81ceSLoGin ehdr: &FileHeader<AnyEndian>, 1014fda81ceSLoGin ) -> Result<(), ExecError> { 1024fda81ceSLoGin // 判断架构是否匹配 1034fda81ceSLoGin if ElfMachine::from(ehdr.e_machine) != ElfMachine::RiscV { 1044fda81ceSLoGin return Err(ExecError::WrongArchitecture); 1054fda81ceSLoGin } 1064fda81ceSLoGin return self.inner_probe_common(param, ehdr); 1074fda81ceSLoGin } 1084fda81ceSLoGin 10940fe15e0SLoGin /// 设置用户堆空间,映射[start, end)区间的虚拟地址,并把brk指针指向end 11040fe15e0SLoGin /// 11140fe15e0SLoGin /// ## 参数 11240fe15e0SLoGin /// 11340fe15e0SLoGin /// - `user_vm_guard` - 用户虚拟地址空间 11440fe15e0SLoGin /// - `start` - 本次映射的起始地址 11540fe15e0SLoGin /// - `end` - 本次映射的结束地址(不包含) 11640fe15e0SLoGin /// - `prot_flags` - 本次映射的权限 11740fe15e0SLoGin fn set_elf_brk( 11840fe15e0SLoGin &self, 11940fe15e0SLoGin user_vm_guard: &mut RwLockWriteGuard<'_, InnerAddressSpace>, 12040fe15e0SLoGin start: VirtAddr, 12140fe15e0SLoGin end: VirtAddr, 12240fe15e0SLoGin prot_flags: ProtFlags, 12340fe15e0SLoGin ) -> Result<(), ExecError> { 12440fe15e0SLoGin let start = self.elf_page_start(start); 12540fe15e0SLoGin let end = self.elf_page_align_up(end); 1261496ba7bSLoGin 12740fe15e0SLoGin if end > start { 12840fe15e0SLoGin let r = user_vm_guard.map_anonymous( 12940fe15e0SLoGin start, 13040fe15e0SLoGin end - start, 13140fe15e0SLoGin prot_flags, 13240fe15e0SLoGin MapFlags::MAP_ANONYMOUS | MapFlags::MAP_FIXED_NOREPLACE, 13340fe15e0SLoGin false, 13440fe15e0SLoGin ); 13540fe15e0SLoGin if r.is_err() { 13640fe15e0SLoGin kerror!("set_elf_brk: map_anonymous failed, err={:?}", r); 13740fe15e0SLoGin return Err(ExecError::OutOfMemory); 13840fe15e0SLoGin } 13940fe15e0SLoGin } 14040fe15e0SLoGin user_vm_guard.elf_brk_start = end; 14140fe15e0SLoGin user_vm_guard.elf_brk = end; 14240fe15e0SLoGin return Ok(()); 14340fe15e0SLoGin } 14440fe15e0SLoGin 14540fe15e0SLoGin /// 计算addr在ELF PAGE内的偏移 14640fe15e0SLoGin fn elf_page_offset(&self, addr: VirtAddr) -> usize { 147*a02ce654SChiichen addr.data() & (CurrentElfArch::ELF_PAGE_SIZE - 1) 14840fe15e0SLoGin } 14940fe15e0SLoGin 15040fe15e0SLoGin fn elf_page_start(&self, addr: VirtAddr) -> VirtAddr { 151*a02ce654SChiichen VirtAddr::new(addr.data() & (!(CurrentElfArch::ELF_PAGE_SIZE - 1))) 15240fe15e0SLoGin } 15340fe15e0SLoGin 15440fe15e0SLoGin fn elf_page_align_up(&self, addr: VirtAddr) -> VirtAddr { 155*a02ce654SChiichen VirtAddr::new( 156*a02ce654SChiichen (addr.data() + CurrentElfArch::ELF_PAGE_SIZE - 1) 157*a02ce654SChiichen & (!(CurrentElfArch::ELF_PAGE_SIZE - 1)), 158*a02ce654SChiichen ) 15940fe15e0SLoGin } 16040fe15e0SLoGin 16140fe15e0SLoGin /// 根据ELF的p_flags生成对应的ProtFlags 16240fe15e0SLoGin fn make_prot(&self, p_flags: u32, _has_interpreter: bool, _is_interpreter: bool) -> ProtFlags { 16340fe15e0SLoGin let mut prot = ProtFlags::empty(); 16440fe15e0SLoGin if p_flags & elf::abi::PF_R != 0 { 16540fe15e0SLoGin prot |= ProtFlags::PROT_READ; 16640fe15e0SLoGin } 16740fe15e0SLoGin if p_flags & elf::abi::PF_W != 0 { 16840fe15e0SLoGin prot |= ProtFlags::PROT_WRITE; 16940fe15e0SLoGin } 17040fe15e0SLoGin if p_flags & elf::abi::PF_X != 0 { 17140fe15e0SLoGin prot |= ProtFlags::PROT_EXEC; 17240fe15e0SLoGin } 17340fe15e0SLoGin 17440fe15e0SLoGin // todo: 增加与架构相关的处理 175e7071df6SLoGin // ref: https://code.dragonos.org.cn/xref/linux-5.19.10/fs/binfmt_elf.c?r=&mo=22652&fi=824#572 17640fe15e0SLoGin 17740fe15e0SLoGin return prot; 17840fe15e0SLoGin } 17940fe15e0SLoGin 18040fe15e0SLoGin /// 加载ELF文件到用户空间 18140fe15e0SLoGin /// 18240fe15e0SLoGin /// 参考Linux的elf_map函数 183e7071df6SLoGin /// https://code.dragonos.org.cn/xref/linux-5.19.10/fs/binfmt_elf.c?r=&mo=22652&fi=824#365 18440fe15e0SLoGin /// ## 参数 18540fe15e0SLoGin /// 18640fe15e0SLoGin /// - `user_vm_guard`:用户空间地址空间 18740fe15e0SLoGin /// - `param`:执行参数 18840fe15e0SLoGin /// - `phent`:ELF文件的ProgramHeader 18940fe15e0SLoGin /// - `addr_to_map`:当前段应该被加载到的内存地址 19040fe15e0SLoGin /// - `prot`:保护标志 19140fe15e0SLoGin /// - `map_flags`:映射标志 19240fe15e0SLoGin /// - `total_size`:ELF文件的总大小 19340fe15e0SLoGin /// 19440fe15e0SLoGin /// ## 返回值 19540fe15e0SLoGin /// 19640fe15e0SLoGin /// - `Ok((VirtAddr, bool))`:如果成功加载,则bool值为true,否则为false. VirtAddr为加载的地址 19740fe15e0SLoGin fn load_elf_segment( 19840fe15e0SLoGin &self, 19940fe15e0SLoGin user_vm_guard: &mut RwLockWriteGuard<'_, InnerAddressSpace>, 20040fe15e0SLoGin param: &mut ExecParam, 20140fe15e0SLoGin phent: &ProgramHeader, 20240fe15e0SLoGin mut addr_to_map: VirtAddr, 20340fe15e0SLoGin prot: &ProtFlags, 20440fe15e0SLoGin map_flags: &MapFlags, 20540fe15e0SLoGin total_size: usize, 20640fe15e0SLoGin ) -> Result<(VirtAddr, bool), SystemError> { 20740fe15e0SLoGin // kdebug!("load_elf_segment: addr_to_map={:?}", addr_to_map); 20840fe15e0SLoGin 20940fe15e0SLoGin // 映射位置的偏移量(页内偏移) 21040fe15e0SLoGin let beginning_page_offset = self.elf_page_offset(addr_to_map); 21140fe15e0SLoGin addr_to_map = self.elf_page_start(addr_to_map); 21240fe15e0SLoGin // 计算要映射的内存的大小 2136d81180bSLoGin let map_size = phent.p_filesz as usize + beginning_page_offset; 21440fe15e0SLoGin let map_size = self.elf_page_align_up(VirtAddr::new(map_size)).data(); 21540fe15e0SLoGin // 当前段在文件中的大小 21640fe15e0SLoGin let seg_in_file_size = phent.p_filesz as usize; 21740fe15e0SLoGin // 当前段在文件中的偏移量 21840fe15e0SLoGin let file_offset = phent.p_offset as usize; 21940fe15e0SLoGin 22040fe15e0SLoGin // 如果当前段的大小为0,则直接返回. 22140fe15e0SLoGin // 段在文件中的大小为0,是合法的,但是段在内存中的大小不能为0 22240fe15e0SLoGin if map_size == 0 { 22340fe15e0SLoGin return Ok((addr_to_map, true)); 22440fe15e0SLoGin } 22540fe15e0SLoGin 22640fe15e0SLoGin let map_err_handler = |err: SystemError| { 22740fe15e0SLoGin if err == SystemError::EEXIST { 22840fe15e0SLoGin kerror!( 2291496ba7bSLoGin "Pid: {:?}, elf segment at {:p} overlaps with existing mapping", 2301496ba7bSLoGin ProcessManager::current_pcb().pid(), 23140fe15e0SLoGin addr_to_map.as_ptr::<u8>() 23240fe15e0SLoGin ); 23340fe15e0SLoGin } 23440fe15e0SLoGin err 23540fe15e0SLoGin }; 23640fe15e0SLoGin // 由于后面需要把ELF文件的内容加载到内存,因此暂时把当前段的权限设置为可写 23740fe15e0SLoGin let tmp_prot = if !prot.contains(ProtFlags::PROT_WRITE) { 23840fe15e0SLoGin *prot | ProtFlags::PROT_WRITE 23940fe15e0SLoGin } else { 24040fe15e0SLoGin *prot 24140fe15e0SLoGin }; 24240fe15e0SLoGin 24340fe15e0SLoGin // 映射到的虚拟地址。请注意,这个虚拟地址是user_vm_guard这个地址空间的虚拟地址。不一定是当前进程地址空间的 24440fe15e0SLoGin let map_addr: VirtAddr; 24540fe15e0SLoGin 24640fe15e0SLoGin // total_size is the size of the ELF (interpreter) image. 24740fe15e0SLoGin // The _first_ mmap needs to know the full size, otherwise 24840fe15e0SLoGin // randomization might put this image into an overlapping 24940fe15e0SLoGin // position with the ELF binary image. (since size < total_size) 25040fe15e0SLoGin // So we first map the 'big' image - and unmap the remainder at 25140fe15e0SLoGin // the end. (which unmap is needed for ELF images with holes.) 25240fe15e0SLoGin if total_size != 0 { 25340fe15e0SLoGin let total_size = self.elf_page_align_up(VirtAddr::new(total_size)).data(); 25440fe15e0SLoGin 25540fe15e0SLoGin // kdebug!("total_size={}", total_size); 25640fe15e0SLoGin 25740fe15e0SLoGin map_addr = user_vm_guard 25840fe15e0SLoGin .map_anonymous(addr_to_map, total_size, tmp_prot, *map_flags, false) 25940fe15e0SLoGin .map_err(map_err_handler)? 26040fe15e0SLoGin .virt_address(); 26140fe15e0SLoGin // kdebug!("map ok: addr_to_map={:?}", addr_to_map); 26240fe15e0SLoGin 26340fe15e0SLoGin let to_unmap = map_addr + map_size; 26440fe15e0SLoGin let to_unmap_size = total_size - map_size; 26540fe15e0SLoGin 26640fe15e0SLoGin // kdebug!("to_unmap={:?}, to_unmap_size={}", to_unmap, to_unmap_size); 26740fe15e0SLoGin user_vm_guard.munmap( 26840fe15e0SLoGin VirtPageFrame::new(to_unmap), 26940fe15e0SLoGin PageFrameCount::from_bytes(to_unmap_size).unwrap(), 27040fe15e0SLoGin )?; 27140fe15e0SLoGin 27240fe15e0SLoGin // 加载文件到内存 27340fe15e0SLoGin self.do_load_file( 27440fe15e0SLoGin map_addr + beginning_page_offset, 27540fe15e0SLoGin seg_in_file_size, 27640fe15e0SLoGin file_offset, 27740fe15e0SLoGin param, 27840fe15e0SLoGin )?; 27940fe15e0SLoGin if tmp_prot != *prot { 28040fe15e0SLoGin user_vm_guard.mprotect( 28140fe15e0SLoGin VirtPageFrame::new(map_addr), 28240fe15e0SLoGin PageFrameCount::from_bytes(page_align_up(map_size)).unwrap(), 28340fe15e0SLoGin *prot, 28440fe15e0SLoGin )?; 28540fe15e0SLoGin } 28640fe15e0SLoGin } else { 28740fe15e0SLoGin // kdebug!("total size = 0"); 28840fe15e0SLoGin 28940fe15e0SLoGin map_addr = user_vm_guard 29040fe15e0SLoGin .map_anonymous(addr_to_map, map_size, tmp_prot, *map_flags, false)? 29140fe15e0SLoGin .virt_address(); 29240fe15e0SLoGin // kdebug!( 29340fe15e0SLoGin // "map ok: addr_to_map={:?}, map_addr={map_addr:?},beginning_page_offset={beginning_page_offset:?}", 29440fe15e0SLoGin // addr_to_map 29540fe15e0SLoGin // ); 29640fe15e0SLoGin 29740fe15e0SLoGin // 加载文件到内存 29840fe15e0SLoGin self.do_load_file( 29940fe15e0SLoGin map_addr + beginning_page_offset, 30040fe15e0SLoGin seg_in_file_size, 30140fe15e0SLoGin file_offset, 30240fe15e0SLoGin param, 30340fe15e0SLoGin )?; 30440fe15e0SLoGin 30540fe15e0SLoGin if tmp_prot != *prot { 30640fe15e0SLoGin user_vm_guard.mprotect( 30740fe15e0SLoGin VirtPageFrame::new(map_addr), 30840fe15e0SLoGin PageFrameCount::from_bytes(page_align_up(map_size)).unwrap(), 30940fe15e0SLoGin *prot, 31040fe15e0SLoGin )?; 31140fe15e0SLoGin } 31240fe15e0SLoGin } 31340fe15e0SLoGin // kdebug!("load_elf_segment OK: map_addr={:?}", map_addr); 31440fe15e0SLoGin return Ok((map_addr, true)); 31540fe15e0SLoGin } 31640fe15e0SLoGin 31740fe15e0SLoGin /// 加载ELF文件到用户空间 31840fe15e0SLoGin /// 31940fe15e0SLoGin /// ## 参数 32040fe15e0SLoGin /// 32140fe15e0SLoGin /// - `vaddr`:要加载到的虚拟地址 32240fe15e0SLoGin /// - `size`:要加载的大小 32340fe15e0SLoGin /// - `offset_in_file`:在文件内的偏移量 32440fe15e0SLoGin /// - `param`:执行参数 32540fe15e0SLoGin fn do_load_file( 32640fe15e0SLoGin &self, 32740fe15e0SLoGin mut vaddr: VirtAddr, 32840fe15e0SLoGin size: usize, 32940fe15e0SLoGin offset_in_file: usize, 33040fe15e0SLoGin param: &mut ExecParam, 33140fe15e0SLoGin ) -> Result<(), SystemError> { 33240fe15e0SLoGin let file = param.file_mut(); 33340fe15e0SLoGin if (file.metadata()?.size as usize) < offset_in_file + size { 33440fe15e0SLoGin return Err(SystemError::ENOEXEC); 33540fe15e0SLoGin } 33640fe15e0SLoGin let buf_size = min(size, Self::FILE_READ_BUF_SIZE); 33740fe15e0SLoGin let mut buf = vec![0u8; buf_size]; 33840fe15e0SLoGin 33940fe15e0SLoGin let mut remain = size; 34040fe15e0SLoGin 34140fe15e0SLoGin file.lseek(SeekFrom::SeekSet(offset_in_file as i64))?; 34240fe15e0SLoGin 34340fe15e0SLoGin while remain > 0 { 34440fe15e0SLoGin let read_size = min(remain, buf_size); 34540fe15e0SLoGin file.read(read_size, &mut buf[..read_size])?; 34640fe15e0SLoGin // kdebug!("copy_to_user: vaddr={:?}, read_size = {read_size}", vaddr); 34740fe15e0SLoGin unsafe { 34840fe15e0SLoGin copy_to_user(vaddr, &buf[..read_size]).map_err(|_| SystemError::EFAULT)?; 34940fe15e0SLoGin } 35040fe15e0SLoGin 35140fe15e0SLoGin vaddr += read_size; 35240fe15e0SLoGin remain -= read_size; 35340fe15e0SLoGin } 35440fe15e0SLoGin return Ok(()); 35540fe15e0SLoGin } 35640fe15e0SLoGin 35740fe15e0SLoGin /// 我们需要显式的把数据段之后剩余的内存页都清零。 35840fe15e0SLoGin fn pad_zero(&self, elf_bss: VirtAddr) -> Result<(), SystemError> { 35940fe15e0SLoGin let nbyte = self.elf_page_offset(elf_bss); 36040fe15e0SLoGin if nbyte > 0 { 361*a02ce654SChiichen let nbyte = CurrentElfArch::ELF_PAGE_SIZE - nbyte; 36240fe15e0SLoGin unsafe { clear_user(elf_bss, nbyte).map_err(|_| SystemError::EFAULT) }?; 36340fe15e0SLoGin } 36440fe15e0SLoGin return Ok(()); 36540fe15e0SLoGin } 36640fe15e0SLoGin 36740fe15e0SLoGin /// 创建auxv 36840fe15e0SLoGin /// 36940fe15e0SLoGin /// ## 参数 37040fe15e0SLoGin /// 37140fe15e0SLoGin /// - `param`:执行参数 37240fe15e0SLoGin /// - `entrypoint_vaddr`:程序入口地址 37340fe15e0SLoGin /// - `phdr_vaddr`:程序头表地址 37440fe15e0SLoGin /// - `elf_header`:ELF文件头 37540fe15e0SLoGin fn create_auxv( 37640fe15e0SLoGin &self, 37740fe15e0SLoGin param: &mut ExecParam, 37840fe15e0SLoGin entrypoint_vaddr: VirtAddr, 37940fe15e0SLoGin phdr_vaddr: Option<VirtAddr>, 38040fe15e0SLoGin ehdr: &elf::file::FileHeader<AnyEndian>, 38140fe15e0SLoGin ) -> Result<(), ExecError> { 38240fe15e0SLoGin let phdr_vaddr = phdr_vaddr.unwrap_or(VirtAddr::new(0)); 38340fe15e0SLoGin 38440fe15e0SLoGin let init_info = param.init_info_mut(); 38540fe15e0SLoGin init_info 38640fe15e0SLoGin .auxv 38740fe15e0SLoGin .insert(AtType::PhEnt as u8, ehdr.e_phentsize as usize); 38840fe15e0SLoGin init_info 38940fe15e0SLoGin .auxv 39040fe15e0SLoGin .insert(AtType::PageSize as u8, MMArch::PAGE_SIZE); 39140fe15e0SLoGin init_info.auxv.insert(AtType::Phdr as u8, phdr_vaddr.data()); 39240fe15e0SLoGin init_info 39340fe15e0SLoGin .auxv 39440fe15e0SLoGin .insert(AtType::PhNum as u8, ehdr.e_phnum as usize); 39540fe15e0SLoGin init_info 39640fe15e0SLoGin .auxv 39740fe15e0SLoGin .insert(AtType::Entry as u8, entrypoint_vaddr.data()); 39840fe15e0SLoGin 39940fe15e0SLoGin return Ok(()); 40040fe15e0SLoGin } 40140fe15e0SLoGin 40240fe15e0SLoGin /// 解析文件的ehdr 40340fe15e0SLoGin fn parse_ehdr(data: &[u8]) -> Result<FileHeader<AnyEndian>, elf::ParseError> { 40440fe15e0SLoGin let ident_buf = data.get_bytes(0..elf::abi::EI_NIDENT)?; 40540fe15e0SLoGin let ident = elf::file::parse_ident::<AnyEndian>(ident_buf)?; 40640fe15e0SLoGin 40740fe15e0SLoGin let tail_start = elf::abi::EI_NIDENT; 40840fe15e0SLoGin let tail_end = match ident.1 { 40940fe15e0SLoGin elf::file::Class::ELF32 => tail_start + elf::file::ELF32_EHDR_TAILSIZE, 41040fe15e0SLoGin elf::file::Class::ELF64 => tail_start + elf::file::ELF64_EHDR_TAILSIZE, 41140fe15e0SLoGin }; 41240fe15e0SLoGin let tail_buf = data.get_bytes(tail_start..tail_end)?; 41340fe15e0SLoGin 41440fe15e0SLoGin let ehdr: FileHeader<_> = FileHeader::parse_tail(ident, tail_buf)?; 41540fe15e0SLoGin return Ok(ehdr); 41640fe15e0SLoGin } 41740fe15e0SLoGin 41840fe15e0SLoGin /// 解析文件的program header table 41940fe15e0SLoGin /// 42040fe15e0SLoGin /// ## 参数 42140fe15e0SLoGin /// 42240fe15e0SLoGin /// - `param`:执行参数 42340fe15e0SLoGin /// - `ehdr`:文件头 42440fe15e0SLoGin /// - `data_buf`:用于缓存SegmentTable的Vec。 42540fe15e0SLoGin /// 这是因为SegmentTable的生命周期与data_buf一致。初始化这个Vec的大小为0即可。 42640fe15e0SLoGin /// 42740fe15e0SLoGin /// ## 说明 42840fe15e0SLoGin /// 42940fe15e0SLoGin /// 这个函数由elf库的`elf::elf_bytes::find_phdrs`修改而来。 43040fe15e0SLoGin fn parse_segments<'a>( 43140fe15e0SLoGin param: &mut ExecParam, 43240fe15e0SLoGin ehdr: &FileHeader<AnyEndian>, 43340fe15e0SLoGin data_buf: &'a mut Vec<u8>, 43440fe15e0SLoGin ) -> Result<Option<elf::segment::SegmentTable<'a, AnyEndian>>, elf::ParseError> { 43540fe15e0SLoGin // It's Ok to have no program headers 43640fe15e0SLoGin if ehdr.e_phoff == 0 { 43740fe15e0SLoGin return Ok(None); 43840fe15e0SLoGin } 43940fe15e0SLoGin let file = param.file_mut(); 44040fe15e0SLoGin // If the number of segments is greater than or equal to PN_XNUM (0xffff), 44140fe15e0SLoGin // e_phnum is set to PN_XNUM, and the actual number of program header table 44240fe15e0SLoGin // entries is contained in the sh_info field of the section header at index 0. 44340fe15e0SLoGin let mut phnum = ehdr.e_phnum as usize; 44440fe15e0SLoGin if phnum == elf::abi::PN_XNUM as usize { 44540fe15e0SLoGin let shoff: usize = ehdr.e_shoff.try_into()?; 44640fe15e0SLoGin 44740fe15e0SLoGin // 从磁盘读取shdr的前2个entry 44840fe15e0SLoGin file.lseek(SeekFrom::SeekSet(shoff as i64)) 44940fe15e0SLoGin .map_err(|_| elf::ParseError::BadOffset(shoff as u64))?; 45040fe15e0SLoGin let shdr_buf_size = ehdr.e_shentsize * 2; 45140fe15e0SLoGin let mut shdr_buf = vec![0u8; shdr_buf_size as usize]; 45240fe15e0SLoGin file.read(shdr_buf_size as usize, &mut shdr_buf) 45340fe15e0SLoGin .map_err(|_| elf::ParseError::BadOffset(shoff as u64))?; 45440fe15e0SLoGin 45540fe15e0SLoGin let mut offset = 0; 45640fe15e0SLoGin let shdr0 = <elf::section::SectionHeader as elf::parse::ParseAt>::parse_at( 45740fe15e0SLoGin ehdr.endianness, 45840fe15e0SLoGin ehdr.class, 45940fe15e0SLoGin &mut offset, 46040fe15e0SLoGin &shdr_buf, 46140fe15e0SLoGin )?; 46240fe15e0SLoGin phnum = shdr0.sh_info.try_into()?; 46340fe15e0SLoGin } 46440fe15e0SLoGin 46540fe15e0SLoGin // Validate phentsize before trying to read the table so that we can error early for corrupted files 46640fe15e0SLoGin let entsize = <ProgramHeader as elf::parse::ParseAt>::validate_entsize( 46740fe15e0SLoGin ehdr.class, 46840fe15e0SLoGin ehdr.e_phentsize as usize, 46940fe15e0SLoGin )?; 47040fe15e0SLoGin let phoff: usize = ehdr.e_phoff.try_into()?; 47140fe15e0SLoGin let size = entsize 47240fe15e0SLoGin .checked_mul(phnum) 47340fe15e0SLoGin .ok_or(elf::ParseError::IntegerOverflow)?; 47440fe15e0SLoGin phoff 47540fe15e0SLoGin .checked_add(size) 47640fe15e0SLoGin .ok_or(elf::ParseError::IntegerOverflow)?; 47740fe15e0SLoGin 47840fe15e0SLoGin // 读取program header table 47940fe15e0SLoGin 48040fe15e0SLoGin file.lseek(SeekFrom::SeekSet(phoff as i64)) 48140fe15e0SLoGin .map_err(|_| elf::ParseError::BadOffset(phoff as u64))?; 48240fe15e0SLoGin data_buf.clear(); 48340fe15e0SLoGin data_buf.resize(size, 0); 48440fe15e0SLoGin 48540fe15e0SLoGin file.read(size, data_buf) 48640fe15e0SLoGin .expect("read program header table failed"); 48740fe15e0SLoGin let buf = data_buf.get_bytes(0..size)?; 48840fe15e0SLoGin 48940fe15e0SLoGin return Ok(Some(elf::segment::SegmentTable::new( 49040fe15e0SLoGin ehdr.endianness, 49140fe15e0SLoGin ehdr.class, 49240fe15e0SLoGin buf, 49340fe15e0SLoGin ))); 49440fe15e0SLoGin } 495*a02ce654SChiichen 496*a02ce654SChiichen // 解析 PT_GNU_PROPERTY 类型的段 497*a02ce654SChiichen // 参照 https://code.dragonos.org.cn/xref/linux-6.1.9/fs/binfmt_elf.c#767 498*a02ce654SChiichen fn parse_gnu_property() -> Result<(), ExecError> { 499*a02ce654SChiichen return Ok(()); 500*a02ce654SChiichen } 50140fe15e0SLoGin } 50240fe15e0SLoGin 50340fe15e0SLoGin impl BinaryLoader for ElfLoader { 50440fe15e0SLoGin fn probe(self: &'static Self, param: &ExecParam, buf: &[u8]) -> Result<(), ExecError> { 50540fe15e0SLoGin // let elf_bytes = 50640fe15e0SLoGin // ElfBytes::<AnyEndian>::minimal_parse(buf).map_err(|_| ExecError::NotExecutable)?; 50740fe15e0SLoGin 50840fe15e0SLoGin let ehdr = Self::parse_ehdr(buf).map_err(|_| ExecError::NotExecutable)?; 50940fe15e0SLoGin 51040fe15e0SLoGin #[cfg(target_arch = "x86_64")] 51140fe15e0SLoGin return self.probe_x86_64(param, &ehdr); 51240fe15e0SLoGin 5134fda81ceSLoGin #[cfg(target_arch = "riscv64")] 5144fda81ceSLoGin return self.probe_riscv(param, &ehdr); 5154fda81ceSLoGin 5164fda81ceSLoGin #[cfg(not(any(target_arch = "x86_64", target_arch = "riscv64")))] 5174fda81ceSLoGin compile_error!("BinaryLoader: Unsupported architecture"); 51840fe15e0SLoGin } 51940fe15e0SLoGin 52040fe15e0SLoGin fn load( 52140fe15e0SLoGin self: &'static Self, 52240fe15e0SLoGin param: &mut ExecParam, 52340fe15e0SLoGin head_buf: &[u8], 52440fe15e0SLoGin ) -> Result<BinaryLoaderResult, ExecError> { 52540fe15e0SLoGin // 解析elf文件头 52640fe15e0SLoGin let ehdr = Self::parse_ehdr(head_buf).map_err(|_| ExecError::NotExecutable)?; 52740fe15e0SLoGin 52840fe15e0SLoGin // 参考linux-5.19的load_elf_binary函数 529e7071df6SLoGin // https://code.dragonos.org.cn/xref/linux-5.19.10/fs/binfmt_elf.c?r=&mo=22652&fi=824#1034 53040fe15e0SLoGin 53140fe15e0SLoGin let elf_type = ElfType::from(ehdr.e_type); 53240fe15e0SLoGin // kdebug!("ehdr = {:?}", ehdr); 53340fe15e0SLoGin 53440fe15e0SLoGin let binding = param.vm().clone(); 53540fe15e0SLoGin let mut user_vm = binding.write(); 53640fe15e0SLoGin 53740fe15e0SLoGin // todo: 增加对user stack上的内存是否具有可执行权限的处理(方法:寻找phdr里面的PT_GNU_STACK段) 53840fe15e0SLoGin 53940fe15e0SLoGin // kdebug!("to parse segments"); 54040fe15e0SLoGin // 加载ELF文件并映射到用户空间 54140fe15e0SLoGin let mut phdr_buf = Vec::new(); 542*a02ce654SChiichen let phdr_table = Self::parse_segments(param, &ehdr, &mut phdr_buf) 54340fe15e0SLoGin .map_err(|_| ExecError::ParseError)? 544*a02ce654SChiichen .ok_or(ExecError::ParseError)?; 545*a02ce654SChiichen let mut _gnu_property_data: Option<ProgramHeader> = None; 546*a02ce654SChiichen let interpreter: Option<File> = None; 547*a02ce654SChiichen for seg in phdr_table { 548*a02ce654SChiichen if seg.p_type == PT_GNU_PROPERTY { 549*a02ce654SChiichen _gnu_property_data = Some(seg.clone()); 550*a02ce654SChiichen continue; 551*a02ce654SChiichen } 552*a02ce654SChiichen if seg.p_type != PT_INTERP { 553*a02ce654SChiichen continue; 554*a02ce654SChiichen } 555*a02ce654SChiichen // 接下来处理这个 .interpreter 段以及动态链接器 556*a02ce654SChiichen // 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/fs/binfmt_elf.c#881 557*a02ce654SChiichen 558*a02ce654SChiichen if seg.p_filesz > 4096 || seg.p_filesz < 2 { 559*a02ce654SChiichen return Err(ExecError::NotExecutable); 560*a02ce654SChiichen } 561*a02ce654SChiichen 562*a02ce654SChiichen let interpreter_ptr = unsafe { 563*a02ce654SChiichen core::slice::from_raw_parts( 564*a02ce654SChiichen seg.p_offset as *const u8, 565*a02ce654SChiichen seg.p_filesz.try_into().unwrap(), 566*a02ce654SChiichen ) 567*a02ce654SChiichen }; 568*a02ce654SChiichen let _interpreter_path = core::str::from_utf8(interpreter_ptr).map_err(|e| { 569*a02ce654SChiichen ExecError::Other(format!( 570*a02ce654SChiichen "Failed to parse the path of dynamic linker with error {}", 571*a02ce654SChiichen e 572*a02ce654SChiichen )) 573*a02ce654SChiichen })?; 574*a02ce654SChiichen 575*a02ce654SChiichen //TODO 加入对动态链接器的加载,参照 https://code.dragonos.org.cn/xref/linux-6.1.9/fs/binfmt_elf.c#890 576*a02ce654SChiichen } 577*a02ce654SChiichen if interpreter.is_some() { 578*a02ce654SChiichen /* Some simple consistency checks for the interpreter */ 579*a02ce654SChiichen // 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/fs/binfmt_elf.c#950 580*a02ce654SChiichen } 581*a02ce654SChiichen Self::parse_gnu_property()?; 58240fe15e0SLoGin 58340fe15e0SLoGin // kdebug!("loadable_sections = {:?}", loadable_sections); 58440fe15e0SLoGin 58540fe15e0SLoGin let mut elf_brk = VirtAddr::new(0); 58640fe15e0SLoGin let mut elf_bss = VirtAddr::new(0); 58740fe15e0SLoGin let mut start_code: Option<VirtAddr> = None; 58840fe15e0SLoGin let mut end_code: Option<VirtAddr> = None; 58940fe15e0SLoGin let mut start_data: Option<VirtAddr> = None; 59040fe15e0SLoGin let mut end_data: Option<VirtAddr> = None; 59140fe15e0SLoGin 592*a02ce654SChiichen // 加载的时候的偏移量(这个偏移量在加载动态链接段的时候产生) 593*a02ce654SChiichen let mut load_bias = 0usize; 59440fe15e0SLoGin let mut bss_prot_flags = ProtFlags::empty(); 59540fe15e0SLoGin // 是否是第一个加载的段 59640fe15e0SLoGin let mut first_pt_load = true; 59740fe15e0SLoGin // program header的虚拟地址 59840fe15e0SLoGin let mut phdr_vaddr: Option<VirtAddr> = None; 599*a02ce654SChiichen let mut _reloc_func_desc = 0usize; 600*a02ce654SChiichen // 参考https://code.dragonos.org.cn/xref/linux-6.1.9/fs/binfmt_elf.c#1158,获取要加载的total_size 601*a02ce654SChiichen let mut has_load = false; 602*a02ce654SChiichen let mut min_address = VirtAddr::new(usize::MAX); 603*a02ce654SChiichen let mut max_address = VirtAddr::new(0usize); 604*a02ce654SChiichen let loadable_sections = phdr_table 605*a02ce654SChiichen .into_iter() 606*a02ce654SChiichen .filter(|seg| seg.p_type == elf::abi::PT_LOAD); 607*a02ce654SChiichen for seg_to_load in loadable_sections { 608*a02ce654SChiichen min_address = min( 609*a02ce654SChiichen min_address, 610*a02ce654SChiichen self.elf_page_start(VirtAddr::new(seg_to_load.p_vaddr.try_into().unwrap())), 611*a02ce654SChiichen ); 612*a02ce654SChiichen max_address = max( 613*a02ce654SChiichen max_address, 614*a02ce654SChiichen VirtAddr::new( 615*a02ce654SChiichen (seg_to_load.p_vaddr + seg_to_load.p_memsz) 616*a02ce654SChiichen .try_into() 617*a02ce654SChiichen .unwrap(), 618*a02ce654SChiichen ), 619*a02ce654SChiichen ); 620*a02ce654SChiichen has_load = true; 621*a02ce654SChiichen } 622*a02ce654SChiichen let total_size = if has_load { 623*a02ce654SChiichen max_address - min_address 624*a02ce654SChiichen } else { 625*a02ce654SChiichen 0 626*a02ce654SChiichen }; 627*a02ce654SChiichen let loadable_sections = phdr_table 628*a02ce654SChiichen .into_iter() 629*a02ce654SChiichen .filter(|seg| seg.p_type == elf::abi::PT_LOAD); 63040fe15e0SLoGin for seg_to_load in loadable_sections { 63140fe15e0SLoGin // kdebug!("seg_to_load = {:?}", seg_to_load); 63240fe15e0SLoGin if unlikely(elf_brk > elf_bss) { 63340fe15e0SLoGin // kdebug!( 63440fe15e0SLoGin // "to set brk, elf_brk = {:?}, elf_bss = {:?}", 63540fe15e0SLoGin // elf_brk, 63640fe15e0SLoGin // elf_bss 63740fe15e0SLoGin // ); 63840fe15e0SLoGin self.set_elf_brk( 63940fe15e0SLoGin &mut user_vm, 64040fe15e0SLoGin elf_bss + load_bias, 64140fe15e0SLoGin elf_brk + load_bias, 64240fe15e0SLoGin bss_prot_flags, 64340fe15e0SLoGin )?; 64440fe15e0SLoGin let nbyte = self.elf_page_offset(elf_bss); 64540fe15e0SLoGin if nbyte > 0 { 646*a02ce654SChiichen let nbyte = min(CurrentElfArch::ELF_PAGE_SIZE - nbyte, elf_brk - elf_bss); 64740fe15e0SLoGin unsafe { 64840fe15e0SLoGin // This bss-zeroing can fail if the ELF file specifies odd protections. 64940fe15e0SLoGin // So we don't check the return value. 65040fe15e0SLoGin clear_user(elf_bss + load_bias, nbyte).ok(); 65140fe15e0SLoGin } 65240fe15e0SLoGin } 65340fe15e0SLoGin } 65440fe15e0SLoGin 65540fe15e0SLoGin // 生成ProtFlags. 656*a02ce654SChiichen let elf_prot_flags = self.make_prot(seg_to_load.p_flags, interpreter.is_some(), false); 65740fe15e0SLoGin 65840fe15e0SLoGin let mut elf_map_flags = MapFlags::MAP_PRIVATE; 65940fe15e0SLoGin 660*a02ce654SChiichen let vaddr = VirtAddr::new(seg_to_load.p_vaddr.try_into().unwrap()); 66140fe15e0SLoGin 66240fe15e0SLoGin if !first_pt_load { 66340fe15e0SLoGin elf_map_flags.insert(MapFlags::MAP_FIXED_NOREPLACE); 66440fe15e0SLoGin } else if elf_type == ElfType::Executable { 66540fe15e0SLoGin /* 66640fe15e0SLoGin * This logic is run once for the first LOAD Program 66740fe15e0SLoGin * Header for ET_EXEC binaries. No special handling 66840fe15e0SLoGin * is needed. 66940fe15e0SLoGin */ 67040fe15e0SLoGin elf_map_flags.insert(MapFlags::MAP_FIXED_NOREPLACE); 67140fe15e0SLoGin } else if elf_type == ElfType::DSO { 67240fe15e0SLoGin // TODO: 支持动态链接 673*a02ce654SChiichen if interpreter.is_some() { 674*a02ce654SChiichen load_bias = CurrentElfArch::ELF_ET_DYN_BASE; 675*a02ce654SChiichen if ProcessManager::current_pcb() 676*a02ce654SChiichen .flags() 677*a02ce654SChiichen .contains(ProcessFlags::RANDOMIZE) 678*a02ce654SChiichen { 679*a02ce654SChiichen //这里x86下需要一个随机加载的方法,但是很多架构,比如Risc-V都是0,就暂时不写了 680*a02ce654SChiichen } else { 681*a02ce654SChiichen load_bias = 0; 682*a02ce654SChiichen } 683*a02ce654SChiichen } 684*a02ce654SChiichen load_bias = self 685*a02ce654SChiichen .elf_page_start(VirtAddr::new( 686*a02ce654SChiichen load_bias - TryInto::<usize>::try_into(seg_to_load.p_vaddr).unwrap(), 687*a02ce654SChiichen )) 688*a02ce654SChiichen .data(); 689*a02ce654SChiichen if total_size == 0 { 690*a02ce654SChiichen return Err(ExecError::InvalidParemeter); 691*a02ce654SChiichen } 69240fe15e0SLoGin } 69340fe15e0SLoGin 69440fe15e0SLoGin // 加载这个段到用户空间 69540fe15e0SLoGin 69640fe15e0SLoGin let e = self 69740fe15e0SLoGin .load_elf_segment( 69840fe15e0SLoGin &mut user_vm, 69940fe15e0SLoGin param, 70040fe15e0SLoGin &seg_to_load, 70140fe15e0SLoGin vaddr + load_bias, 70240fe15e0SLoGin &elf_prot_flags, 70340fe15e0SLoGin &elf_map_flags, 704*a02ce654SChiichen total_size, 70540fe15e0SLoGin ) 70640fe15e0SLoGin .map_err(|e| match e { 70740fe15e0SLoGin SystemError::EFAULT => ExecError::BadAddress(None), 70840fe15e0SLoGin SystemError::ENOMEM => ExecError::OutOfMemory, 70940fe15e0SLoGin _ => ExecError::Other(format!("load_elf_segment failed: {:?}", e)), 71040fe15e0SLoGin })?; 71140fe15e0SLoGin 71240fe15e0SLoGin // 如果地址不对,那么就报错 71340fe15e0SLoGin if !e.1 { 71440fe15e0SLoGin return Err(ExecError::BadAddress(Some(e.0))); 71540fe15e0SLoGin } 71640fe15e0SLoGin 71740fe15e0SLoGin if first_pt_load { 71840fe15e0SLoGin first_pt_load = false; 71940fe15e0SLoGin if elf_type == ElfType::DSO { 72040fe15e0SLoGin // todo: 在这里增加对load_bias和reloc_func_desc的更新代码 721*a02ce654SChiichen load_bias += e.0.data() 722*a02ce654SChiichen - self 723*a02ce654SChiichen .elf_page_start(VirtAddr::new( 724*a02ce654SChiichen load_bias 725*a02ce654SChiichen + TryInto::<usize>::try_into(seg_to_load.p_vaddr).unwrap(), 726*a02ce654SChiichen )) 727*a02ce654SChiichen .data(); 728*a02ce654SChiichen _reloc_func_desc = load_bias; 72940fe15e0SLoGin } 73040fe15e0SLoGin } 73140fe15e0SLoGin 73240fe15e0SLoGin // kdebug!("seg_to_load.p_offset={}", seg_to_load.p_offset); 73340fe15e0SLoGin // kdebug!("e_phoff={}", ehdr.e_phoff); 73440fe15e0SLoGin // kdebug!("seg_to_load.p_filesz={}", seg_to_load.p_filesz); 73540fe15e0SLoGin // Figure out which segment in the file contains the Program Header Table, 73640fe15e0SLoGin // and map to the associated virtual address. 73740fe15e0SLoGin if (seg_to_load.p_offset <= ehdr.e_phoff) 73840fe15e0SLoGin && (ehdr.e_phoff < (seg_to_load.p_offset + seg_to_load.p_filesz)) 73940fe15e0SLoGin { 74040fe15e0SLoGin phdr_vaddr = Some(VirtAddr::new( 74140fe15e0SLoGin (ehdr.e_phoff - seg_to_load.p_offset + seg_to_load.p_vaddr) as usize, 74240fe15e0SLoGin )); 74340fe15e0SLoGin } 74440fe15e0SLoGin 74540fe15e0SLoGin let p_vaddr = VirtAddr::new(seg_to_load.p_vaddr as usize); 74640fe15e0SLoGin if (seg_to_load.p_flags & elf::abi::PF_X) != 0 { 74740fe15e0SLoGin if start_code.is_none() || start_code.as_ref().unwrap() > &p_vaddr { 74840fe15e0SLoGin start_code = Some(p_vaddr); 74940fe15e0SLoGin } 75040fe15e0SLoGin } 75140fe15e0SLoGin 75240fe15e0SLoGin if start_data.is_none() 75340fe15e0SLoGin || (start_data.is_some() && start_data.as_ref().unwrap() > &p_vaddr) 75440fe15e0SLoGin { 75540fe15e0SLoGin start_data = Some(p_vaddr); 75640fe15e0SLoGin } 75740fe15e0SLoGin 75840fe15e0SLoGin // 如果程序段要加载的目标地址不在用户空间内,或者是其他不合法的情况,那么就报错 75940fe15e0SLoGin if !p_vaddr.check_user() 76040fe15e0SLoGin || seg_to_load.p_filesz > seg_to_load.p_memsz 7615d549a76SChiichen || self.elf_page_align_up(p_vaddr + seg_to_load.p_memsz as usize) 7625d549a76SChiichen >= MMArch::USER_END_VADDR 76340fe15e0SLoGin { 76440fe15e0SLoGin // kdebug!("ERR: p_vaddr={p_vaddr:?}"); 76540fe15e0SLoGin return Err(ExecError::InvalidParemeter); 76640fe15e0SLoGin } 76740fe15e0SLoGin 76840fe15e0SLoGin // end vaddr of this segment(code+data+bss) 76940fe15e0SLoGin let seg_end_vaddr_f = self.elf_page_align_up(VirtAddr::new( 77040fe15e0SLoGin (seg_to_load.p_vaddr + seg_to_load.p_filesz) as usize, 77140fe15e0SLoGin )); 77240fe15e0SLoGin 77340fe15e0SLoGin if seg_end_vaddr_f > elf_bss { 77440fe15e0SLoGin elf_bss = seg_end_vaddr_f; 77540fe15e0SLoGin } 77640fe15e0SLoGin 77740fe15e0SLoGin if ((seg_to_load.p_flags & elf::abi::PF_X) != 0) 77840fe15e0SLoGin && (end_code.is_none() 77940fe15e0SLoGin || (end_code.is_some() && end_code.as_ref().unwrap() < &seg_end_vaddr_f)) 78040fe15e0SLoGin { 78140fe15e0SLoGin end_code = Some(seg_end_vaddr_f); 78240fe15e0SLoGin } 78340fe15e0SLoGin 78440fe15e0SLoGin if end_data.is_none() 78540fe15e0SLoGin || (end_data.is_some() && end_data.as_ref().unwrap() < &seg_end_vaddr_f) 78640fe15e0SLoGin { 78740fe15e0SLoGin end_data = Some(seg_end_vaddr_f); 78840fe15e0SLoGin } 78940fe15e0SLoGin 79040fe15e0SLoGin let seg_end_vaddr = VirtAddr::new((seg_to_load.p_vaddr + seg_to_load.p_memsz) as usize); 79140fe15e0SLoGin 79240fe15e0SLoGin if seg_end_vaddr > elf_brk { 79340fe15e0SLoGin bss_prot_flags = elf_prot_flags; 79440fe15e0SLoGin elf_brk = seg_end_vaddr; 79540fe15e0SLoGin } 79640fe15e0SLoGin } 79740fe15e0SLoGin // kdebug!("elf load: phdr_vaddr={phdr_vaddr:?}"); 79840fe15e0SLoGin let program_entrypoint = VirtAddr::new(ehdr.e_entry as usize + load_bias); 79940fe15e0SLoGin let phdr_vaddr = if phdr_vaddr.is_some() { 80040fe15e0SLoGin Some(phdr_vaddr.unwrap() + load_bias) 80140fe15e0SLoGin } else { 80240fe15e0SLoGin None 80340fe15e0SLoGin }; 80440fe15e0SLoGin 80540fe15e0SLoGin elf_bss += load_bias; 80640fe15e0SLoGin elf_brk += load_bias; 80740fe15e0SLoGin start_code = start_code.map(|v| v + load_bias); 80840fe15e0SLoGin end_code = end_code.map(|v| v + load_bias); 80940fe15e0SLoGin start_data = start_data.map(|v| v + load_bias); 81040fe15e0SLoGin end_data = end_data.map(|v| v + load_bias); 81140fe15e0SLoGin 81240fe15e0SLoGin // kdebug!( 81340fe15e0SLoGin // "to set brk: elf_bss: {:?}, elf_brk: {:?}, bss_prot_flags: {:?}", 81440fe15e0SLoGin // elf_bss, 81540fe15e0SLoGin // elf_brk, 81640fe15e0SLoGin // bss_prot_flags 81740fe15e0SLoGin // ); 81840fe15e0SLoGin self.set_elf_brk(&mut user_vm, elf_bss, elf_brk, bss_prot_flags)?; 81940fe15e0SLoGin 82040fe15e0SLoGin if likely(elf_bss != elf_brk) && unlikely(self.pad_zero(elf_bss).is_err()) { 82140fe15e0SLoGin // kdebug!("elf_bss = {elf_bss:?}, elf_brk = {elf_brk:?}"); 82240fe15e0SLoGin return Err(ExecError::BadAddress(Some(elf_bss))); 82340fe15e0SLoGin } 824*a02ce654SChiichen if interpreter.is_some() { 825*a02ce654SChiichen // TODO 添加对动态加载器的处理 826*a02ce654SChiichen // 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/fs/binfmt_elf.c#1249 827*a02ce654SChiichen } 82840fe15e0SLoGin // kdebug!("to create auxv"); 82940fe15e0SLoGin 83040fe15e0SLoGin self.create_auxv(param, program_entrypoint, phdr_vaddr, &ehdr)?; 83140fe15e0SLoGin 83240fe15e0SLoGin // kdebug!("auxv create ok"); 83340fe15e0SLoGin user_vm.start_code = start_code.unwrap_or(VirtAddr::new(0)); 83440fe15e0SLoGin user_vm.end_code = end_code.unwrap_or(VirtAddr::new(0)); 83540fe15e0SLoGin user_vm.start_data = start_data.unwrap_or(VirtAddr::new(0)); 83640fe15e0SLoGin user_vm.end_data = end_data.unwrap_or(VirtAddr::new(0)); 83740fe15e0SLoGin 83840fe15e0SLoGin let result = BinaryLoaderResult::new(program_entrypoint); 83940fe15e0SLoGin // kdebug!("elf load OK!!!"); 84040fe15e0SLoGin return Ok(result); 84140fe15e0SLoGin } 84240fe15e0SLoGin } 84340fe15e0SLoGin 84440fe15e0SLoGin /// Elf机器架构,对应于e_machine字段。在ABI中,以EM_开头的常量是e_machine字段的值。 84540fe15e0SLoGin #[derive(Debug, Eq, PartialEq)] 84640fe15e0SLoGin pub enum ElfMachine { 84740fe15e0SLoGin I386, 84840fe15e0SLoGin AArch32, 84940fe15e0SLoGin AArch64, 85040fe15e0SLoGin X86_64, 85140fe15e0SLoGin RiscV, 85240fe15e0SLoGin /// 龙芯架构 85340fe15e0SLoGin LoongArch, 85440fe15e0SLoGin /// 未知架构 85540fe15e0SLoGin Unknown, 85640fe15e0SLoGin } 85740fe15e0SLoGin 85840fe15e0SLoGin impl From<u16> for ElfMachine { 85940fe15e0SLoGin fn from(machine: u16) -> Self { 86040fe15e0SLoGin match machine { 86140fe15e0SLoGin 0x03 => Self::I386, 86240fe15e0SLoGin 0x28 => Self::AArch32, 86340fe15e0SLoGin 0xb7 => Self::AArch64, 86440fe15e0SLoGin 0x3e => Self::X86_64, 86540fe15e0SLoGin 0xf3 => Self::RiscV, 86640fe15e0SLoGin 0x102 => Self::LoongArch, 86740fe15e0SLoGin // 未知架构 86840fe15e0SLoGin _ => Self::Unknown, 86940fe15e0SLoGin } 87040fe15e0SLoGin } 87140fe15e0SLoGin } 87240fe15e0SLoGin 87340fe15e0SLoGin /// Elf文件类型,对应于e_type字段。在ABI中,以ET_开头的常量是e_type字段的值。 87440fe15e0SLoGin #[derive(Debug, Eq, PartialEq)] 87540fe15e0SLoGin pub enum ElfType { 87640fe15e0SLoGin /// 可重定位文件 87740fe15e0SLoGin Relocatable, 87840fe15e0SLoGin /// 可执行文件 87940fe15e0SLoGin Executable, 88040fe15e0SLoGin /// 动态链接库 88140fe15e0SLoGin DSO, 88240fe15e0SLoGin /// 核心转储文件 88340fe15e0SLoGin Core, 88440fe15e0SLoGin /// 未知类型 88540fe15e0SLoGin Unknown, 88640fe15e0SLoGin } 88740fe15e0SLoGin 88840fe15e0SLoGin impl From<u16> for ElfType { 88940fe15e0SLoGin fn from(elf_type: u16) -> Self { 89040fe15e0SLoGin match elf_type { 89140fe15e0SLoGin 0x01 => Self::Relocatable, 89240fe15e0SLoGin 0x02 => Self::Executable, 89340fe15e0SLoGin 0x03 => Self::DSO, 89440fe15e0SLoGin 0x04 => Self::Core, 89540fe15e0SLoGin _ => Self::Unknown, 89640fe15e0SLoGin } 89740fe15e0SLoGin } 89840fe15e0SLoGin } 89940fe15e0SLoGin 90040fe15e0SLoGin // Simple convenience extension trait to wrap get() with .ok_or(SliceReadError) 90140fe15e0SLoGin trait ReadBytesExt<'data> { 90240fe15e0SLoGin fn get_bytes(self, range: Range<usize>) -> Result<&'data [u8], elf::ParseError>; 90340fe15e0SLoGin } 90440fe15e0SLoGin impl<'data> ReadBytesExt<'data> for &'data [u8] { 90540fe15e0SLoGin fn get_bytes(self, range: Range<usize>) -> Result<&'data [u8], elf::ParseError> { 90640fe15e0SLoGin let start = range.start; 90740fe15e0SLoGin let end = range.end; 90840fe15e0SLoGin self.get(range) 90940fe15e0SLoGin .ok_or(elf::ParseError::SliceReadError((start, end))) 91040fe15e0SLoGin } 91140fe15e0SLoGin } 912