void Loader::execute() { std::cout << "====== start loading elf ======" << std::endl; // 检查当前运行程序是否64位 if (sizeof(intptr_t) != sizeof(std::int64_t)) { throw std::runtime_error("please use x64 compile and run this program"); } // 读取ELF头 Elf64_External_Ehdr elfHeader = {}; fileStream_.seekg(0); fileStream_.read(reinterpret_cast<char*>(&elfHeader), sizeof(elfHeader)); // 检查ELF头,只支持64位且byte order是little endian的程序 if (std::string(reinterpret_cast<char*>(elfHeader.e_ident), 4) != "\x7f\x45\x4c\x46") { throw std::runtime_error("magic not match"); } else if (elfHeader.e_ident[EI_CLASS] != ELFCLASS64) { throw std::runtime_error("only support ELF64"); } else if (elfHeader.e_ident[EI_DATA] != ELFDATA2LSB) { throw std::runtime_error("only support little endian"); } // 获取program table的信息 std::uint32_t programTableOffset = *reinterpret_cast<std::uint32_t*>(elfHeader.e_phoff); std::uint16_t programTableEntrySize = *reinterpret_cast<std::uint16_t*>(elfHeader.e_phentsize); std::uint16_t programTableEntryNum = *reinterpret_cast<std::uint16_t*>(elfHeader.e_phnum); std::cout << "program table at: " << programTableOffset << ", " << programTableEntryNum << " x " << programTableEntrySize << std::endl; // 获取section table的信息 // section table只给linker用,loader中其实不需要访问section table std::uint32_t sectionTableOffset = *reinterpret_cast<std::uint32_t*>(elfHeader.e_shoff); std::uint16_t sectionTableEntrySize = *reinterpret_cast<std::uint16_t*>(elfHeader.e_shentsize); std::uint16_t sectionTableEntryNum = *reinterpret_cast<std::uint16_t*>(elfHeader.e_shentsize); std::cout << "section table at: " << sectionTableOffset << ", " << sectionTableEntryNum << " x " << sectionTableEntrySize << std::endl;
在Windows上实现运行Linux程序,附示例代码(9)
内容版权声明:除非注明,否则皆为本站原创文章。
转载注明出处:https://www.heiqu.com/72b280b1eb63e21e26b1857dcd76d550.html