DynamicLoader.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  1. /*
  2. * Copyright (c) 2019-2020, Andrew Kaster <akaster@serenityos.org>
  3. * Copyright (c) 2020, Itamar S. <itamar8910@gmail.com>
  4. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  5. * Copyright (c) 2022, Daniel Bertalan <dani@danielbertalan.dev>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include <AK/Optional.h>
  10. #include <AK/QuickSort.h>
  11. #include <AK/StringBuilder.h>
  12. #include <LibELF/DynamicLinker.h>
  13. #include <LibELF/DynamicLoader.h>
  14. #include <LibELF/Hashes.h>
  15. #include <LibELF/Validation.h>
  16. #include <assert.h>
  17. #include <bits/dlfcn_integration.h>
  18. #include <dlfcn.h>
  19. #include <errno.h>
  20. #include <stdio.h>
  21. #include <stdlib.h>
  22. #include <string.h>
  23. #include <sys/mman.h>
  24. #include <sys/stat.h>
  25. #include <unistd.h>
  26. #ifndef AK_OS_SERENITY
  27. static void* mmap_with_name(void* addr, size_t length, int prot, int flags, int fd, off_t offset, char const*)
  28. {
  29. return mmap(addr, length, prot, flags, fd, offset);
  30. }
  31. # define MAP_RANDOMIZED 0
  32. #endif
  33. namespace ELF {
  34. Result<NonnullRefPtr<DynamicLoader>, DlErrorMessage> DynamicLoader::try_create(int fd, DeprecatedString filepath)
  35. {
  36. VERIFY(filepath.starts_with('/'));
  37. struct stat stat;
  38. if (fstat(fd, &stat) < 0) {
  39. return DlErrorMessage { "DynamicLoader::try_create fstat" };
  40. }
  41. VERIFY(stat.st_size >= 0);
  42. auto size = static_cast<size_t>(stat.st_size);
  43. if (size < sizeof(ElfW(Ehdr)))
  44. return DlErrorMessage { DeprecatedString::formatted("File {} has invalid ELF header", filepath) };
  45. DeprecatedString file_mmap_name = DeprecatedString::formatted("ELF_DYN: {}", filepath);
  46. auto* data = mmap_with_name(nullptr, size, PROT_READ, MAP_SHARED, fd, 0, file_mmap_name.characters());
  47. if (data == MAP_FAILED) {
  48. return DlErrorMessage { "DynamicLoader::try_create mmap" };
  49. }
  50. auto loader = adopt_ref(*new DynamicLoader(fd, move(filepath), data, size));
  51. if (!loader->is_valid())
  52. return DlErrorMessage { "ELF image validation failed" };
  53. return loader;
  54. }
  55. DynamicLoader::DynamicLoader(int fd, DeprecatedString filepath, void* data, size_t size)
  56. : m_filepath(move(filepath))
  57. , m_file_size(size)
  58. , m_image_fd(fd)
  59. , m_file_data(data)
  60. {
  61. m_elf_image = adopt_own(*new ELF::Image((u8*)m_file_data, m_file_size));
  62. m_valid = validate();
  63. if (m_valid)
  64. find_tls_size_and_alignment();
  65. else
  66. dbgln("Image validation failed for file {}", m_filepath);
  67. }
  68. DynamicLoader::~DynamicLoader()
  69. {
  70. if (munmap(m_file_data, m_file_size) < 0) {
  71. perror("munmap");
  72. VERIFY_NOT_REACHED();
  73. }
  74. if (close(m_image_fd) < 0) {
  75. perror("close");
  76. VERIFY_NOT_REACHED();
  77. }
  78. }
  79. DynamicObject const& DynamicLoader::dynamic_object() const
  80. {
  81. if (!m_cached_dynamic_object) {
  82. VirtualAddress dynamic_section_address;
  83. image().for_each_program_header([&dynamic_section_address](auto program_header) {
  84. if (program_header.type() == PT_DYNAMIC) {
  85. dynamic_section_address = VirtualAddress(program_header.raw_data());
  86. }
  87. });
  88. VERIFY(!dynamic_section_address.is_null());
  89. m_cached_dynamic_object = ELF::DynamicObject::create(m_filepath, VirtualAddress(image().base_address()), dynamic_section_address);
  90. }
  91. return *m_cached_dynamic_object;
  92. }
  93. void DynamicLoader::find_tls_size_and_alignment()
  94. {
  95. image().for_each_program_header([this](auto program_header) {
  96. if (program_header.type() == PT_TLS) {
  97. m_tls_size_of_current_object = program_header.size_in_memory();
  98. auto alignment = program_header.alignment();
  99. VERIFY(!alignment || is_power_of_two(alignment));
  100. m_tls_alignment_of_current_object = alignment > 1 ? alignment : 0; // No need to reserve extra space for single byte alignment
  101. return IterationDecision::Break;
  102. }
  103. return IterationDecision::Continue;
  104. });
  105. }
  106. bool DynamicLoader::validate()
  107. {
  108. if (!image().is_valid())
  109. return false;
  110. auto* elf_header = (ElfW(Ehdr)*)m_file_data;
  111. if (!validate_elf_header(*elf_header, m_file_size))
  112. return false;
  113. auto result_or_error = validate_program_headers(*elf_header, m_file_size, { m_file_data, m_file_size });
  114. if (result_or_error.is_error() || !result_or_error.value())
  115. return false;
  116. return true;
  117. }
  118. RefPtr<DynamicObject> DynamicLoader::map()
  119. {
  120. if (m_dynamic_object) {
  121. // Already mapped.
  122. return nullptr;
  123. }
  124. if (!m_valid) {
  125. dbgln("DynamicLoader::map failed: image is invalid");
  126. return nullptr;
  127. }
  128. load_program_headers();
  129. VERIFY(!m_base_address.is_null());
  130. m_dynamic_object = DynamicObject::create(m_filepath, m_base_address, m_dynamic_section_address);
  131. m_dynamic_object->set_tls_offset(m_tls_offset);
  132. m_dynamic_object->set_tls_size(m_tls_size_of_current_object);
  133. return m_dynamic_object;
  134. }
  135. bool DynamicLoader::link(unsigned flags)
  136. {
  137. return load_stage_2(flags);
  138. }
  139. bool DynamicLoader::load_stage_2(unsigned flags)
  140. {
  141. VERIFY(flags & RTLD_GLOBAL);
  142. if (m_dynamic_object->has_text_relocations()) {
  143. dbgln("\033[33mWarning:\033[0m Dynamic object {} has text relocations", m_dynamic_object->filepath());
  144. for (auto& text_segment : m_text_segments) {
  145. VERIFY(text_segment.address().get() != 0);
  146. #ifndef AK_OS_MACOS
  147. // Remap this text region as private.
  148. if (mremap(text_segment.address().as_ptr(), text_segment.size(), text_segment.size(), MAP_PRIVATE) == MAP_FAILED) {
  149. perror("mremap .text: MAP_PRIVATE");
  150. return false;
  151. }
  152. #endif
  153. if (0 > mprotect(text_segment.address().as_ptr(), text_segment.size(), PROT_READ | PROT_WRITE)) {
  154. perror("mprotect .text: PROT_READ | PROT_WRITE"); // FIXME: dlerror?
  155. return false;
  156. }
  157. }
  158. } else {
  159. // .text needs to be executable while we process relocations because it might contain IFUNC resolvers.
  160. // We don't allow IFUNC resolvers in objects with textrels.
  161. for (auto& text_segment : m_text_segments) {
  162. if (mprotect(text_segment.address().as_ptr(), text_segment.size(), PROT_READ | PROT_EXEC) < 0) {
  163. perror("mprotect .text: PROT_READ | PROT_EXEC");
  164. return false;
  165. }
  166. }
  167. }
  168. do_main_relocations();
  169. return true;
  170. }
  171. void DynamicLoader::do_main_relocations()
  172. {
  173. auto do_single_relocation = [&](const ELF::DynamicObject::Relocation& relocation) {
  174. switch (do_relocation(relocation, ShouldInitializeWeak::No)) {
  175. case RelocationResult::Failed:
  176. dbgln("Loader.so: {} unresolved symbol '{}'", m_filepath, relocation.symbol().name());
  177. VERIFY_NOT_REACHED();
  178. case RelocationResult::ResolveLater:
  179. m_unresolved_relocations.append(relocation);
  180. break;
  181. case RelocationResult::Success:
  182. break;
  183. }
  184. };
  185. do_relr_relocations();
  186. m_dynamic_object->relocation_section().for_each_relocation(do_single_relocation);
  187. m_dynamic_object->plt_relocation_section().for_each_relocation(do_single_relocation);
  188. }
  189. Result<NonnullRefPtr<DynamicObject>, DlErrorMessage> DynamicLoader::load_stage_3(unsigned flags)
  190. {
  191. do_lazy_relocations();
  192. if (flags & RTLD_LAZY) {
  193. if (m_dynamic_object->has_plt())
  194. setup_plt_trampoline();
  195. }
  196. if (m_dynamic_object->has_text_relocations()) {
  197. // If we don't have textrels, .text has already been made executable by this point in load_stage_2.
  198. for (auto& text_segment : m_text_segments) {
  199. if (mprotect(text_segment.address().as_ptr(), text_segment.size(), PROT_READ | PROT_EXEC) < 0) {
  200. return DlErrorMessage { DeprecatedString::formatted("mprotect .text: PROT_READ | PROT_EXEC: {}", strerror(errno)) };
  201. }
  202. }
  203. }
  204. if (m_relro_segment_size) {
  205. if (mprotect(m_relro_segment_address.as_ptr(), m_relro_segment_size, PROT_READ) < 0) {
  206. return DlErrorMessage { DeprecatedString::formatted("mprotect .relro: PROT_READ: {}", strerror(errno)) };
  207. }
  208. #ifdef AK_OS_SERENITY
  209. if (set_mmap_name(m_relro_segment_address.as_ptr(), m_relro_segment_size, DeprecatedString::formatted("{}: .relro", m_filepath).characters()) < 0) {
  210. return DlErrorMessage { DeprecatedString::formatted("set_mmap_name .relro: {}", strerror(errno)) };
  211. }
  212. #endif
  213. }
  214. m_fully_relocated = true;
  215. return NonnullRefPtr<DynamicObject> { *m_dynamic_object };
  216. }
  217. void DynamicLoader::load_stage_4()
  218. {
  219. call_object_init_functions();
  220. m_fully_initialized = true;
  221. }
  222. void DynamicLoader::do_lazy_relocations()
  223. {
  224. for (auto const& relocation : m_unresolved_relocations) {
  225. if (auto res = do_relocation(relocation, ShouldInitializeWeak::Yes); res != RelocationResult::Success) {
  226. dbgln("Loader.so: {} unresolved symbol '{}'", m_filepath, relocation.symbol().name());
  227. VERIFY_NOT_REACHED();
  228. }
  229. }
  230. }
  231. void DynamicLoader::load_program_headers()
  232. {
  233. FlatPtr ph_load_start = SIZE_MAX;
  234. FlatPtr ph_load_end = 0;
  235. // We walk the program header list once to find the requested address ranges of the program.
  236. // We don't fill in the list of regions yet to keep malloc memory blocks from interfering with our reservation.
  237. image().for_each_program_header([&](Image::ProgramHeader const& program_header) {
  238. if (program_header.type() != PT_LOAD)
  239. return;
  240. FlatPtr section_start = program_header.vaddr().get();
  241. FlatPtr section_end = section_start + program_header.size_in_memory();
  242. if (ph_load_start > section_start)
  243. ph_load_start = section_start;
  244. if (ph_load_end < section_end)
  245. ph_load_end = section_end;
  246. });
  247. void* requested_load_address = image().is_dynamic() ? nullptr : reinterpret_cast<void*>(ph_load_start);
  248. int reservation_mmap_flags = MAP_ANON | MAP_PRIVATE | MAP_NORESERVE;
  249. if (image().is_dynamic())
  250. reservation_mmap_flags |= MAP_RANDOMIZED;
  251. #ifdef MAP_FIXED_NOREPLACE
  252. else
  253. reservation_mmap_flags |= MAP_FIXED_NOREPLACE;
  254. #endif
  255. // First, we make a dummy reservation mapping, in order to allocate enough VM
  256. // to hold all regions contiguously in the address space.
  257. FlatPtr ph_load_base = ph_load_start & ~(FlatPtr)0xfffu;
  258. ph_load_end = round_up_to_power_of_two(ph_load_end, PAGE_SIZE);
  259. size_t total_mapping_size = ph_load_end - ph_load_base;
  260. // Before we make our reservation, unmap our existing mapped ELF image that we used for reading header information.
  261. // This leaves our pointers dangling momentarily, but it reduces the chance that we will conflict with ourselves.
  262. if (munmap(m_file_data, m_file_size) < 0) {
  263. perror("munmap old mapping");
  264. VERIFY_NOT_REACHED();
  265. }
  266. m_elf_image = nullptr;
  267. m_file_data = nullptr;
  268. auto* reservation = mmap(requested_load_address, total_mapping_size, PROT_NONE, reservation_mmap_flags, 0, 0);
  269. if (reservation == MAP_FAILED) {
  270. perror("mmap reservation");
  271. VERIFY_NOT_REACHED();
  272. }
  273. // Now that we can't accidentally block our requested space, re-map our ELF image.
  274. DeprecatedString file_mmap_name = DeprecatedString::formatted("ELF_DYN: {}", m_filepath);
  275. auto* data = mmap_with_name(nullptr, m_file_size, PROT_READ, MAP_SHARED, m_image_fd, 0, file_mmap_name.characters());
  276. if (data == MAP_FAILED) {
  277. perror("mmap new mapping");
  278. VERIFY_NOT_REACHED();
  279. }
  280. m_file_data = data;
  281. m_elf_image = adopt_own(*new ELF::Image((u8*)m_file_data, m_file_size));
  282. VERIFY(requested_load_address == nullptr || reservation == requested_load_address);
  283. m_base_address = VirtualAddress { reservation };
  284. // Then we unmap the reservation.
  285. if (munmap(reservation, total_mapping_size) < 0) {
  286. perror("munmap reservation");
  287. VERIFY_NOT_REACHED();
  288. }
  289. // Most binaries have four loadable regions, three of which are mapped
  290. // (symbol tables/relocation information, executable instructions, read-only data)
  291. // and one of which is copied (modifiable data).
  292. // These are allocated in-line to cut down on the malloc calls.
  293. Vector<ProgramHeaderRegion, 3> map_regions;
  294. Vector<ProgramHeaderRegion, 1> copy_regions;
  295. Optional<ProgramHeaderRegion> relro_region;
  296. VirtualAddress dynamic_region_desired_vaddr;
  297. image().for_each_program_header([&](Image::ProgramHeader const& program_header) {
  298. ProgramHeaderRegion region {};
  299. region.set_program_header(program_header.raw_header());
  300. if (region.is_tls_template()) {
  301. // Skip, this is handled in DynamicLoader::copy_initial_tls_data_into.
  302. } else if (region.is_load()) {
  303. if (region.size_in_memory() == 0)
  304. return;
  305. if (region.is_writable()) {
  306. copy_regions.append(region);
  307. } else {
  308. map_regions.append(region);
  309. }
  310. } else if (region.is_dynamic()) {
  311. dynamic_region_desired_vaddr = region.desired_load_address();
  312. } else if (region.is_relro()) {
  313. VERIFY(!relro_region.has_value());
  314. relro_region = region;
  315. }
  316. });
  317. VERIFY(!map_regions.is_empty() || !copy_regions.is_empty());
  318. auto compare_load_address = [](ProgramHeaderRegion& a, ProgramHeaderRegion& b) {
  319. return a.desired_load_address().as_ptr() < b.desired_load_address().as_ptr();
  320. };
  321. quick_sort(map_regions, compare_load_address);
  322. quick_sort(copy_regions, compare_load_address);
  323. // Process regions in order: .text, .data, .tls
  324. for (auto& region : map_regions) {
  325. FlatPtr ph_desired_base = region.desired_load_address().get();
  326. FlatPtr ph_base = region.desired_load_address().page_base().get();
  327. FlatPtr ph_end = ph_base + round_up_to_power_of_two(region.size_in_memory() + region.desired_load_address().get() - ph_base, PAGE_SIZE);
  328. StringBuilder builder;
  329. builder.append(m_filepath);
  330. if (region.is_executable())
  331. builder.append(": .text"sv);
  332. else
  333. builder.append(": .rodata"sv);
  334. // Now we can map the text segment at the reserved address.
  335. auto* segment_base = (u8*)mmap_with_name(
  336. (u8*)reservation + ph_base - ph_load_base,
  337. ph_desired_base - ph_base + region.size_in_image(),
  338. PROT_READ,
  339. MAP_FILE | MAP_SHARED | MAP_FIXED,
  340. m_image_fd,
  341. VirtualAddress { region.offset() }.page_base().get(),
  342. builder.to_deprecated_string().characters());
  343. if (segment_base == MAP_FAILED) {
  344. perror("mmap non-writable");
  345. VERIFY_NOT_REACHED();
  346. }
  347. if (region.is_executable())
  348. m_text_segments.append({ VirtualAddress { segment_base }, ph_end - ph_base });
  349. }
  350. VERIFY(requested_load_address == nullptr || requested_load_address == reservation);
  351. if (relro_region.has_value()) {
  352. m_relro_segment_size = relro_region->size_in_memory();
  353. m_relro_segment_address = VirtualAddress { (u8*)reservation + relro_region->desired_load_address().get() - ph_load_base };
  354. }
  355. if (image().is_dynamic())
  356. m_dynamic_section_address = VirtualAddress { (u8*)reservation + dynamic_region_desired_vaddr.get() - ph_load_base };
  357. else
  358. m_dynamic_section_address = dynamic_region_desired_vaddr;
  359. for (auto& region : copy_regions) {
  360. FlatPtr ph_data_base = region.desired_load_address().page_base().get();
  361. FlatPtr ph_data_end = ph_data_base + round_up_to_power_of_two(region.size_in_memory() + region.desired_load_address().get() - ph_data_base, PAGE_SIZE);
  362. auto* data_segment_address = (u8*)reservation + ph_data_base - ph_load_base;
  363. size_t data_segment_size = ph_data_end - ph_data_base;
  364. // Finally, we make an anonymous mapping for the data segment. Contents are then copied from the file.
  365. auto* data_segment = (u8*)mmap_with_name(
  366. data_segment_address,
  367. data_segment_size,
  368. PROT_READ | PROT_WRITE,
  369. MAP_ANONYMOUS | MAP_PRIVATE | MAP_FIXED,
  370. 0,
  371. 0,
  372. DeprecatedString::formatted("{}: .data", m_filepath).characters());
  373. if (MAP_FAILED == data_segment) {
  374. perror("mmap writable");
  375. VERIFY_NOT_REACHED();
  376. }
  377. VirtualAddress data_segment_start;
  378. if (image().is_dynamic())
  379. data_segment_start = VirtualAddress { (u8*)reservation + region.desired_load_address().get() };
  380. else
  381. data_segment_start = region.desired_load_address();
  382. VERIFY(data_segment_start.as_ptr() + region.size_in_memory() <= data_segment + data_segment_size);
  383. memcpy(data_segment_start.as_ptr(), (u8*)m_file_data + region.offset(), region.size_in_image());
  384. }
  385. }
  386. DynamicLoader::RelocationResult DynamicLoader::do_relocation(const ELF::DynamicObject::Relocation& relocation, ShouldInitializeWeak should_initialize_weak)
  387. {
  388. FlatPtr* patch_ptr = nullptr;
  389. if (is_dynamic())
  390. patch_ptr = (FlatPtr*)(m_dynamic_object->base_address().as_ptr() + relocation.offset());
  391. else
  392. patch_ptr = (FlatPtr*)(FlatPtr)relocation.offset();
  393. auto call_ifunc_resolver = [](VirtualAddress address) {
  394. return VirtualAddress { reinterpret_cast<DynamicObject::IfuncResolver>(address.get())() };
  395. };
  396. switch (relocation.type()) {
  397. case R_X86_64_NONE:
  398. // Apparently most loaders will just skip these?
  399. // Seems if the 'link editor' generates one something is funky with your code
  400. break;
  401. case R_AARCH64_ABS64:
  402. case R_X86_64_64: {
  403. auto symbol = relocation.symbol();
  404. auto res = lookup_symbol(symbol);
  405. if (!res.has_value()) {
  406. if (symbol.bind() == STB_WEAK)
  407. return RelocationResult::ResolveLater;
  408. dbgln("ERROR: symbol not found: {}.", symbol.name());
  409. return RelocationResult::Failed;
  410. }
  411. auto symbol_address = res.value().address;
  412. if (relocation.addend_used())
  413. *patch_ptr = symbol_address.get() + relocation.addend();
  414. else
  415. *patch_ptr += symbol_address.get();
  416. if (res.value().type == STT_GNU_IFUNC)
  417. *patch_ptr = call_ifunc_resolver(VirtualAddress { *patch_ptr }).get();
  418. break;
  419. }
  420. case R_AARCH64_GLOB_DAT:
  421. case R_X86_64_GLOB_DAT: {
  422. auto symbol = relocation.symbol();
  423. auto res = lookup_symbol(symbol);
  424. VirtualAddress symbol_location;
  425. if (!res.has_value()) {
  426. if (symbol.bind() == STB_WEAK) {
  427. if (should_initialize_weak == ShouldInitializeWeak::No)
  428. return RelocationResult::ResolveLater;
  429. } else {
  430. // Symbol not found
  431. return RelocationResult::Failed;
  432. }
  433. symbol_location = VirtualAddress { (FlatPtr)0 };
  434. } else {
  435. symbol_location = res.value().address;
  436. if (res.value().type == STT_GNU_IFUNC) {
  437. if (res.value().dynamic_object != nullptr && res.value().dynamic_object->has_text_relocations()) {
  438. dbgln("\033[31mError:\033[0m Refusing to call IFUNC resolver defined in an object with text relocations.");
  439. return RelocationResult::Failed;
  440. }
  441. symbol_location = call_ifunc_resolver(symbol_location);
  442. }
  443. }
  444. VERIFY(symbol_location != m_dynamic_object->base_address());
  445. *patch_ptr = symbol_location.get();
  446. break;
  447. }
  448. case R_AARCH64_RELATIVE:
  449. case R_X86_64_RELATIVE: {
  450. if (!image().is_dynamic())
  451. break;
  452. // FIXME: According to the spec, R_386_relative ones must be done first.
  453. // We could explicitly do them first using m_number_of_relocations from DT_RELCOUNT
  454. // However, our compiler is nice enough to put them at the front of the relocations for us :)
  455. if (relocation.addend_used())
  456. *patch_ptr = m_dynamic_object->base_address().offset(relocation.addend()).get();
  457. else
  458. *patch_ptr += m_dynamic_object->base_address().get();
  459. break;
  460. }
  461. case R_AARCH64_TLS_TPREL64:
  462. case R_X86_64_TPOFF64: {
  463. auto symbol = relocation.symbol();
  464. FlatPtr symbol_value;
  465. DynamicObject const* dynamic_object_of_symbol;
  466. if (relocation.symbol_index() != 0) {
  467. auto res = lookup_symbol(symbol);
  468. if (!res.has_value())
  469. break;
  470. VERIFY(symbol.type() != STT_GNU_IFUNC);
  471. symbol_value = res.value().value;
  472. dynamic_object_of_symbol = res.value().dynamic_object;
  473. } else {
  474. symbol_value = 0;
  475. dynamic_object_of_symbol = &relocation.dynamic_object();
  476. }
  477. VERIFY(dynamic_object_of_symbol);
  478. size_t addend = relocation.addend_used() ? relocation.addend() : *patch_ptr;
  479. *patch_ptr = addend + dynamic_object_of_symbol->tls_offset().value() + symbol_value;
  480. // At offset 0 there's the thread's ThreadSpecificData structure, we don't want to collide with it.
  481. VERIFY(static_cast<ssize_t>(*patch_ptr) < 0);
  482. break;
  483. }
  484. case R_AARCH64_JUMP_SLOT:
  485. case R_X86_64_JUMP_SLOT: {
  486. // FIXME: Or BIND_NOW flag passed in?
  487. if (m_dynamic_object->must_bind_now()) {
  488. // Eagerly BIND_NOW the PLT entries, doing all the symbol looking goodness
  489. // The patch method returns the address for the LAZY fixup path, but we don't need it here
  490. m_dynamic_object->patch_plt_entry(relocation.offset_in_section());
  491. } else {
  492. auto relocation_address = (FlatPtr*)relocation.address().as_ptr();
  493. if (image().is_dynamic())
  494. *relocation_address += m_dynamic_object->base_address().get();
  495. }
  496. break;
  497. }
  498. case R_X86_64_IRELATIVE: {
  499. VirtualAddress resolver;
  500. if (relocation.addend_used())
  501. resolver = m_dynamic_object->base_address().offset(relocation.addend());
  502. else
  503. resolver = m_dynamic_object->base_address().offset(*patch_ptr);
  504. if (m_dynamic_object->has_text_relocations()) {
  505. dbgln("\033[31mError:\033[0m Refusing to call IFUNC resolver defined in an object with text relocations.");
  506. return RelocationResult::Failed;
  507. }
  508. *patch_ptr = call_ifunc_resolver(resolver).get();
  509. break;
  510. }
  511. default:
  512. // Raise the alarm! Someone needs to implement this relocation type
  513. dbgln("Found a new exciting relocation type {}", relocation.type());
  514. VERIFY_NOT_REACHED();
  515. }
  516. return RelocationResult::Success;
  517. }
  518. void DynamicLoader::do_relr_relocations()
  519. {
  520. auto base_address = m_dynamic_object->base_address().get();
  521. m_dynamic_object->for_each_relr_relocation([base_address](FlatPtr address) {
  522. *(FlatPtr*)address += base_address;
  523. });
  524. }
  525. void DynamicLoader::copy_initial_tls_data_into(ByteBuffer& buffer) const
  526. {
  527. image().for_each_program_header([this, &buffer](ELF::Image::ProgramHeader program_header) {
  528. if (program_header.type() != PT_TLS)
  529. return IterationDecision::Continue;
  530. // Note: The "size in image" is only concerned with initialized data. Uninitialized data (.tbss) is
  531. // only included in the "size in memory" metric, and is expected to not be touched or read from, as
  532. // it is not present in the image and zeroed out in-memory. We will still check that the buffer has
  533. // space for both the initialized and the uninitialized data.
  534. // Note: The m_tls_offset here is (of course) negative.
  535. // TODO: Is the initialized data always in the beginning of the TLS segment, or should we walk the
  536. // sections to figure that out?
  537. size_t tls_start_in_buffer = buffer.size() + m_tls_offset;
  538. VERIFY(program_header.size_in_image() <= program_header.size_in_memory());
  539. VERIFY(program_header.size_in_memory() <= m_tls_size_of_current_object);
  540. VERIFY(tls_start_in_buffer + program_header.size_in_memory() <= buffer.size());
  541. memcpy(buffer.data() + tls_start_in_buffer, static_cast<const u8*>(m_file_data) + program_header.offset(), program_header.size_in_image());
  542. return IterationDecision::Break;
  543. });
  544. }
  545. // Defined in <arch>/plt_trampoline.S
  546. extern "C" void _plt_trampoline(void) __attribute__((visibility("hidden")));
  547. void DynamicLoader::setup_plt_trampoline()
  548. {
  549. VERIFY(m_dynamic_object);
  550. VERIFY(m_dynamic_object->has_plt());
  551. VirtualAddress got_address = m_dynamic_object->plt_got_base_address();
  552. auto* got_ptr = (FlatPtr*)got_address.as_ptr();
  553. got_ptr[1] = (FlatPtr)m_dynamic_object.ptr();
  554. got_ptr[2] = (FlatPtr)&_plt_trampoline;
  555. }
  556. // Called from our ASM routine _plt_trampoline.
  557. // Tell the compiler that it might be called from other places:
  558. extern "C" FlatPtr _fixup_plt_entry(DynamicObject* object, u32 relocation_offset);
  559. extern "C" FlatPtr _fixup_plt_entry(DynamicObject* object, u32 relocation_offset)
  560. {
  561. return object->patch_plt_entry(relocation_offset).get();
  562. }
  563. void DynamicLoader::call_object_init_functions()
  564. {
  565. typedef void (*InitFunc)();
  566. if (m_dynamic_object->has_init_section()) {
  567. auto init_function = (InitFunc)(m_dynamic_object->init_section().address().as_ptr());
  568. (init_function)();
  569. }
  570. if (m_dynamic_object->has_init_array_section()) {
  571. auto init_array_section = m_dynamic_object->init_array_section();
  572. InitFunc* init_begin = (InitFunc*)(init_array_section.address().as_ptr());
  573. InitFunc* init_end = init_begin + init_array_section.entry_count();
  574. while (init_begin != init_end) {
  575. // Android sources claim that these can be -1, to be ignored.
  576. // 0 definitely shows up. Apparently 0/-1 are valid? Confusing.
  577. if (!*init_begin || ((FlatPtr)*init_begin == (FlatPtr)-1))
  578. continue;
  579. (*init_begin)();
  580. ++init_begin;
  581. }
  582. }
  583. }
  584. Optional<DynamicObject::SymbolLookupResult> DynamicLoader::lookup_symbol(const ELF::DynamicObject::Symbol& symbol)
  585. {
  586. if (symbol.is_undefined() || symbol.bind() == STB_WEAK)
  587. return DynamicLinker::lookup_global_symbol(symbol.name());
  588. return DynamicObject::SymbolLookupResult { symbol.value(), symbol.size(), symbol.address(), symbol.bind(), symbol.type(), &symbol.object() };
  589. }
  590. } // end namespace ELF