elf.cpp 11 KB

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