DynamicLoader.cpp 26 KB

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