elf_file.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  1. #include <elf.h>
  2. #include "elf_file.h"
  3. #include "elf_file_i.h"
  4. #include "elf_api_interface.h"
  5. #define TAG "elf"
  6. #define ELF_NAME_BUFFER_LEN 32
  7. #define SECTION_OFFSET(e, n) (e->section_table + n * sizeof(Elf32_Shdr))
  8. #define IS_FLAGS_SET(v, m) ((v & m) == m)
  9. #define RESOLVER_THREAD_YIELD_STEP 30
  10. // #define ELF_DEBUG_LOG 1
  11. #ifndef ELF_DEBUG_LOG
  12. #undef FURI_LOG_D
  13. #define FURI_LOG_D(...)
  14. #endif
  15. #define TRAMPOLINE_CODE_SIZE 6
  16. /**
  17. ldr r12, [pc, #2]
  18. bx r12
  19. */
  20. const uint8_t trampoline_code_little_endian[TRAMPOLINE_CODE_SIZE] =
  21. {0xdf, 0xf8, 0x02, 0xc0, 0x60, 0x47};
  22. typedef struct {
  23. uint8_t code[TRAMPOLINE_CODE_SIZE];
  24. uint32_t addr;
  25. } __attribute__((packed)) JMPTrampoline;
  26. /**************************************************************************************************/
  27. /********************************************* Caches *********************************************/
  28. /**************************************************************************************************/
  29. static bool address_cache_get(AddressCache_t cache, int symEntry, Elf32_Addr* symAddr) {
  30. Elf32_Addr* addr = AddressCache_get(cache, symEntry);
  31. if(addr) {
  32. *symAddr = *addr;
  33. return true;
  34. } else {
  35. return false;
  36. }
  37. }
  38. static void address_cache_put(AddressCache_t cache, int symEntry, Elf32_Addr symAddr) {
  39. AddressCache_set_at(cache, symEntry, symAddr);
  40. }
  41. /**************************************************************************************************/
  42. /********************************************** ELF ***********************************************/
  43. /**************************************************************************************************/
  44. static ELFSection* elf_file_get_section(ELFFile* elf, const char* name) {
  45. return ELFSectionDict_get(elf->sections, name);
  46. }
  47. static ELFSection* elf_file_get_or_put_section(ELFFile* elf, const char* name) {
  48. ELFSection* section_p = elf_file_get_section(elf, name);
  49. if(!section_p) {
  50. ELFSectionDict_set_at(
  51. elf->sections,
  52. strdup(name),
  53. (ELFSection){
  54. .data = NULL,
  55. .sec_idx = 0,
  56. .size = 0,
  57. .rel_count = 0,
  58. .rel_offset = 0,
  59. });
  60. section_p = elf_file_get_section(elf, name);
  61. }
  62. return section_p;
  63. }
  64. static bool elf_read_string_from_offset(ELFFile* elf, off_t offset, FuriString* name) {
  65. bool result = false;
  66. off_t old = storage_file_tell(elf->fd);
  67. do {
  68. if(!storage_file_seek(elf->fd, offset, true)) break;
  69. char buffer[ELF_NAME_BUFFER_LEN + 1];
  70. buffer[ELF_NAME_BUFFER_LEN] = 0;
  71. while(true) {
  72. uint16_t read = storage_file_read(elf->fd, buffer, ELF_NAME_BUFFER_LEN);
  73. furi_string_cat(name, buffer);
  74. if(strlen(buffer) < ELF_NAME_BUFFER_LEN) {
  75. result = true;
  76. break;
  77. }
  78. if(storage_file_get_error(elf->fd) != FSE_OK || read == 0) break;
  79. }
  80. } while(false);
  81. storage_file_seek(elf->fd, old, true);
  82. return result;
  83. }
  84. static bool elf_read_section_name(ELFFile* elf, off_t offset, FuriString* name) {
  85. return elf_read_string_from_offset(elf, elf->section_table_strings + offset, name);
  86. }
  87. static bool elf_read_symbol_name(ELFFile* elf, off_t offset, FuriString* name) {
  88. return elf_read_string_from_offset(elf, elf->symbol_table_strings + offset, name);
  89. }
  90. static bool elf_read_section_header(ELFFile* elf, size_t section_idx, Elf32_Shdr* section_header) {
  91. off_t offset = SECTION_OFFSET(elf, section_idx);
  92. return storage_file_seek(elf->fd, offset, true) &&
  93. storage_file_read(elf->fd, section_header, sizeof(Elf32_Shdr)) == sizeof(Elf32_Shdr);
  94. }
  95. static bool elf_read_section(
  96. ELFFile* elf,
  97. size_t section_idx,
  98. Elf32_Shdr* section_header,
  99. FuriString* name) {
  100. if(!elf_read_section_header(elf, section_idx, section_header)) {
  101. return false;
  102. }
  103. if(section_header->sh_name && !elf_read_section_name(elf, section_header->sh_name, name)) {
  104. return false;
  105. }
  106. return true;
  107. }
  108. static bool elf_read_symbol(ELFFile* elf, int n, Elf32_Sym* sym, FuriString* name) {
  109. bool success = false;
  110. off_t old = storage_file_tell(elf->fd);
  111. off_t pos = elf->symbol_table + n * sizeof(Elf32_Sym);
  112. if(storage_file_seek(elf->fd, pos, true) &&
  113. storage_file_read(elf->fd, sym, sizeof(Elf32_Sym)) == sizeof(Elf32_Sym)) {
  114. if(sym->st_name)
  115. success = elf_read_symbol_name(elf, sym->st_name, name);
  116. else {
  117. Elf32_Shdr shdr;
  118. success = elf_read_section(elf, sym->st_shndx, &shdr, name);
  119. }
  120. }
  121. storage_file_seek(elf->fd, old, true);
  122. return success;
  123. }
  124. static ELFSection* elf_section_of(ELFFile* elf, int index) {
  125. ELFSectionDict_it_t it;
  126. for(ELFSectionDict_it(it, elf->sections); !ELFSectionDict_end_p(it); ELFSectionDict_next(it)) {
  127. ELFSectionDict_itref_t* itref = ELFSectionDict_ref(it);
  128. if(itref->value.sec_idx == index) {
  129. return &itref->value;
  130. }
  131. }
  132. return NULL;
  133. }
  134. static Elf32_Addr elf_address_of(ELFFile* elf, Elf32_Sym* sym, const char* sName) {
  135. if(sym->st_shndx == SHN_UNDEF) {
  136. Elf32_Addr addr = 0;
  137. if(elf->api_interface->resolver_callback(sName, &addr)) {
  138. return addr;
  139. }
  140. } else {
  141. ELFSection* symSec = elf_section_of(elf, sym->st_shndx);
  142. if(symSec) {
  143. return ((Elf32_Addr)symSec->data) + sym->st_value;
  144. }
  145. }
  146. FURI_LOG_D(TAG, " Can not find address for symbol %s", sName);
  147. return ELF_INVALID_ADDRESS;
  148. }
  149. __attribute__((unused)) static const char* elf_reloc_type_to_str(int symt) {
  150. #define STRCASE(name) \
  151. case name: \
  152. return #name;
  153. switch(symt) {
  154. STRCASE(R_ARM_NONE)
  155. STRCASE(R_ARM_TARGET1)
  156. STRCASE(R_ARM_ABS32)
  157. STRCASE(R_ARM_THM_PC22)
  158. STRCASE(R_ARM_THM_JUMP24)
  159. default:
  160. return "R_<unknow>";
  161. }
  162. #undef STRCASE
  163. }
  164. static JMPTrampoline* elf_create_trampoline(Elf32_Addr addr) {
  165. JMPTrampoline* trampoline = malloc(sizeof(JMPTrampoline));
  166. memcpy(trampoline->code, trampoline_code_little_endian, TRAMPOLINE_CODE_SIZE);
  167. trampoline->addr = addr;
  168. return trampoline;
  169. }
  170. static void elf_relocate_jmp_call(ELFFile* elf, Elf32_Addr relAddr, int type, Elf32_Addr symAddr) {
  171. int offset, hi, lo, s, j1, j2, i1, i2, imm10, imm11;
  172. int to_thumb, is_call, blx_bit = 1 << 12;
  173. /* Get initial offset */
  174. hi = ((uint16_t*)relAddr)[0];
  175. lo = ((uint16_t*)relAddr)[1];
  176. s = (hi >> 10) & 1;
  177. j1 = (lo >> 13) & 1;
  178. j2 = (lo >> 11) & 1;
  179. i1 = (j1 ^ s) ^ 1;
  180. i2 = (j2 ^ s) ^ 1;
  181. imm10 = hi & 0x3ff;
  182. imm11 = lo & 0x7ff;
  183. offset = (s << 24) | (i1 << 23) | (i2 << 22) | (imm10 << 12) | (imm11 << 1);
  184. if(offset & 0x01000000) offset -= 0x02000000;
  185. to_thumb = symAddr & 1;
  186. is_call = (type == R_ARM_THM_PC22);
  187. /* Store offset */
  188. int offset_copy = offset;
  189. /* Compute final offset */
  190. offset += symAddr - relAddr;
  191. if(!to_thumb && is_call) {
  192. blx_bit = 0; /* bl -> blx */
  193. offset = (offset + 3) & -4; /* Compute offset from aligned PC */
  194. }
  195. /* Check that relocation is possible
  196. * offset must not be out of range
  197. * if target is to be entered in arm mode:
  198. - bit 1 must not set
  199. - instruction must be a call (bl) or a jump to PLT */
  200. if(!to_thumb || offset >= 0x1000000 || offset < -0x1000000) {
  201. if(to_thumb || (symAddr & 2) || (!is_call)) {
  202. FURI_LOG_D(
  203. TAG,
  204. "can't relocate value at %x, %s, doing trampoline",
  205. relAddr,
  206. elf_reloc_type_to_str(type));
  207. Elf32_Addr addr;
  208. if(!address_cache_get(elf->trampoline_cache, symAddr, &addr)) {
  209. addr = (Elf32_Addr)elf_create_trampoline(symAddr);
  210. address_cache_put(elf->trampoline_cache, symAddr, addr);
  211. }
  212. offset = offset_copy;
  213. offset += (int)addr - relAddr;
  214. if(!to_thumb && is_call) {
  215. blx_bit = 0; /* bl -> blx */
  216. offset = (offset + 3) & -4; /* Compute offset from aligned PC */
  217. }
  218. }
  219. }
  220. /* Compute and store final offset */
  221. s = (offset >> 24) & 1;
  222. i1 = (offset >> 23) & 1;
  223. i2 = (offset >> 22) & 1;
  224. j1 = s ^ (i1 ^ 1);
  225. j2 = s ^ (i2 ^ 1);
  226. imm10 = (offset >> 12) & 0x3ff;
  227. imm11 = (offset >> 1) & 0x7ff;
  228. (*(uint16_t*)relAddr) = (uint16_t)((hi & 0xf800) | (s << 10) | imm10);
  229. (*(uint16_t*)(relAddr + 2)) =
  230. (uint16_t)((lo & 0xc000) | (j1 << 13) | blx_bit | (j2 << 11) | imm11);
  231. }
  232. static void elf_relocate_mov(Elf32_Addr relAddr, int type, Elf32_Addr symAddr) {
  233. uint16_t upper_insn = ((uint16_t*)relAddr)[0];
  234. uint16_t lower_insn = ((uint16_t*)relAddr)[1];
  235. /* MOV*<C> <Rd>,#<imm16>
  236. *
  237. * i = upper[10]
  238. * imm4 = upper[3:0]
  239. * imm3 = lower[14:12]
  240. * imm8 = lower[7:0]
  241. *
  242. * imm16 = imm4:i:imm3:imm8
  243. */
  244. uint32_t i = (upper_insn >> 10) & 1; /* upper[10] */
  245. uint32_t imm4 = upper_insn & 0x000F; /* upper[3:0] */
  246. uint32_t imm3 = (lower_insn >> 12) & 0x7; /* lower[14:12] */
  247. uint32_t imm8 = lower_insn & 0x00FF; /* lower[7:0] */
  248. int32_t addend = (imm4 << 12) | (i << 11) | (imm3 << 8) | imm8; /* imm16 */
  249. uint32_t addr = (symAddr + addend);
  250. if(type == R_ARM_THM_MOVT_ABS) {
  251. addr >>= 16; /* upper 16 bits */
  252. } else {
  253. addr &= 0x0000FFFF; /* lower 16 bits */
  254. }
  255. /* Re-encode */
  256. ((uint16_t*)relAddr)[0] = (upper_insn & 0xFBF0) | (((addr >> 11) & 1) << 10) /* i */
  257. | ((addr >> 12) & 0x000F); /* imm4 */
  258. ((uint16_t*)relAddr)[1] = (lower_insn & 0x8F00) | (((addr >> 8) & 0x7) << 12) /* imm3 */
  259. | (addr & 0x00FF); /* imm8 */
  260. }
  261. static bool elf_relocate_symbol(ELFFile* elf, Elf32_Addr relAddr, int type, Elf32_Addr symAddr) {
  262. switch(type) {
  263. case R_ARM_TARGET1:
  264. case R_ARM_ABS32:
  265. *((uint32_t*)relAddr) += symAddr;
  266. FURI_LOG_D(TAG, " R_ARM_ABS32 relocated is 0x%08X", (unsigned int)*((uint32_t*)relAddr));
  267. break;
  268. case R_ARM_THM_PC22:
  269. case R_ARM_THM_JUMP24:
  270. elf_relocate_jmp_call(elf, relAddr, type, symAddr);
  271. FURI_LOG_D(
  272. TAG, " R_ARM_THM_CALL/JMP relocated is 0x%08X", (unsigned int)*((uint32_t*)relAddr));
  273. break;
  274. case R_ARM_THM_MOVW_ABS_NC:
  275. case R_ARM_THM_MOVT_ABS:
  276. elf_relocate_mov(relAddr, type, symAddr);
  277. FURI_LOG_D(
  278. TAG,
  279. " R_ARM_THM_MOVW_ABS_NC/MOVT_ABS relocated is 0x%08X",
  280. (unsigned int)*((uint32_t*)relAddr));
  281. break;
  282. default:
  283. FURI_LOG_E(TAG, " Undefined relocation %d", type);
  284. return false;
  285. }
  286. return true;
  287. }
  288. static bool elf_relocate(ELFFile* elf, ELFSection* s) {
  289. if(s->data) {
  290. Elf32_Rel rel;
  291. size_t relEntries = s->rel_count;
  292. size_t relCount;
  293. (void)storage_file_seek(elf->fd, s->rel_offset, true);
  294. FURI_LOG_D(TAG, " Offset Info Type Name");
  295. int relocate_result = true;
  296. FuriString* symbol_name;
  297. symbol_name = furi_string_alloc();
  298. for(relCount = 0; relCount < relEntries; relCount++) {
  299. if(relCount % RESOLVER_THREAD_YIELD_STEP == 0) {
  300. FURI_LOG_D(TAG, " reloc YIELD");
  301. furi_delay_tick(1);
  302. }
  303. if(storage_file_read(elf->fd, &rel, sizeof(Elf32_Rel)) != sizeof(Elf32_Rel)) {
  304. FURI_LOG_E(TAG, " reloc read fail");
  305. furi_string_free(symbol_name);
  306. return false;
  307. }
  308. Elf32_Addr symAddr;
  309. int symEntry = ELF32_R_SYM(rel.r_info);
  310. int relType = ELF32_R_TYPE(rel.r_info);
  311. Elf32_Addr relAddr = ((Elf32_Addr)s->data) + rel.r_offset;
  312. if(!address_cache_get(elf->relocation_cache, symEntry, &symAddr)) {
  313. Elf32_Sym sym;
  314. furi_string_reset(symbol_name);
  315. if(!elf_read_symbol(elf, symEntry, &sym, symbol_name)) {
  316. FURI_LOG_E(TAG, " symbol read fail");
  317. furi_string_free(symbol_name);
  318. return false;
  319. }
  320. FURI_LOG_D(
  321. TAG,
  322. " %08X %08X %-16s %s",
  323. (unsigned int)rel.r_offset,
  324. (unsigned int)rel.r_info,
  325. elf_reloc_type_to_str(relType),
  326. furi_string_get_cstr(symbol_name));
  327. symAddr = elf_address_of(elf, &sym, furi_string_get_cstr(symbol_name));
  328. address_cache_put(elf->relocation_cache, symEntry, symAddr);
  329. }
  330. if(symAddr != ELF_INVALID_ADDRESS) {
  331. FURI_LOG_D(
  332. TAG,
  333. " symAddr=%08X relAddr=%08X",
  334. (unsigned int)symAddr,
  335. (unsigned int)relAddr);
  336. if(!elf_relocate_symbol(elf, relAddr, relType, symAddr)) {
  337. relocate_result = false;
  338. }
  339. } else {
  340. FURI_LOG_E(TAG, " No symbol address of %s", furi_string_get_cstr(symbol_name));
  341. relocate_result = false;
  342. }
  343. }
  344. furi_string_free(symbol_name);
  345. return relocate_result;
  346. } else {
  347. FURI_LOG_D(TAG, "Section not loaded");
  348. }
  349. return false;
  350. }
  351. /**************************************************************************************************/
  352. /************************************ Internal FAP interfaces *************************************/
  353. /**************************************************************************************************/
  354. typedef enum {
  355. SectionTypeERROR = 0,
  356. SectionTypeUnused = 1 << 0,
  357. SectionTypeData = 1 << 1,
  358. SectionTypeRelData = 1 << 2,
  359. SectionTypeSymTab = 1 << 3,
  360. SectionTypeStrTab = 1 << 4,
  361. SectionTypeManifest = 1 << 5,
  362. SectionTypeDebugLink = 1 << 6,
  363. SectionTypeValid = SectionTypeSymTab | SectionTypeStrTab | SectionTypeManifest,
  364. } SectionType;
  365. static bool elf_load_metadata(
  366. ELFFile* elf,
  367. Elf32_Shdr* section_header,
  368. FlipperApplicationManifest* manifest) {
  369. if(section_header->sh_size < sizeof(FlipperApplicationManifest)) {
  370. return false;
  371. }
  372. if(manifest == NULL) {
  373. return true;
  374. }
  375. return storage_file_seek(elf->fd, section_header->sh_offset, true) &&
  376. storage_file_read(elf->fd, manifest, section_header->sh_size) ==
  377. section_header->sh_size;
  378. }
  379. static bool elf_load_debug_link(ELFFile* elf, Elf32_Shdr* section_header) {
  380. elf->debug_link_info.debug_link_size = section_header->sh_size;
  381. elf->debug_link_info.debug_link = malloc(section_header->sh_size);
  382. return storage_file_seek(elf->fd, section_header->sh_offset, true) &&
  383. storage_file_read(elf->fd, elf->debug_link_info.debug_link, section_header->sh_size) ==
  384. section_header->sh_size;
  385. }
  386. static bool str_prefix(const char* str, const char* prefix) {
  387. return strncmp(prefix, str, strlen(prefix)) == 0;
  388. }
  389. static bool elf_load_section_data(ELFFile* elf, ELFSection* section, Elf32_Shdr* section_header) {
  390. if(section_header->sh_size == 0) {
  391. FURI_LOG_D(TAG, "No data for section");
  392. return true;
  393. }
  394. section->data = aligned_malloc(section_header->sh_size, section_header->sh_addralign);
  395. section->size = section_header->sh_size;
  396. if(section_header->sh_type == SHT_NOBITS) {
  397. // BSS section, no data to load
  398. return true;
  399. }
  400. if((!storage_file_seek(elf->fd, section_header->sh_offset, true)) ||
  401. (storage_file_read(elf->fd, section->data, section_header->sh_size) !=
  402. section_header->sh_size)) {
  403. FURI_LOG_E(TAG, " seek/read fail");
  404. return false;
  405. }
  406. FURI_LOG_D(TAG, "0x%X", section->data);
  407. return true;
  408. }
  409. static SectionType elf_preload_section(
  410. ELFFile* elf,
  411. size_t section_idx,
  412. Elf32_Shdr* section_header,
  413. FuriString* name_string,
  414. FlipperApplicationManifest* manifest) {
  415. const char* name = furi_string_get_cstr(name_string);
  416. #ifdef ELF_DEBUG_LOG
  417. // log section name, type and flags
  418. FuriString* flags_string = furi_string_alloc();
  419. if(section_header->sh_flags & SHF_WRITE) furi_string_cat(flags_string, "W");
  420. if(section_header->sh_flags & SHF_ALLOC) furi_string_cat(flags_string, "A");
  421. if(section_header->sh_flags & SHF_EXECINSTR) furi_string_cat(flags_string, "X");
  422. if(section_header->sh_flags & SHF_MERGE) furi_string_cat(flags_string, "M");
  423. if(section_header->sh_flags & SHF_STRINGS) furi_string_cat(flags_string, "S");
  424. if(section_header->sh_flags & SHF_INFO_LINK) furi_string_cat(flags_string, "I");
  425. if(section_header->sh_flags & SHF_LINK_ORDER) furi_string_cat(flags_string, "L");
  426. if(section_header->sh_flags & SHF_OS_NONCONFORMING) furi_string_cat(flags_string, "O");
  427. if(section_header->sh_flags & SHF_GROUP) furi_string_cat(flags_string, "G");
  428. if(section_header->sh_flags & SHF_TLS) furi_string_cat(flags_string, "T");
  429. if(section_header->sh_flags & SHF_COMPRESSED) furi_string_cat(flags_string, "T");
  430. if(section_header->sh_flags & SHF_MASKOS) furi_string_cat(flags_string, "o");
  431. if(section_header->sh_flags & SHF_MASKPROC) furi_string_cat(flags_string, "p");
  432. if(section_header->sh_flags & SHF_ORDERED) furi_string_cat(flags_string, "R");
  433. if(section_header->sh_flags & SHF_EXCLUDE) furi_string_cat(flags_string, "E");
  434. FURI_LOG_I(
  435. TAG,
  436. "Section %s: type: %ld, flags: %s",
  437. name,
  438. section_header->sh_type,
  439. furi_string_get_cstr(flags_string));
  440. furi_string_free(flags_string);
  441. #endif
  442. // ignore .ARM and .rel.ARM sections
  443. // TODO: how to do it not by name?
  444. // .ARM: type 0x70000001, flags SHF_ALLOC | SHF_LINK_ORDER
  445. // .rel.ARM: type 0x9, flags SHT_REL
  446. if(str_prefix(name, ".ARM.") || str_prefix(name, ".rel.ARM.")) {
  447. FURI_LOG_D(TAG, "Ignoring ARM section");
  448. return SectionTypeUnused;
  449. }
  450. // Load allocable section
  451. if(section_header->sh_flags & SHF_ALLOC) {
  452. ELFSection* section_p = elf_file_get_or_put_section(elf, name);
  453. section_p->sec_idx = section_idx;
  454. if(section_header->sh_type == SHT_PREINIT_ARRAY) {
  455. elf->preinit_array = section_p;
  456. } else if(section_header->sh_type == SHT_INIT_ARRAY) {
  457. elf->init_array = section_p;
  458. } else if(section_header->sh_type == SHT_FINI_ARRAY) {
  459. elf->fini_array = section_p;
  460. }
  461. if(!elf_load_section_data(elf, section_p, section_header)) {
  462. FURI_LOG_E(TAG, "Error loading section '%s'", name);
  463. return SectionTypeERROR;
  464. } else {
  465. return SectionTypeData;
  466. }
  467. }
  468. // Load link info section
  469. if(section_header->sh_flags & SHF_INFO_LINK) {
  470. name = name + strlen(".rel");
  471. ELFSection* section_p = elf_file_get_or_put_section(elf, name);
  472. section_p->rel_count = section_header->sh_size / sizeof(Elf32_Rel);
  473. section_p->rel_offset = section_header->sh_offset;
  474. return SectionTypeRelData;
  475. }
  476. // Load symbol table
  477. if(strcmp(name, ".symtab") == 0) {
  478. FURI_LOG_D(TAG, "Found .symtab section");
  479. elf->symbol_table = section_header->sh_offset;
  480. elf->symbol_count = section_header->sh_size / sizeof(Elf32_Sym);
  481. return SectionTypeSymTab;
  482. }
  483. // Load string table
  484. if(strcmp(name, ".strtab") == 0) {
  485. FURI_LOG_D(TAG, "Found .strtab section");
  486. elf->symbol_table_strings = section_header->sh_offset;
  487. return SectionTypeStrTab;
  488. }
  489. // Load manifest section
  490. if(strcmp(name, ".fapmeta") == 0) {
  491. FURI_LOG_D(TAG, "Found .fapmeta section");
  492. if(elf_load_metadata(elf, section_header, manifest)) {
  493. return SectionTypeManifest;
  494. } else {
  495. return SectionTypeERROR;
  496. }
  497. }
  498. // Load debug link section
  499. if(strcmp(name, ".gnu_debuglink") == 0) {
  500. FURI_LOG_D(TAG, "Found .gnu_debuglink section");
  501. if(elf_load_debug_link(elf, section_header)) {
  502. return SectionTypeDebugLink;
  503. } else {
  504. return SectionTypeERROR;
  505. }
  506. }
  507. return SectionTypeUnused;
  508. }
  509. static bool elf_relocate_section(ELFFile* elf, ELFSection* section) {
  510. if(section->rel_count) {
  511. FURI_LOG_D(TAG, "Relocating section");
  512. return elf_relocate(elf, section);
  513. } else {
  514. FURI_LOG_D(TAG, "No relocation index"); /* Not an error */
  515. }
  516. return true;
  517. }
  518. static void elf_file_call_section_list(ELFSection* section, bool reverse_order) {
  519. if(section && section->size) {
  520. const uint32_t* start = section->data;
  521. const uint32_t* end = section->data + section->size;
  522. if(reverse_order) {
  523. while(end > start) {
  524. end--;
  525. ((void (*)(void))(*end))();
  526. }
  527. } else {
  528. while(start < end) {
  529. ((void (*)(void))(*start))();
  530. start++;
  531. }
  532. }
  533. }
  534. }
  535. /**************************************************************************************************/
  536. /********************************************* Public *********************************************/
  537. /**************************************************************************************************/
  538. ELFFile* elf_file_alloc(Storage* storage, const ElfApiInterface* api_interface) {
  539. ELFFile* elf = malloc(sizeof(ELFFile));
  540. elf->fd = storage_file_alloc(storage);
  541. elf->api_interface = api_interface;
  542. ELFSectionDict_init(elf->sections);
  543. AddressCache_init(elf->trampoline_cache);
  544. return elf;
  545. }
  546. void elf_file_free(ELFFile* elf) {
  547. // free sections data
  548. {
  549. ELFSectionDict_it_t it;
  550. for(ELFSectionDict_it(it, elf->sections); !ELFSectionDict_end_p(it);
  551. ELFSectionDict_next(it)) {
  552. const ELFSectionDict_itref_t* itref = ELFSectionDict_cref(it);
  553. if(itref->value.data) {
  554. aligned_free(itref->value.data);
  555. }
  556. free((void*)itref->key);
  557. }
  558. ELFSectionDict_clear(elf->sections);
  559. }
  560. // free trampoline data
  561. {
  562. AddressCache_it_t it;
  563. for(AddressCache_it(it, elf->trampoline_cache); !AddressCache_end_p(it);
  564. AddressCache_next(it)) {
  565. const AddressCache_itref_t* itref = AddressCache_cref(it);
  566. free((void*)itref->value);
  567. }
  568. AddressCache_clear(elf->trampoline_cache);
  569. }
  570. if(elf->debug_link_info.debug_link) {
  571. free(elf->debug_link_info.debug_link);
  572. }
  573. storage_file_free(elf->fd);
  574. free(elf);
  575. }
  576. bool elf_file_open(ELFFile* elf, const char* path) {
  577. Elf32_Ehdr h;
  578. Elf32_Shdr sH;
  579. if(!storage_file_open(elf->fd, path, FSAM_READ, FSOM_OPEN_EXISTING) ||
  580. !storage_file_seek(elf->fd, 0, true) ||
  581. storage_file_read(elf->fd, &h, sizeof(h)) != sizeof(h) ||
  582. !storage_file_seek(elf->fd, h.e_shoff + h.e_shstrndx * sizeof(sH), true) ||
  583. storage_file_read(elf->fd, &sH, sizeof(Elf32_Shdr)) != sizeof(Elf32_Shdr)) {
  584. return false;
  585. }
  586. elf->entry = h.e_entry;
  587. elf->sections_count = h.e_shnum;
  588. elf->section_table = h.e_shoff;
  589. elf->section_table_strings = sH.sh_offset;
  590. return true;
  591. }
  592. bool elf_file_load_manifest(ELFFile* elf, FlipperApplicationManifest* manifest) {
  593. bool result = false;
  594. FuriString* name;
  595. name = furi_string_alloc();
  596. FURI_LOG_D(TAG, "Looking for manifest section");
  597. for(size_t section_idx = 1; section_idx < elf->sections_count; section_idx++) {
  598. Elf32_Shdr section_header;
  599. furi_string_reset(name);
  600. if(!elf_read_section(elf, section_idx, &section_header, name)) {
  601. break;
  602. }
  603. if(furi_string_cmp(name, ".fapmeta") == 0) {
  604. if(elf_load_metadata(elf, &section_header, manifest)) {
  605. FURI_LOG_D(TAG, "Load manifest done");
  606. result = true;
  607. break;
  608. } else {
  609. break;
  610. }
  611. }
  612. }
  613. furi_string_free(name);
  614. return result;
  615. }
  616. bool elf_file_load_section_table(ELFFile* elf, FlipperApplicationManifest* manifest) {
  617. SectionType loaded_sections = SectionTypeERROR;
  618. FuriString* name;
  619. name = furi_string_alloc();
  620. FURI_LOG_D(TAG, "Scan ELF indexs...");
  621. for(size_t section_idx = 1; section_idx < elf->sections_count; section_idx++) {
  622. Elf32_Shdr section_header;
  623. furi_string_reset(name);
  624. if(!elf_read_section(elf, section_idx, &section_header, name)) {
  625. loaded_sections = SectionTypeERROR;
  626. break;
  627. }
  628. FURI_LOG_D(
  629. TAG, "Preloading data for section #%d %s", section_idx, furi_string_get_cstr(name));
  630. SectionType section_type =
  631. elf_preload_section(elf, section_idx, &section_header, name, manifest);
  632. loaded_sections |= section_type;
  633. if(section_type == SectionTypeERROR) {
  634. loaded_sections = SectionTypeERROR;
  635. break;
  636. }
  637. }
  638. furi_string_free(name);
  639. return IS_FLAGS_SET(loaded_sections, SectionTypeValid);
  640. }
  641. ELFFileLoadStatus elf_file_load_sections(ELFFile* elf) {
  642. ELFFileLoadStatus status = ELFFileLoadStatusSuccess;
  643. ELFSectionDict_it_t it;
  644. AddressCache_init(elf->relocation_cache);
  645. if(status == ELFFileLoadStatusSuccess) {
  646. for(ELFSectionDict_it(it, elf->sections); !ELFSectionDict_end_p(it);
  647. ELFSectionDict_next(it)) {
  648. ELFSectionDict_itref_t* itref = ELFSectionDict_ref(it);
  649. FURI_LOG_D(TAG, "Relocating section '%s'", itref->key);
  650. if(!elf_relocate_section(elf, &itref->value)) {
  651. FURI_LOG_E(TAG, "Error relocating section '%s'", itref->key);
  652. status = ELFFileLoadStatusMissingImports;
  653. }
  654. }
  655. }
  656. /* Fixing up entry point */
  657. if(status == ELFFileLoadStatusSuccess) {
  658. ELFSection* text_section = elf_file_get_section(elf, ".text");
  659. if(text_section == NULL) {
  660. FURI_LOG_E(TAG, "No .text section found");
  661. status = ELFFileLoadStatusUnspecifiedError;
  662. } else {
  663. elf->entry += (uint32_t)text_section->data;
  664. }
  665. }
  666. FURI_LOG_D(TAG, "Relocation cache size: %u", AddressCache_size(elf->relocation_cache));
  667. FURI_LOG_D(TAG, "Trampoline cache size: %u", AddressCache_size(elf->trampoline_cache));
  668. AddressCache_clear(elf->relocation_cache);
  669. return status;
  670. }
  671. void elf_file_pre_run(ELFFile* elf) {
  672. elf_file_call_section_list(elf->preinit_array, false);
  673. elf_file_call_section_list(elf->init_array, false);
  674. }
  675. int32_t elf_file_run(ELFFile* elf, void* args) {
  676. int32_t result;
  677. result = ((int32_t(*)(void*))elf->entry)(args);
  678. return result;
  679. }
  680. void elf_file_post_run(ELFFile* elf) {
  681. elf_file_call_section_list(elf->fini_array, true);
  682. }
  683. const ElfApiInterface* elf_file_get_api_interface(ELFFile* elf_file) {
  684. return elf_file->api_interface;
  685. }
  686. void elf_file_init_debug_info(ELFFile* elf, ELFDebugInfo* debug_info) {
  687. // set entry
  688. debug_info->entry = elf->entry;
  689. // copy debug info
  690. memcpy(&debug_info->debug_link_info, &elf->debug_link_info, sizeof(ELFDebugLinkInfo));
  691. // init mmap
  692. debug_info->mmap_entry_count = ELFSectionDict_size(elf->sections);
  693. debug_info->mmap_entries = malloc(sizeof(ELFMemoryMapEntry) * debug_info->mmap_entry_count);
  694. uint32_t mmap_entry_idx = 0;
  695. ELFSectionDict_it_t it;
  696. for(ELFSectionDict_it(it, elf->sections); !ELFSectionDict_end_p(it); ELFSectionDict_next(it)) {
  697. const ELFSectionDict_itref_t* itref = ELFSectionDict_cref(it);
  698. const void* data_ptr = itref->value.data;
  699. if(data_ptr) {
  700. debug_info->mmap_entries[mmap_entry_idx].address = (uint32_t)data_ptr;
  701. debug_info->mmap_entries[mmap_entry_idx].name = itref->key;
  702. mmap_entry_idx++;
  703. }
  704. }
  705. }
  706. void elf_file_clear_debug_info(ELFDebugInfo* debug_info) {
  707. // clear debug info
  708. memset(&debug_info->debug_link_info, 0, sizeof(ELFDebugLinkInfo));
  709. // clear mmap
  710. if(debug_info->mmap_entries) {
  711. free(debug_info->mmap_entries);
  712. debug_info->mmap_entries = NULL;
  713. }
  714. debug_info->mmap_entry_count = 0;
  715. }