elf.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. // Copyright 2013 Dolphin Emulator Project / 2014 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <cstring>
  5. #include <memory>
  6. #include <string>
  7. #include "common/common_funcs.h"
  8. #include "common/common_types.h"
  9. #include "common/file_util.h"
  10. #include "common/logging/log.h"
  11. #include "core/hle/kernel/code_set.h"
  12. #include "core/hle/kernel/memory/page_table.h"
  13. #include "core/hle/kernel/process.h"
  14. #include "core/loader/elf.h"
  15. #include "core/memory.h"
  16. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17. // ELF Header Constants
  18. // File type
  19. enum ElfType {
  20. ET_NONE = 0,
  21. ET_REL = 1,
  22. ET_EXEC = 2,
  23. ET_DYN = 3,
  24. ET_CORE = 4,
  25. ET_LOPROC = 0xFF00,
  26. ET_HIPROC = 0xFFFF,
  27. };
  28. // Machine/Architecture
  29. enum ElfMachine {
  30. EM_NONE = 0,
  31. EM_M32 = 1,
  32. EM_SPARC = 2,
  33. EM_386 = 3,
  34. EM_68K = 4,
  35. EM_88K = 5,
  36. EM_860 = 7,
  37. EM_MIPS = 8
  38. };
  39. // File version
  40. #define EV_NONE 0
  41. #define EV_CURRENT 1
  42. // Identification index
  43. #define EI_MAG0 0
  44. #define EI_MAG1 1
  45. #define EI_MAG2 2
  46. #define EI_MAG3 3
  47. #define EI_CLASS 4
  48. #define EI_DATA 5
  49. #define EI_VERSION 6
  50. #define EI_PAD 7
  51. #define EI_NIDENT 16
  52. // Sections constants
  53. // Section types
  54. #define SHT_NULL 0
  55. #define SHT_PROGBITS 1
  56. #define SHT_SYMTAB 2
  57. #define SHT_STRTAB 3
  58. #define SHT_RELA 4
  59. #define SHT_HASH 5
  60. #define SHT_DYNAMIC 6
  61. #define SHT_NOTE 7
  62. #define SHT_NOBITS 8
  63. #define SHT_REL 9
  64. #define SHT_SHLIB 10
  65. #define SHT_DYNSYM 11
  66. #define SHT_LOPROC 0x70000000
  67. #define SHT_HIPROC 0x7FFFFFFF
  68. #define SHT_LOUSER 0x80000000
  69. #define SHT_HIUSER 0xFFFFFFFF
  70. // Section flags
  71. enum ElfSectionFlags {
  72. SHF_WRITE = 0x1,
  73. SHF_ALLOC = 0x2,
  74. SHF_EXECINSTR = 0x4,
  75. SHF_MASKPROC = 0xF0000000,
  76. };
  77. // Segment types
  78. #define PT_NULL 0
  79. #define PT_LOAD 1
  80. #define PT_DYNAMIC 2
  81. #define PT_INTERP 3
  82. #define PT_NOTE 4
  83. #define PT_SHLIB 5
  84. #define PT_PHDR 6
  85. #define PT_LOPROC 0x70000000
  86. #define PT_HIPROC 0x7FFFFFFF
  87. // Segment flags
  88. #define PF_X 0x1
  89. #define PF_W 0x2
  90. #define PF_R 0x4
  91. #define PF_MASKPROC 0xF0000000
  92. typedef unsigned int Elf32_Addr;
  93. typedef unsigned short Elf32_Half;
  94. typedef unsigned int Elf32_Off;
  95. typedef signed int Elf32_Sword;
  96. typedef unsigned int Elf32_Word;
  97. ////////////////////////////////////////////////////////////////////////////////////////////////////
  98. // ELF file header
  99. struct Elf32_Ehdr {
  100. unsigned char e_ident[EI_NIDENT];
  101. Elf32_Half e_type;
  102. Elf32_Half e_machine;
  103. Elf32_Word e_version;
  104. Elf32_Addr e_entry;
  105. Elf32_Off e_phoff;
  106. Elf32_Off e_shoff;
  107. Elf32_Word e_flags;
  108. Elf32_Half e_ehsize;
  109. Elf32_Half e_phentsize;
  110. Elf32_Half e_phnum;
  111. Elf32_Half e_shentsize;
  112. Elf32_Half e_shnum;
  113. Elf32_Half e_shstrndx;
  114. };
  115. // Section header
  116. struct Elf32_Shdr {
  117. Elf32_Word sh_name;
  118. Elf32_Word sh_type;
  119. Elf32_Word sh_flags;
  120. Elf32_Addr sh_addr;
  121. Elf32_Off sh_offset;
  122. Elf32_Word sh_size;
  123. Elf32_Word sh_link;
  124. Elf32_Word sh_info;
  125. Elf32_Word sh_addralign;
  126. Elf32_Word sh_entsize;
  127. };
  128. // Segment header
  129. struct Elf32_Phdr {
  130. Elf32_Word p_type;
  131. Elf32_Off p_offset;
  132. Elf32_Addr p_vaddr;
  133. Elf32_Addr p_paddr;
  134. Elf32_Word p_filesz;
  135. Elf32_Word p_memsz;
  136. Elf32_Word p_flags;
  137. Elf32_Word p_align;
  138. };
  139. // Symbol table entry
  140. struct Elf32_Sym {
  141. Elf32_Word st_name;
  142. Elf32_Addr st_value;
  143. Elf32_Word st_size;
  144. unsigned char st_info;
  145. unsigned char st_other;
  146. Elf32_Half st_shndx;
  147. };
  148. // Relocation entries
  149. struct Elf32_Rel {
  150. Elf32_Addr r_offset;
  151. Elf32_Word r_info;
  152. };
  153. ////////////////////////////////////////////////////////////////////////////////////////////////////
  154. // ElfReader class
  155. typedef int SectionID;
  156. class ElfReader {
  157. private:
  158. char* base;
  159. u32* base32;
  160. Elf32_Ehdr* header;
  161. Elf32_Phdr* segments;
  162. Elf32_Shdr* sections;
  163. u32* sectionAddrs;
  164. bool relocate;
  165. VAddr entryPoint;
  166. public:
  167. explicit ElfReader(void* ptr);
  168. u32 Read32(int off) const {
  169. return base32[off >> 2];
  170. }
  171. // Quick accessors
  172. ElfType GetType() const {
  173. return (ElfType)(header->e_type);
  174. }
  175. ElfMachine GetMachine() const {
  176. return (ElfMachine)(header->e_machine);
  177. }
  178. VAddr GetEntryPoint() const {
  179. return entryPoint;
  180. }
  181. u32 GetFlags() const {
  182. return (u32)(header->e_flags);
  183. }
  184. Kernel::CodeSet LoadInto(VAddr vaddr);
  185. int GetNumSegments() const {
  186. return (int)(header->e_phnum);
  187. }
  188. int GetNumSections() const {
  189. return (int)(header->e_shnum);
  190. }
  191. const u8* GetPtr(int offset) const {
  192. return (u8*)base + offset;
  193. }
  194. const char* GetSectionName(int section) const;
  195. const u8* GetSectionDataPtr(int section) const {
  196. if (section < 0 || section >= header->e_shnum)
  197. return nullptr;
  198. if (sections[section].sh_type != SHT_NOBITS)
  199. return GetPtr(sections[section].sh_offset);
  200. else
  201. return nullptr;
  202. }
  203. bool IsCodeSection(int section) const {
  204. return sections[section].sh_type == SHT_PROGBITS;
  205. }
  206. const u8* GetSegmentPtr(int segment) {
  207. return GetPtr(segments[segment].p_offset);
  208. }
  209. u32 GetSectionAddr(SectionID section) const {
  210. return sectionAddrs[section];
  211. }
  212. unsigned int GetSectionSize(SectionID section) const {
  213. return sections[section].sh_size;
  214. }
  215. SectionID GetSectionByName(const char* name, int firstSection = 0) const; //-1 for not found
  216. bool DidRelocate() const {
  217. return relocate;
  218. }
  219. };
  220. ElfReader::ElfReader(void* ptr) {
  221. base = (char*)ptr;
  222. base32 = (u32*)ptr;
  223. header = (Elf32_Ehdr*)ptr;
  224. segments = (Elf32_Phdr*)(base + header->e_phoff);
  225. sections = (Elf32_Shdr*)(base + header->e_shoff);
  226. entryPoint = header->e_entry;
  227. }
  228. const char* ElfReader::GetSectionName(int section) const {
  229. if (sections[section].sh_type == SHT_NULL)
  230. return nullptr;
  231. int name_offset = sections[section].sh_name;
  232. const char* ptr = reinterpret_cast<const char*>(GetSectionDataPtr(header->e_shstrndx));
  233. if (ptr)
  234. return ptr + name_offset;
  235. return nullptr;
  236. }
  237. Kernel::CodeSet ElfReader::LoadInto(VAddr vaddr) {
  238. LOG_DEBUG(Loader, "String section: {}", header->e_shstrndx);
  239. // Should we relocate?
  240. relocate = (header->e_type != ET_EXEC);
  241. if (relocate) {
  242. LOG_DEBUG(Loader, "Relocatable module");
  243. entryPoint += vaddr;
  244. } else {
  245. LOG_DEBUG(Loader, "Prerelocated executable");
  246. }
  247. LOG_DEBUG(Loader, "{} segments:", header->e_phnum);
  248. // First pass : Get the bits into RAM
  249. const VAddr base_addr = relocate ? vaddr : 0;
  250. u64 total_image_size = 0;
  251. for (unsigned int i = 0; i < header->e_phnum; ++i) {
  252. const Elf32_Phdr* p = &segments[i];
  253. if (p->p_type == PT_LOAD) {
  254. total_image_size += (p->p_memsz + 0xFFF) & ~0xFFF;
  255. }
  256. }
  257. Kernel::PhysicalMemory program_image(total_image_size);
  258. std::size_t current_image_position = 0;
  259. Kernel::CodeSet codeset;
  260. for (unsigned int i = 0; i < header->e_phnum; ++i) {
  261. const Elf32_Phdr* p = &segments[i];
  262. LOG_DEBUG(Loader, "Type: {} Vaddr: {:08X} Filesz: {:08X} Memsz: {:08X} ", p->p_type,
  263. p->p_vaddr, p->p_filesz, p->p_memsz);
  264. if (p->p_type == PT_LOAD) {
  265. Kernel::CodeSet::Segment* codeset_segment;
  266. u32 permission_flags = p->p_flags & (PF_R | PF_W | PF_X);
  267. if (permission_flags == (PF_R | PF_X)) {
  268. codeset_segment = &codeset.CodeSegment();
  269. } else if (permission_flags == (PF_R)) {
  270. codeset_segment = &codeset.RODataSegment();
  271. } else if (permission_flags == (PF_R | PF_W)) {
  272. codeset_segment = &codeset.DataSegment();
  273. } else {
  274. LOG_ERROR(Loader, "Unexpected ELF PT_LOAD segment id {} with flags {:X}", i,
  275. p->p_flags);
  276. continue;
  277. }
  278. if (codeset_segment->size != 0) {
  279. LOG_ERROR(Loader,
  280. "ELF has more than one segment of the same type. Skipping extra "
  281. "segment (id {})",
  282. i);
  283. continue;
  284. }
  285. const VAddr segment_addr = base_addr + p->p_vaddr;
  286. const u32 aligned_size = (p->p_memsz + 0xFFF) & ~0xFFF;
  287. codeset_segment->offset = current_image_position;
  288. codeset_segment->addr = segment_addr;
  289. codeset_segment->size = aligned_size;
  290. std::memcpy(program_image.data() + current_image_position, GetSegmentPtr(i),
  291. p->p_filesz);
  292. current_image_position += aligned_size;
  293. }
  294. }
  295. codeset.entrypoint = base_addr + header->e_entry;
  296. codeset.memory = std::move(program_image);
  297. LOG_DEBUG(Loader, "Done loading.");
  298. return codeset;
  299. }
  300. SectionID ElfReader::GetSectionByName(const char* name, int firstSection) const {
  301. for (int i = firstSection; i < header->e_shnum; i++) {
  302. const char* secname = GetSectionName(i);
  303. if (secname != nullptr && strcmp(name, secname) == 0)
  304. return i;
  305. }
  306. return -1;
  307. }
  308. ////////////////////////////////////////////////////////////////////////////////////////////////////
  309. // Loader namespace
  310. namespace Loader {
  311. AppLoader_ELF::AppLoader_ELF(FileSys::VirtualFile file) : AppLoader(std::move(file)) {}
  312. FileType AppLoader_ELF::IdentifyType(const FileSys::VirtualFile& file) {
  313. static constexpr u16 ELF_MACHINE_ARM{0x28};
  314. u32 magic = 0;
  315. if (4 != file->ReadObject(&magic))
  316. return FileType::Error;
  317. u16 machine = 0;
  318. if (2 != file->ReadObject(&machine, 18))
  319. return FileType::Error;
  320. if (Common::MakeMagic('\x7f', 'E', 'L', 'F') == magic && ELF_MACHINE_ARM == machine)
  321. return FileType::ELF;
  322. return FileType::Error;
  323. }
  324. AppLoader_ELF::LoadResult AppLoader_ELF::Load(Kernel::Process& process,
  325. [[maybe_unused]] Core::System& system) {
  326. if (is_loaded) {
  327. return {ResultStatus::ErrorAlreadyLoaded, {}};
  328. }
  329. std::vector<u8> buffer = file->ReadAllBytes();
  330. if (buffer.size() != file->GetSize()) {
  331. return {ResultStatus::ErrorIncorrectELFFileSize, {}};
  332. }
  333. const VAddr base_address = process.PageTable().GetCodeRegionStart();
  334. ElfReader elf_reader(&buffer[0]);
  335. Kernel::CodeSet codeset = elf_reader.LoadInto(base_address);
  336. const VAddr entry_point = codeset.entrypoint;
  337. // Setup the process code layout
  338. if (process.LoadFromMetadata(FileSys::ProgramMetadata::GetDefault(), buffer.size()).IsError()) {
  339. return {ResultStatus::ErrorNotInitialized, {}};
  340. }
  341. process.LoadModule(std::move(codeset), entry_point);
  342. is_loaded = true;
  343. return {ResultStatus::Success, LoadParameters{48, Core::Memory::DEFAULT_STACK_SIZE}};
  344. }
  345. } // namespace Loader