main.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. /*
  2. * Copyright (c) 2020, Itamar S. <itamar8910@gmail.com>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/HashMap.h>
  27. #include <AK/HashTable.h>
  28. #include <AK/LexicalPath.h>
  29. #include <AK/LogStream.h>
  30. #include <AK/ScopeGuard.h>
  31. #include <LibC/mman.h>
  32. #include <LibC/stdio.h>
  33. #include <LibC/sys/internals.h>
  34. #include <LibC/unistd.h>
  35. #include <LibCore/File.h>
  36. #include <LibELF/AuxiliaryVector.h>
  37. #include <LibELF/DynamicLoader.h>
  38. #include <LibELF/DynamicObject.h>
  39. #include <LibELF/Image.h>
  40. #include <LibELF/exec_elf.h>
  41. #include <dlfcn.h>
  42. #include <string.h>
  43. #include <sys/stat.h>
  44. #include <sys/types.h>
  45. // #define DYNAMIC_LOAD_VERBOSE
  46. #ifdef DYNAMIC_LOAD_VERBOSE
  47. # define VERBOSE(fmt, ...) dbgprintf(fmt, ##__VA_ARGS__)
  48. #else
  49. # define VERBOSE(fmt, ...) \
  50. do { \
  51. } while (0)
  52. #endif
  53. #define TLS_VERBOSE(fmt, ...) dbgprintf(fmt, ##__VA_ARGS__)
  54. char* __static_environ[] = { nullptr }; // We don't get the environment without some libc workarounds..
  55. static HashMap<String, NonnullRefPtr<ELF::DynamicLoader>> g_loaders;
  56. static HashMap<String, NonnullRefPtr<ELF::DynamicObject>> g_loaded_objects;
  57. using MainFunction = int (*)(int, char**, char**);
  58. using LibCExitFunction = void (*)(int);
  59. static size_t g_current_tls_offset = 0;
  60. static size_t g_total_tls_size = 0;
  61. static char** g_envp = nullptr;
  62. static LibCExitFunction g_libc_exit = nullptr;
  63. static void init_libc()
  64. {
  65. environ = __static_environ;
  66. __environ_is_malloced = false;
  67. __stdio_is_initialized = false;
  68. __malloc_init();
  69. }
  70. static void perform_self_relocations(auxv_t* auxvp)
  71. {
  72. // We need to relocate ourselves.
  73. // (these relocations seem to be generated because of our vtables)
  74. FlatPtr base_address = 0;
  75. bool found_base_address = false;
  76. for (; auxvp->a_type != AT_NULL; ++auxvp) {
  77. if (auxvp->a_type == ELF::AuxiliaryValue::BaseAddress) {
  78. base_address = auxvp->a_un.a_val;
  79. found_base_address = true;
  80. }
  81. }
  82. ASSERT(found_base_address);
  83. Elf32_Ehdr* header = (Elf32_Ehdr*)(base_address);
  84. Elf32_Phdr* pheader = (Elf32_Phdr*)(base_address + header->e_phoff);
  85. u32 dynamic_section_addr = 0;
  86. for (size_t i = 0; i < (size_t)header->e_phnum; ++i, ++pheader) {
  87. if (pheader->p_type != PT_DYNAMIC)
  88. continue;
  89. dynamic_section_addr = pheader->p_vaddr + base_address;
  90. }
  91. if (!dynamic_section_addr)
  92. exit(1);
  93. auto dynamic_object = ELF::DynamicObject::construct((VirtualAddress(base_address)), (VirtualAddress(dynamic_section_addr)));
  94. dynamic_object->relocation_section().for_each_relocation([base_address](auto& reloc) {
  95. if (reloc.type() != R_386_RELATIVE)
  96. return IterationDecision::Continue;
  97. *(u32*)reloc.address().as_ptr() += base_address;
  98. return IterationDecision::Continue;
  99. });
  100. }
  101. static ELF::DynamicObject::SymbolLookupResult global_symbol_lookup(const char* symbol_name)
  102. {
  103. VERBOSE("global symbol lookup: %s\n", symbol_name);
  104. for (auto& lib : g_loaded_objects) {
  105. VERBOSE("looking up in object: %s\n", lib.key.characters());
  106. auto res = lib.value->lookup_symbol(symbol_name);
  107. if (!res.has_value())
  108. continue;
  109. return res.value();
  110. }
  111. // ASSERT_NOT_REACHED();
  112. return {};
  113. }
  114. static void map_library(const String& name, int fd)
  115. {
  116. struct stat lib_stat;
  117. int rc = fstat(fd, &lib_stat);
  118. ASSERT(!rc);
  119. auto loader = ELF::DynamicLoader::construct(name.characters(), fd, lib_stat.st_size);
  120. loader->set_tls_offset(g_current_tls_offset);
  121. loader->set_global_symbol_lookup_function(global_symbol_lookup);
  122. g_loaders.set(name, loader);
  123. g_current_tls_offset += loader->tls_size();
  124. }
  125. static void map_library(const String& name)
  126. {
  127. // TODO: Do we want to also look for libs in other paths too?
  128. String path = String::format("/usr/lib/%s", name.characters());
  129. int fd = open(path.characters(), O_RDONLY);
  130. ASSERT(fd >= 0);
  131. map_library(name, fd);
  132. }
  133. static String get_library_name(const StringView& path)
  134. {
  135. return LexicalPath(path).basename();
  136. }
  137. static Vector<String> get_dependencies(const String& name)
  138. {
  139. auto lib = g_loaders.get(name).value();
  140. Vector<String> dependencies;
  141. lib->for_each_needed_library([&dependencies, &name](auto needed_name) {
  142. if (name == needed_name)
  143. return IterationDecision::Continue;
  144. dependencies.append(needed_name);
  145. return IterationDecision::Continue;
  146. });
  147. return dependencies;
  148. }
  149. static void map_dependencies(const String& name)
  150. {
  151. VERBOSE("mapping dependencies for: %s\n", name.characters());
  152. for (const auto& needed_name : get_dependencies(name)) {
  153. VERBOSE("needed library: %s\n", needed_name.characters());
  154. String library_name = get_library_name(needed_name);
  155. if (!g_loaders.contains(library_name)) {
  156. map_library(library_name);
  157. map_dependencies(library_name);
  158. }
  159. }
  160. }
  161. static void allocate_tls()
  162. {
  163. size_t total_tls_size = 0;
  164. for (const auto& data : g_loaders) {
  165. VERBOSE("%s: TLS Size: %zu\n", data.key.characters(), data.value->tls_size());
  166. total_tls_size += data.value->tls_size();
  167. }
  168. if (total_tls_size) {
  169. [[maybe_unused]] void* tls_address = allocate_tls(total_tls_size);
  170. VERBOSE("from userspace, tls_address: %p\n", tls_address);
  171. }
  172. g_total_tls_size = total_tls_size;
  173. }
  174. static void initialize_libc()
  175. {
  176. // Traditionally, `_start` of the main program initializes libc.
  177. // However, since some libs use malloc() and getenv() in global constructors,
  178. // we have to initialize libc just after it is loaded.
  179. // Also, we can't just mark `__libc_init` with "__attribute__((constructor))"
  180. // because it uses getenv() internally, so `environ` has to be initialized before we call `__libc_init`.
  181. auto res = global_symbol_lookup("environ");
  182. *((char***)res.address) = g_envp;
  183. ASSERT(res.found);
  184. res = global_symbol_lookup("__environ_is_malloced");
  185. ASSERT(res.found);
  186. *((bool*)res.address) = false;
  187. res = global_symbol_lookup("exit");
  188. ASSERT(res.found);
  189. g_libc_exit = (LibCExitFunction)res.address;
  190. res = global_symbol_lookup("__libc_init");
  191. ASSERT(res.found);
  192. typedef void libc_init_func();
  193. ((libc_init_func*)res.address)();
  194. }
  195. static void load_elf(const String& name)
  196. {
  197. VERBOSE("load_elf: %s\n", name.characters());
  198. auto loader = g_loaders.get(name).value();
  199. VERBOSE("a1\n");
  200. for (const auto& needed_name : get_dependencies(name)) {
  201. VERBOSE("needed library: %s\n", needed_name.characters());
  202. String library_name = get_library_name(needed_name);
  203. if (!g_loaded_objects.contains(library_name)) {
  204. load_elf(library_name);
  205. }
  206. }
  207. auto dynamic_object = loader->load_from_image(RTLD_GLOBAL | RTLD_LAZY, g_total_tls_size);
  208. ASSERT(!dynamic_object.is_null());
  209. g_loaded_objects.set(name, dynamic_object.release_nonnull());
  210. if (name == "libc.so") {
  211. initialize_libc();
  212. }
  213. }
  214. static void clear_temporary_objects_mappings()
  215. {
  216. g_loaders.clear();
  217. }
  218. static void display_help()
  219. {
  220. const char message[] =
  221. R"(You have invoked `Loader.so'. This is the helper program for programs that
  222. use shared libraries. Special directives embedded in executables tell the
  223. kernel to load this program.
  224. This helper program loads the shared libraries needed by the program,
  225. prepares the program to run, and runs it. You do not need to invoke
  226. this helper program directly.
  227. )";
  228. write(1, message, sizeof(message));
  229. }
  230. static FlatPtr loader_main(auxv_t* auxvp)
  231. {
  232. int main_program_fd = -1;
  233. String main_program_name;
  234. for (; auxvp->a_type != AT_NULL; ++auxvp) {
  235. if (auxvp->a_type == ELF::AuxiliaryValue::ExecFileDescriptor) {
  236. main_program_fd = auxvp->a_un.a_val;
  237. }
  238. if (auxvp->a_type == ELF::AuxiliaryValue::ExecFilename) {
  239. main_program_name = (const char*)auxvp->a_un.a_ptr;
  240. }
  241. }
  242. ASSERT(main_program_fd >= 0);
  243. ASSERT(!main_program_name.is_null());
  244. if (main_program_name == "/usr/lib/Loader.so") {
  245. // We've been invoked directly as an executable rather than as the
  246. // ELF interpreter for some other binary. In the future we may want
  247. // to support launching a program directly from the dynamic loader
  248. // like ld.so on Linux.
  249. display_help();
  250. _exit(1);
  251. }
  252. map_library(main_program_name, main_program_fd);
  253. map_dependencies(main_program_name);
  254. VERBOSE("loaded all dependencies");
  255. for ([[maybe_unused]] auto& lib : g_loaders) {
  256. VERBOSE("%s - tls size: %zu, tls offset: %zu\n", lib.key.characters(), lib.value->tls_size(), lib.value->tls_offset());
  257. }
  258. allocate_tls();
  259. load_elf(main_program_name);
  260. auto main_program_lib = g_loaders.get(main_program_name).value();
  261. FlatPtr entry_point = reinterpret_cast<FlatPtr>(main_program_lib->image().entry().as_ptr());
  262. if (main_program_lib->is_dynamic())
  263. entry_point += reinterpret_cast<FlatPtr>(main_program_lib->text_segment_load_address().as_ptr());
  264. VERBOSE("entry point: %p\n", (void*)entry_point);
  265. // This will unmap the temporary memory maps we had for loading the libraries
  266. clear_temporary_objects_mappings();
  267. return entry_point;
  268. }
  269. extern "C" {
  270. // The compiler expects a previous declaration
  271. void _start(int, char**, char**);
  272. void _start(int argc, char** argv, char** envp)
  273. {
  274. g_envp = envp;
  275. char** env;
  276. for (env = envp; *env; ++env) {
  277. }
  278. auxv_t* auxvp = (auxv_t*)++env;
  279. perform_self_relocations(auxvp);
  280. init_libc();
  281. FlatPtr entry = loader_main(auxvp);
  282. VERBOSE("Loaded libs:\n");
  283. for ([[maybe_unused]] auto& obj : g_loaded_objects) {
  284. VERBOSE("%s: %p\n", obj.key.characters(), obj.value->base_address().as_ptr());
  285. }
  286. MainFunction main_function = (MainFunction)(entry);
  287. VERBOSE("jumping to main program entry point: %p\n", main_function);
  288. int rc = main_function(argc, argv, envp);
  289. VERBOSE("rc: %d\n", rc);
  290. if (g_libc_exit != nullptr) {
  291. g_libc_exit(rc);
  292. } else {
  293. _exit(rc);
  294. }
  295. }
  296. }