elf.cpp 11 KB

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