DynamicLoader.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  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-2023, Daniel Bertalan <dani@danielbertalan.dev>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include <AK/Debug.h>
  10. #include <AK/Optional.h>
  11. #include <AK/QuickSort.h>
  12. #include <AK/StringBuilder.h>
  13. #include <LibELF/DynamicLinker.h>
  14. #include <LibELF/DynamicLoader.h>
  15. #include <LibELF/Hashes.h>
  16. #include <LibELF/Validation.h>
  17. #include <assert.h>
  18. #include <bits/dlfcn_integration.h>
  19. #include <dlfcn.h>
  20. #include <errno.h>
  21. #include <stdio.h>
  22. #include <stdlib.h>
  23. #include <string.h>
  24. #include <sys/mman.h>
  25. #include <sys/stat.h>
  26. #include <unistd.h>
  27. #ifndef AK_OS_SERENITY
  28. static void* mmap_with_name(void* addr, size_t length, int prot, int flags, int fd, off_t offset, char const*)
  29. {
  30. return mmap(addr, length, prot, flags, fd, offset);
  31. }
  32. # define MAP_RANDOMIZED 0
  33. #endif
  34. #if ARCH(AARCH64)
  35. # define HAS_TLSDESC_SUPPORT
  36. extern "C" {
  37. void* __tlsdesc_static(void*);
  38. }
  39. #endif
  40. namespace ELF {
  41. Result<NonnullRefPtr<DynamicLoader>, DlErrorMessage> DynamicLoader::try_create(int fd, ByteString filepath)
  42. {
  43. VERIFY(filepath.starts_with('/'));
  44. struct stat stat;
  45. if (fstat(fd, &stat) < 0) {
  46. return DlErrorMessage { "DynamicLoader::try_create fstat" };
  47. }
  48. VERIFY(stat.st_size >= 0);
  49. auto size = static_cast<size_t>(stat.st_size);
  50. if (size < sizeof(Elf_Ehdr))
  51. return DlErrorMessage { ByteString::formatted("File {} has invalid ELF header", filepath) };
  52. ByteString file_mmap_name = ByteString::formatted("ELF_DYN: {}", filepath);
  53. auto* data = mmap_with_name(nullptr, size, PROT_READ, MAP_SHARED, fd, 0, file_mmap_name.characters());
  54. if (data == MAP_FAILED) {
  55. return DlErrorMessage { "DynamicLoader::try_create mmap" };
  56. }
  57. auto loader = adopt_ref(*new DynamicLoader(fd, move(filepath), data, size));
  58. if (!loader->is_valid())
  59. return DlErrorMessage { "ELF image validation failed" };
  60. return loader;
  61. }
  62. DynamicLoader::DynamicLoader(int fd, ByteString filepath, void* data, size_t size)
  63. : m_filepath(move(filepath))
  64. , m_file_size(size)
  65. , m_image_fd(fd)
  66. , m_file_data(data)
  67. {
  68. m_elf_image = adopt_own(*new ELF::Image((u8*)m_file_data, m_file_size));
  69. m_valid = validate();
  70. if (m_valid)
  71. find_tls_size_and_alignment();
  72. else
  73. dbgln("Image validation failed for file {}", m_filepath);
  74. }
  75. DynamicLoader::~DynamicLoader()
  76. {
  77. if (munmap(m_file_data, m_file_size) < 0) {
  78. perror("munmap");
  79. VERIFY_NOT_REACHED();
  80. }
  81. if (close(m_image_fd) < 0) {
  82. perror("close");
  83. VERIFY_NOT_REACHED();
  84. }
  85. }
  86. DynamicObject const& DynamicLoader::dynamic_object() const
  87. {
  88. if (!m_cached_dynamic_object) {
  89. VirtualAddress dynamic_section_address;
  90. image().for_each_program_header([&dynamic_section_address](auto program_header) {
  91. if (program_header.type() == PT_DYNAMIC) {
  92. dynamic_section_address = VirtualAddress(program_header.raw_data());
  93. }
  94. });
  95. VERIFY(!dynamic_section_address.is_null());
  96. m_cached_dynamic_object = ELF::DynamicObject::create(m_filepath, VirtualAddress(image().base_address()), dynamic_section_address);
  97. }
  98. return *m_cached_dynamic_object;
  99. }
  100. void DynamicLoader::find_tls_size_and_alignment()
  101. {
  102. image().for_each_program_header([this](auto program_header) {
  103. if (program_header.type() == PT_TLS) {
  104. m_tls_size_of_current_object = program_header.size_in_memory();
  105. auto alignment = program_header.alignment();
  106. VERIFY(!alignment || is_power_of_two(alignment));
  107. m_tls_alignment_of_current_object = alignment > 1 ? alignment : 0; // No need to reserve extra space for single byte alignment
  108. return IterationDecision::Break;
  109. }
  110. return IterationDecision::Continue;
  111. });
  112. }
  113. bool DynamicLoader::validate()
  114. {
  115. if (!image().is_valid())
  116. return false;
  117. auto* elf_header = (Elf_Ehdr*)m_file_data;
  118. if (!validate_elf_header(*elf_header, m_file_size))
  119. return false;
  120. auto result_or_error = validate_program_headers(*elf_header, m_file_size, { m_file_data, m_file_size });
  121. if (result_or_error.is_error() || !result_or_error.value())
  122. return false;
  123. return true;
  124. }
  125. RefPtr<DynamicObject> DynamicLoader::map()
  126. {
  127. if (m_dynamic_object) {
  128. // Already mapped.
  129. return nullptr;
  130. }
  131. if (!m_valid) {
  132. dbgln("DynamicLoader::map failed: image is invalid");
  133. return nullptr;
  134. }
  135. load_program_headers();
  136. VERIFY(!m_base_address.is_null());
  137. m_dynamic_object = DynamicObject::create(m_filepath, m_base_address, m_dynamic_section_address);
  138. m_dynamic_object->set_tls_offset(m_tls_offset);
  139. m_dynamic_object->set_tls_size(m_tls_size_of_current_object);
  140. return m_dynamic_object;
  141. }
  142. bool DynamicLoader::link(unsigned flags)
  143. {
  144. return load_stage_2(flags);
  145. }
  146. bool DynamicLoader::load_stage_2(unsigned flags)
  147. {
  148. VERIFY(flags & RTLD_GLOBAL);
  149. if (m_dynamic_object->has_text_relocations()) {
  150. dbgln("\033[33mWarning:\033[0m Dynamic object {} has text relocations", m_dynamic_object->filepath());
  151. for (auto& text_segment : m_text_segments) {
  152. VERIFY(text_segment.address().get() != 0);
  153. #ifndef AK_OS_MACOS
  154. // Remap this text region as private.
  155. if (mremap(text_segment.address().as_ptr(), text_segment.size(), text_segment.size(), MAP_PRIVATE) == MAP_FAILED) {
  156. perror("mremap .text: MAP_PRIVATE");
  157. return false;
  158. }
  159. #endif
  160. if (0 > mprotect(text_segment.address().as_ptr(), text_segment.size(), PROT_READ | PROT_WRITE)) {
  161. perror("mprotect .text: PROT_READ | PROT_WRITE"); // FIXME: dlerror?
  162. return false;
  163. }
  164. }
  165. } else {
  166. // .text needs to be executable while we process relocations because it might contain IFUNC resolvers.
  167. // We don't allow IFUNC resolvers in objects with textrels.
  168. for (auto& text_segment : m_text_segments) {
  169. if (mprotect(text_segment.address().as_ptr(), text_segment.size(), PROT_READ | PROT_EXEC) < 0) {
  170. perror("mprotect .text: PROT_READ | PROT_EXEC");
  171. return false;
  172. }
  173. }
  174. }
  175. do_main_relocations();
  176. return true;
  177. }
  178. void DynamicLoader::do_main_relocations()
  179. {
  180. do_relr_relocations();
  181. Optional<DynamicLoader::CachedLookupResult> cached_result;
  182. m_dynamic_object->relocation_section().for_each_relocation([&](DynamicObject::Relocation const& relocation) {
  183. switch (do_direct_relocation(relocation, cached_result, ShouldInitializeWeak::No, ShouldCallIfuncResolver::No)) {
  184. case RelocationResult::Failed:
  185. dbgln("Loader.so: {} unresolved symbol '{}'", m_filepath, relocation.symbol().name());
  186. VERIFY_NOT_REACHED();
  187. case RelocationResult::ResolveLater:
  188. m_unresolved_relocations.append(relocation);
  189. break;
  190. case RelocationResult::CallIfuncResolver:
  191. m_direct_ifunc_relocations.append(relocation);
  192. break;
  193. case RelocationResult::Success:
  194. break;
  195. }
  196. });
  197. // If the object is position-independent, the pointer to the PLT trampoline needs to be relocated.
  198. auto fixup_trampoline_pointer = [&](DynamicObject::Relocation const& relocation) {
  199. VERIFY(relocation.type() == R_X86_64_JUMP_SLOT || relocation.type() == R_AARCH64_JUMP_SLOT);
  200. if (image().is_dynamic())
  201. *((FlatPtr*)relocation.address().as_ptr()) += m_dynamic_object->base_address().get();
  202. };
  203. m_dynamic_object->plt_relocation_section().for_each_relocation([&](DynamicObject::Relocation const& relocation) {
  204. if (relocation.type() == R_X86_64_IRELATIVE || relocation.type() == R_AARCH64_IRELATIVE) {
  205. m_direct_ifunc_relocations.append(relocation);
  206. return;
  207. }
  208. if (relocation.type() == R_X86_64_TLSDESC || relocation.type() == R_AARCH64_TLSDESC) {
  209. // GNU ld for some reason puts TLSDESC relocations into .rela.plt
  210. // https://sourceware.org/bugzilla/show_bug.cgi?id=28387
  211. VERIFY(do_direct_relocation(relocation, cached_result, ShouldInitializeWeak::No, ShouldCallIfuncResolver::No) == RelocationResult::Success);
  212. return;
  213. }
  214. // FIXME: Or LD_BIND_NOW is set?
  215. if (m_dynamic_object->must_bind_now()) {
  216. switch (do_plt_relocation(relocation, ShouldCallIfuncResolver::No)) {
  217. case RelocationResult::Failed:
  218. dbgln("Loader.so: {} unresolved symbol '{}'", m_filepath, relocation.symbol().name());
  219. VERIFY_NOT_REACHED();
  220. case RelocationResult::ResolveLater:
  221. VERIFY_NOT_REACHED();
  222. case RelocationResult::CallIfuncResolver:
  223. m_plt_ifunc_relocations.append(relocation);
  224. // Set up lazy binding, in case an IFUNC resolver calls another IFUNC that hasn't been resolved yet.
  225. fixup_trampoline_pointer(relocation);
  226. break;
  227. case RelocationResult::Success:
  228. break;
  229. }
  230. } else {
  231. fixup_trampoline_pointer(relocation);
  232. }
  233. });
  234. }
  235. Result<NonnullRefPtr<DynamicObject>, DlErrorMessage> DynamicLoader::load_stage_3(unsigned flags)
  236. {
  237. do_lazy_relocations();
  238. if (flags & RTLD_LAZY) {
  239. if (m_dynamic_object->has_plt())
  240. setup_plt_trampoline();
  241. }
  242. // IFUNC resolvers can only be called after the PLT has been populated,
  243. // as they may call arbitrary functions via the PLT.
  244. for (auto const& relocation : m_plt_ifunc_relocations) {
  245. auto result = do_plt_relocation(relocation, ShouldCallIfuncResolver::Yes);
  246. VERIFY(result == RelocationResult::Success);
  247. }
  248. Optional<DynamicLoader::CachedLookupResult> cached_result;
  249. for (auto const& relocation : m_direct_ifunc_relocations) {
  250. auto result = do_direct_relocation(relocation, cached_result, ShouldInitializeWeak::No, ShouldCallIfuncResolver::Yes);
  251. VERIFY(result == RelocationResult::Success);
  252. }
  253. if (m_dynamic_object->has_text_relocations()) {
  254. // If we don't have textrels, .text has already been made executable by this point in load_stage_2.
  255. for (auto& text_segment : m_text_segments) {
  256. if (mprotect(text_segment.address().as_ptr(), text_segment.size(), PROT_READ | PROT_EXEC) < 0) {
  257. return DlErrorMessage { ByteString::formatted("mprotect .text: PROT_READ | PROT_EXEC: {}", strerror(errno)) };
  258. }
  259. }
  260. }
  261. if (m_relro_segment_size) {
  262. if (mprotect(m_relro_segment_address.as_ptr(), m_relro_segment_size, PROT_READ) < 0) {
  263. return DlErrorMessage { ByteString::formatted("mprotect .relro: PROT_READ: {}", strerror(errno)) };
  264. }
  265. #ifdef AK_OS_SERENITY
  266. if (set_mmap_name(m_relro_segment_address.as_ptr(), m_relro_segment_size, ByteString::formatted("{}: .relro", m_filepath).characters()) < 0) {
  267. return DlErrorMessage { ByteString::formatted("set_mmap_name .relro: {}", strerror(errno)) };
  268. }
  269. #endif
  270. }
  271. m_fully_relocated = true;
  272. return NonnullRefPtr<DynamicObject> { *m_dynamic_object };
  273. }
  274. void DynamicLoader::load_stage_4()
  275. {
  276. call_object_init_functions();
  277. m_fully_initialized = true;
  278. }
  279. void DynamicLoader::do_lazy_relocations()
  280. {
  281. Optional<DynamicLoader::CachedLookupResult> cached_result;
  282. for (auto const& relocation : m_unresolved_relocations) {
  283. if (auto res = do_direct_relocation(relocation, cached_result, ShouldInitializeWeak::Yes, ShouldCallIfuncResolver::Yes); res != RelocationResult::Success) {
  284. dbgln("Loader.so: {} unresolved symbol '{}'", m_filepath, relocation.symbol().name());
  285. VERIFY_NOT_REACHED();
  286. }
  287. }
  288. }
  289. void DynamicLoader::load_program_headers()
  290. {
  291. FlatPtr ph_load_start = SIZE_MAX;
  292. FlatPtr ph_load_end = 0;
  293. // We walk the program header list once to find the requested address ranges of the program.
  294. // We don't fill in the list of regions yet to keep malloc memory blocks from interfering with our reservation.
  295. image().for_each_program_header([&](Image::ProgramHeader const& program_header) {
  296. if (program_header.type() != PT_LOAD)
  297. return;
  298. FlatPtr section_start = program_header.vaddr().get();
  299. FlatPtr section_end = section_start + program_header.size_in_memory();
  300. if (ph_load_start > section_start)
  301. ph_load_start = section_start;
  302. if (ph_load_end < section_end)
  303. ph_load_end = section_end;
  304. });
  305. void* requested_load_address = image().is_dynamic() ? nullptr : reinterpret_cast<void*>(ph_load_start);
  306. int reservation_mmap_flags = MAP_ANON | MAP_PRIVATE | MAP_NORESERVE;
  307. if (image().is_dynamic())
  308. reservation_mmap_flags |= MAP_RANDOMIZED;
  309. #ifdef MAP_FIXED_NOREPLACE
  310. else
  311. reservation_mmap_flags |= MAP_FIXED_NOREPLACE;
  312. #endif
  313. // First, we make a dummy reservation mapping, in order to allocate enough VM
  314. // to hold all regions contiguously in the address space.
  315. FlatPtr ph_load_base = ph_load_start & ~(FlatPtr)0xfffu;
  316. ph_load_end = round_up_to_power_of_two(ph_load_end, PAGE_SIZE);
  317. size_t total_mapping_size = ph_load_end - ph_load_base;
  318. // Before we make our reservation, unmap our existing mapped ELF image that we used for reading header information.
  319. // This leaves our pointers dangling momentarily, but it reduces the chance that we will conflict with ourselves.
  320. if (munmap(m_file_data, m_file_size) < 0) {
  321. perror("munmap old mapping");
  322. VERIFY_NOT_REACHED();
  323. }
  324. m_elf_image = nullptr;
  325. m_file_data = nullptr;
  326. auto* reservation = mmap(requested_load_address, total_mapping_size, PROT_NONE, reservation_mmap_flags, 0, 0);
  327. if (reservation == MAP_FAILED) {
  328. perror("mmap reservation");
  329. VERIFY_NOT_REACHED();
  330. }
  331. // Now that we can't accidentally block our requested space, re-map our ELF image.
  332. ByteString file_mmap_name = ByteString::formatted("ELF_DYN: {}", m_filepath);
  333. auto* data = mmap_with_name(nullptr, m_file_size, PROT_READ, MAP_SHARED, m_image_fd, 0, file_mmap_name.characters());
  334. if (data == MAP_FAILED) {
  335. perror("mmap new mapping");
  336. VERIFY_NOT_REACHED();
  337. }
  338. m_file_data = data;
  339. m_elf_image = adopt_own(*new ELF::Image((u8*)m_file_data, m_file_size));
  340. VERIFY(requested_load_address == nullptr || reservation == requested_load_address);
  341. m_base_address = VirtualAddress { reservation };
  342. // Most binaries have four loadable regions, three of which are mapped
  343. // (symbol tables/relocation information, executable instructions, read-only data)
  344. // and one of which is copied (modifiable data).
  345. // These are allocated in-line to cut down on the malloc calls.
  346. Vector<ProgramHeaderRegion, 3> map_regions;
  347. Vector<ProgramHeaderRegion, 1> copy_regions;
  348. Optional<ProgramHeaderRegion> relro_region;
  349. VirtualAddress dynamic_region_desired_vaddr;
  350. image().for_each_program_header([&](Image::ProgramHeader const& program_header) {
  351. ProgramHeaderRegion region {};
  352. region.set_program_header(program_header.raw_header());
  353. if (region.is_tls_template()) {
  354. // Skip, this is handled in DynamicLoader::copy_initial_tls_data_into.
  355. } else if (region.is_load()) {
  356. if (region.size_in_memory() == 0)
  357. return;
  358. if (region.is_writable()) {
  359. copy_regions.append(region);
  360. } else {
  361. map_regions.append(region);
  362. }
  363. } else if (region.is_dynamic()) {
  364. dynamic_region_desired_vaddr = region.desired_load_address();
  365. } else if (region.is_relro()) {
  366. VERIFY(!relro_region.has_value());
  367. relro_region = region;
  368. }
  369. });
  370. VERIFY(!map_regions.is_empty() || !copy_regions.is_empty());
  371. auto compare_load_address = [](ProgramHeaderRegion& a, ProgramHeaderRegion& b) {
  372. return a.desired_load_address().as_ptr() < b.desired_load_address().as_ptr();
  373. };
  374. quick_sort(map_regions, compare_load_address);
  375. quick_sort(copy_regions, compare_load_address);
  376. // Pre-allocate any malloc memory needed before unmapping the reservation.
  377. // We don't want any future malloc to accidentally mmap a reserved address!
  378. ByteString text_segment_name = ByteString::formatted("{}: .text", m_filepath);
  379. ByteString rodata_segment_name = ByteString::formatted("{}: .rodata", m_filepath);
  380. ByteString data_segment_name = ByteString::formatted("{}: .data", m_filepath);
  381. m_text_segments.ensure_capacity(map_regions.size());
  382. // Finally, we unmap the reservation.
  383. if (munmap(reservation, total_mapping_size) < 0) {
  384. perror("munmap reservation");
  385. VERIFY_NOT_REACHED();
  386. }
  387. // WARNING: Allocating after this point has the possibility of malloc stealing our reserved
  388. // virtual memory addresses. Be careful not to malloc below!
  389. // Process regions in order: .text, .data, .tls
  390. for (auto& region : map_regions) {
  391. FlatPtr ph_desired_base = region.desired_load_address().get();
  392. FlatPtr ph_base = region.desired_load_address().page_base().get();
  393. FlatPtr ph_end = ph_base + round_up_to_power_of_two(region.size_in_memory() + region.desired_load_address().get() - ph_base, PAGE_SIZE);
  394. char const* const segment_name = region.is_executable() ? text_segment_name.characters() : rodata_segment_name.characters();
  395. // Now we can map the text segment at the reserved address.
  396. auto* segment_base = (u8*)mmap_with_name(
  397. (u8*)reservation + ph_base - ph_load_base,
  398. ph_desired_base - ph_base + region.size_in_image(),
  399. PROT_READ,
  400. MAP_SHARED | MAP_FIXED,
  401. m_image_fd,
  402. VirtualAddress { region.offset() }.page_base().get(),
  403. segment_name);
  404. if (segment_base == MAP_FAILED) {
  405. perror("mmap non-writable");
  406. VERIFY_NOT_REACHED();
  407. }
  408. // NOTE: Capacity ensured above the line of no malloc above
  409. if (region.is_executable())
  410. m_text_segments.unchecked_append({ VirtualAddress { segment_base }, ph_end - ph_base });
  411. }
  412. VERIFY(requested_load_address == nullptr || requested_load_address == reservation);
  413. if (relro_region.has_value()) {
  414. m_relro_segment_size = relro_region->size_in_memory();
  415. m_relro_segment_address = VirtualAddress { (u8*)reservation + relro_region->desired_load_address().get() - ph_load_base };
  416. }
  417. if (image().is_dynamic())
  418. m_dynamic_section_address = VirtualAddress { (u8*)reservation + dynamic_region_desired_vaddr.get() - ph_load_base };
  419. else
  420. m_dynamic_section_address = dynamic_region_desired_vaddr;
  421. for (auto& region : copy_regions) {
  422. FlatPtr ph_data_base = region.desired_load_address().page_base().get();
  423. 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);
  424. auto* data_segment_address = (u8*)reservation + ph_data_base - ph_load_base;
  425. size_t data_segment_size = ph_data_end - ph_data_base;
  426. // Finally, we make an anonymous mapping for the data segment. Contents are then copied from the file.
  427. auto* data_segment = (u8*)mmap_with_name(
  428. data_segment_address,
  429. data_segment_size,
  430. PROT_READ | PROT_WRITE,
  431. MAP_ANONYMOUS | MAP_PRIVATE | MAP_FIXED,
  432. 0,
  433. 0,
  434. data_segment_name.characters());
  435. if (MAP_FAILED == data_segment) {
  436. perror("mmap writable");
  437. VERIFY_NOT_REACHED();
  438. }
  439. VirtualAddress data_segment_start;
  440. if (image().is_dynamic())
  441. data_segment_start = VirtualAddress { (u8*)reservation + region.desired_load_address().get() };
  442. else
  443. data_segment_start = region.desired_load_address();
  444. VERIFY(data_segment_start.as_ptr() + region.size_in_memory() <= data_segment + data_segment_size);
  445. memcpy(data_segment_start.as_ptr(), (u8*)m_file_data + region.offset(), region.size_in_image());
  446. }
  447. }
  448. DynamicLoader::RelocationResult DynamicLoader::do_direct_relocation(DynamicObject::Relocation const& relocation,
  449. Optional<DynamicLoader::CachedLookupResult>& cached_result,
  450. ShouldInitializeWeak should_initialize_weak,
  451. ShouldCallIfuncResolver should_call_ifunc_resolver)
  452. {
  453. FlatPtr* patch_ptr = nullptr;
  454. if (is_dynamic())
  455. patch_ptr = (FlatPtr*)(m_dynamic_object->base_address().as_ptr() + relocation.offset());
  456. else
  457. patch_ptr = (FlatPtr*)(FlatPtr)relocation.offset();
  458. auto call_ifunc_resolver = [](VirtualAddress address) {
  459. return VirtualAddress { reinterpret_cast<DynamicObject::IfuncResolver>(address.get())() };
  460. };
  461. auto lookup_symbol = [&](DynamicObject::Symbol const& symbol) {
  462. // The static linker sorts relocations by the referenced symbol. Especially when vtables
  463. // in large inheritance hierarchies are involved, there might be tens of references to
  464. // the same symbol. We can avoid redundant lookups by keeping track of the previous result.
  465. if (!cached_result.has_value() || !cached_result.value().symbol.definitely_equals(symbol))
  466. cached_result = DynamicLoader::CachedLookupResult { symbol, DynamicLoader::lookup_symbol(symbol) };
  467. return cached_result.value().result;
  468. };
  469. struct ResolvedTLSSymbol {
  470. DynamicObject const& dynamic_object;
  471. FlatPtr value;
  472. };
  473. auto resolve_tls_symbol = [&](DynamicObject::Relocation const& relocation) -> Optional<ResolvedTLSSymbol> {
  474. if (relocation.symbol_index() == 0)
  475. return ResolvedTLSSymbol { relocation.dynamic_object(), 0 };
  476. auto res = lookup_symbol(relocation.symbol());
  477. if (!res.has_value())
  478. return {};
  479. VERIFY(relocation.symbol().type() != STT_GNU_IFUNC);
  480. VERIFY(res.value().dynamic_object != nullptr);
  481. return ResolvedTLSSymbol { *res.value().dynamic_object, res.value().value };
  482. };
  483. switch (relocation.type()) {
  484. case R_X86_64_NONE:
  485. // Apparently most loaders will just skip these?
  486. // Seems if the 'link editor' generates one something is funky with your code
  487. break;
  488. case R_AARCH64_ABS64:
  489. case R_X86_64_64: {
  490. auto symbol = relocation.symbol();
  491. auto res = lookup_symbol(symbol);
  492. if (!res.has_value()) {
  493. if (symbol.bind() == STB_WEAK)
  494. return RelocationResult::ResolveLater;
  495. dbgln("ERROR: symbol not found: {}.", symbol.name());
  496. return RelocationResult::Failed;
  497. }
  498. if (res.value().type == STT_GNU_IFUNC && should_call_ifunc_resolver == ShouldCallIfuncResolver::No)
  499. return RelocationResult::CallIfuncResolver;
  500. auto symbol_address = res.value().address;
  501. if (relocation.addend_used())
  502. *patch_ptr = symbol_address.get() + relocation.addend();
  503. else
  504. *patch_ptr += symbol_address.get();
  505. if (res.value().type == STT_GNU_IFUNC)
  506. *patch_ptr = call_ifunc_resolver(VirtualAddress { *patch_ptr }).get();
  507. break;
  508. }
  509. case R_AARCH64_GLOB_DAT:
  510. case R_X86_64_GLOB_DAT: {
  511. auto symbol = relocation.symbol();
  512. auto res = lookup_symbol(symbol);
  513. VirtualAddress symbol_location;
  514. if (!res.has_value()) {
  515. if (symbol.bind() == STB_WEAK) {
  516. if (should_initialize_weak == ShouldInitializeWeak::No)
  517. return RelocationResult::ResolveLater;
  518. } else {
  519. // Symbol not found
  520. return RelocationResult::Failed;
  521. }
  522. symbol_location = VirtualAddress { (FlatPtr)0 };
  523. } else {
  524. symbol_location = res.value().address;
  525. if (res.value().type == STT_GNU_IFUNC) {
  526. if (should_call_ifunc_resolver == ShouldCallIfuncResolver::No)
  527. return RelocationResult::CallIfuncResolver;
  528. if (res.value().dynamic_object != nullptr && res.value().dynamic_object->has_text_relocations()) {
  529. dbgln("\033[31mError:\033[0m Refusing to call IFUNC resolver defined in an object with text relocations.");
  530. return RelocationResult::Failed;
  531. }
  532. symbol_location = call_ifunc_resolver(symbol_location);
  533. }
  534. }
  535. VERIFY(symbol_location != m_dynamic_object->base_address());
  536. *patch_ptr = symbol_location.get();
  537. break;
  538. }
  539. case R_AARCH64_RELATIVE:
  540. case R_X86_64_RELATIVE: {
  541. if (!image().is_dynamic())
  542. break;
  543. // FIXME: According to the spec, R_386_relative ones must be done first.
  544. // We could explicitly do them first using m_number_of_relocations from DT_RELCOUNT
  545. // However, our compiler is nice enough to put them at the front of the relocations for us :)
  546. if (relocation.addend_used())
  547. *patch_ptr = m_dynamic_object->base_address().offset(relocation.addend()).get();
  548. else
  549. *patch_ptr += m_dynamic_object->base_address().get();
  550. break;
  551. }
  552. case R_AARCH64_TLS_TPREL:
  553. case R_X86_64_TPOFF64: {
  554. auto maybe_resolution = resolve_tls_symbol(relocation);
  555. if (!maybe_resolution.has_value())
  556. break;
  557. auto [dynamic_object_of_symbol, symbol_value] = maybe_resolution.value();
  558. size_t addend = relocation.addend_used() ? relocation.addend() : *patch_ptr;
  559. *patch_ptr = addend + dynamic_object_of_symbol.tls_offset().value() + symbol_value;
  560. // At offset 0 there's the thread's ThreadSpecificData structure, we don't want to collide with it.
  561. VERIFY(static_cast<ssize_t>(*patch_ptr) < 0);
  562. break;
  563. }
  564. case R_X86_64_DTPMOD64: {
  565. auto maybe_resolution = resolve_tls_symbol(relocation);
  566. if (!maybe_resolution.has_value())
  567. break;
  568. // We repurpose the module index to store the TLS block's TP offset. This is fine
  569. // because we currently only support a single static TLS block.
  570. *patch_ptr = maybe_resolution->dynamic_object.tls_offset().value();
  571. break;
  572. }
  573. case R_X86_64_DTPOFF64: {
  574. auto maybe_resolution = resolve_tls_symbol(relocation);
  575. if (!maybe_resolution.has_value())
  576. break;
  577. size_t addend = relocation.addend_used() ? relocation.addend() : *patch_ptr;
  578. *patch_ptr = addend + maybe_resolution->value;
  579. break;
  580. }
  581. #ifdef HAS_TLSDESC_SUPPORT
  582. case R_AARCH64_TLSDESC: {
  583. auto maybe_resolution = resolve_tls_symbol(relocation);
  584. if (!maybe_resolution.has_value())
  585. break;
  586. auto [dynamic_object_of_symbol, symbol_value] = maybe_resolution.value();
  587. size_t addend = relocation.addend_used() ? relocation.addend() : *patch_ptr;
  588. patch_ptr[0] = (FlatPtr)__tlsdesc_static;
  589. patch_ptr[1] = addend + dynamic_object_of_symbol.tls_offset().value() + symbol_value;
  590. break;
  591. }
  592. #endif
  593. case R_AARCH64_IRELATIVE:
  594. case R_X86_64_IRELATIVE: {
  595. if (should_call_ifunc_resolver == ShouldCallIfuncResolver::No)
  596. return RelocationResult::CallIfuncResolver;
  597. VirtualAddress resolver;
  598. if (relocation.addend_used())
  599. resolver = m_dynamic_object->base_address().offset(relocation.addend());
  600. else
  601. resolver = m_dynamic_object->base_address().offset(*patch_ptr);
  602. if (m_dynamic_object->has_text_relocations()) {
  603. dbgln("\033[31mError:\033[0m Refusing to call IFUNC resolver defined in an object with text relocations.");
  604. return RelocationResult::Failed;
  605. }
  606. *patch_ptr = call_ifunc_resolver(resolver).get();
  607. break;
  608. }
  609. case R_AARCH64_JUMP_SLOT:
  610. case R_X86_64_JUMP_SLOT:
  611. VERIFY_NOT_REACHED(); // PLT relocations are handled by do_plt_relocation.
  612. default:
  613. // Raise the alarm! Someone needs to implement this relocation type
  614. dbgln("Found a new exciting relocation type {}", relocation.type());
  615. VERIFY_NOT_REACHED();
  616. }
  617. return RelocationResult::Success;
  618. }
  619. DynamicLoader::RelocationResult DynamicLoader::do_plt_relocation(DynamicObject::Relocation const& relocation, ShouldCallIfuncResolver should_call_ifunc_resolver)
  620. {
  621. VERIFY(relocation.type() == R_X86_64_JUMP_SLOT || relocation.type() == R_AARCH64_JUMP_SLOT);
  622. auto symbol = relocation.symbol();
  623. auto* relocation_address = (FlatPtr*)relocation.address().as_ptr();
  624. VirtualAddress symbol_location {};
  625. if (auto result = lookup_symbol(symbol); result.has_value()) {
  626. auto address = result.value().address;
  627. if (result.value().type == STT_GNU_IFUNC) {
  628. if (should_call_ifunc_resolver == ShouldCallIfuncResolver::No)
  629. return RelocationResult::CallIfuncResolver;
  630. symbol_location = VirtualAddress { reinterpret_cast<DynamicObject::IfuncResolver>(address.get())() };
  631. } else {
  632. symbol_location = address;
  633. }
  634. } else if (symbol.bind() != STB_WEAK) {
  635. return RelocationResult::Failed;
  636. }
  637. dbgln_if(DYNAMIC_LOAD_DEBUG, "DynamicLoader: Jump slot relocation: putting {} ({}) into PLT at {}", symbol.name(), symbol_location, (void*)relocation_address);
  638. *relocation_address = symbol_location.get();
  639. return RelocationResult::Success;
  640. }
  641. void DynamicLoader::do_relr_relocations()
  642. {
  643. auto base_address = m_dynamic_object->base_address().get();
  644. m_dynamic_object->for_each_relr_relocation([base_address](FlatPtr address) {
  645. *(FlatPtr*)address += base_address;
  646. });
  647. }
  648. void DynamicLoader::copy_initial_tls_data_into(ByteBuffer& buffer) const
  649. {
  650. image().for_each_program_header([this, &buffer](ELF::Image::ProgramHeader program_header) {
  651. if (program_header.type() != PT_TLS)
  652. return IterationDecision::Continue;
  653. // Note: The "size in image" is only concerned with initialized data. Uninitialized data (.tbss) is
  654. // only included in the "size in memory" metric, and is expected to not be touched or read from, as
  655. // it is not present in the image and zeroed out in-memory. We will still check that the buffer has
  656. // space for both the initialized and the uninitialized data.
  657. // Note: The m_tls_offset here is (of course) negative.
  658. // TODO: Is the initialized data always in the beginning of the TLS segment, or should we walk the
  659. // sections to figure that out?
  660. size_t tls_start_in_buffer = buffer.size() + m_tls_offset;
  661. VERIFY(program_header.size_in_image() <= program_header.size_in_memory());
  662. VERIFY(program_header.size_in_memory() <= m_tls_size_of_current_object);
  663. VERIFY(tls_start_in_buffer + program_header.size_in_memory() <= buffer.size());
  664. memcpy(buffer.data() + tls_start_in_buffer, static_cast<const u8*>(m_file_data) + program_header.offset(), program_header.size_in_image());
  665. return IterationDecision::Break;
  666. });
  667. }
  668. // Defined in <arch>/plt_trampoline.S
  669. extern "C" void _plt_trampoline(void) __attribute__((visibility("hidden")));
  670. void DynamicLoader::setup_plt_trampoline()
  671. {
  672. VERIFY(m_dynamic_object);
  673. VERIFY(m_dynamic_object->has_plt());
  674. VirtualAddress got_address = m_dynamic_object->plt_got_base_address();
  675. auto* got_ptr = (FlatPtr*)got_address.as_ptr();
  676. got_ptr[1] = (FlatPtr)m_dynamic_object.ptr();
  677. got_ptr[2] = (FlatPtr)&_plt_trampoline;
  678. }
  679. // Called from our ASM routine _plt_trampoline.
  680. extern "C" FlatPtr _fixup_plt_entry(DynamicObject* object, u32 relocation_offset)
  681. {
  682. auto const& relocation = object->plt_relocation_section().relocation_at_offset(relocation_offset);
  683. auto result = DynamicLoader::do_plt_relocation(relocation, ShouldCallIfuncResolver::Yes);
  684. if (result != DynamicLoader::RelocationResult::Success) {
  685. dbgln("Loader.so: {} unresolved symbol '{}'", object->filepath(), relocation.symbol().name());
  686. VERIFY_NOT_REACHED();
  687. }
  688. return *reinterpret_cast<FlatPtr*>(relocation.address().as_ptr());
  689. }
  690. void DynamicLoader::call_object_init_functions()
  691. {
  692. typedef void (*InitFunc)();
  693. if (m_dynamic_object->has_init_section()) {
  694. auto init_function = m_dynamic_object->init_section_function();
  695. (init_function)();
  696. }
  697. if (m_dynamic_object->has_init_array_section()) {
  698. auto init_array_section = m_dynamic_object->init_array_section();
  699. InitFunc* init_begin = (InitFunc*)(init_array_section.address().as_ptr());
  700. InitFunc* init_end = init_begin + init_array_section.entry_count();
  701. while (init_begin != init_end) {
  702. // Android sources claim that these can be -1, to be ignored.
  703. // 0 definitely shows up. Apparently 0/-1 are valid? Confusing.
  704. if (!*init_begin || ((FlatPtr)*init_begin == (FlatPtr)-1))
  705. continue;
  706. (*init_begin)();
  707. ++init_begin;
  708. }
  709. }
  710. }
  711. Optional<DynamicObject::SymbolLookupResult> DynamicLoader::lookup_symbol(const ELF::DynamicObject::Symbol& symbol)
  712. {
  713. if (symbol.is_undefined() || symbol.bind() == STB_WEAK)
  714. return DynamicLinker::lookup_global_symbol(symbol.name());
  715. return DynamicObject::SymbolLookupResult { symbol.value(), symbol.size(), symbol.address(), symbol.bind(), symbol.type(), &symbol.object() };
  716. }
  717. } // end namespace ELF