elf_file.c 28 KB

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