linker.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850
  1. /* vim: ts=4 sw=4 noexpandtab
  2. * This file is part of ToaruOS and is released under the terms
  3. * of the NCSA / University of Illinois License - see LICENSE.md
  4. * Copyright (C) 2016-2018 Kevin Lange
  5. *
  6. * ELF Dynamic Linker/Loader
  7. *
  8. * Loads ELF executables and links them at runtime to their
  9. * shared library dependencies.
  10. *
  11. * As of writing, this is a simplistic and not-fully-compliant
  12. * implementation of ELF dynamic linking. It suffers from a number
  13. * of issues, including not actually sharing libraries (there
  14. * isn't a sufficient mechanism in the kernel at the moment for
  15. * doing that - we need something with copy-on-write, preferably
  16. * an mmap-file mechanism), as well as not handling symbol
  17. * resolution correctly.
  18. *
  19. * However, it's sufficient for our purposes, and works well enough
  20. * to load Python C modules.
  21. */
  22. #include <stdlib.h>
  23. #include <stdint.h>
  24. #include <alloca.h>
  25. #include <stdio.h>
  26. #include <string.h>
  27. #include <unistd.h>
  28. #include <sys/stat.h>
  29. #include <sys/types.h>
  30. #include <sys/sysfunc.h>
  31. #include <kernel/elf.h>
  32. void * (*_malloc)(size_t size) = malloc;
  33. void (*_free)(void * ptr) = free;
  34. #undef malloc
  35. #undef free
  36. #define malloc ld_x_malloc
  37. #define free ld_x_free
  38. uintptr_t _malloc_minimum = 0;
  39. static void * malloc(size_t size) {
  40. return _malloc(size);
  41. }
  42. static void free(void * ptr) {
  43. if ((uintptr_t)ptr < _malloc_minimum) return;
  44. _free(ptr);
  45. }
  46. /*
  47. * When the LD_DEBUG environment variable is set, TRACE_LD messages
  48. * will be printed to stderr
  49. */
  50. #define TRACE_APP_NAME "ld.so"
  51. #define TRACE_LD(...) do { if (__trace_ld) { TRACE(__VA_ARGS__); } } while (0)
  52. static int __trace_ld = 0;
  53. #include <toaru/trace.h>
  54. /*
  55. * This libraries are included in source form to avoid having
  56. * to build separate objects for them and complicate linking,
  57. * since ld is specially built as a static object.
  58. */
  59. #include "../lib/list.c"
  60. #include "../lib/hashmap.c"
  61. typedef int (*entry_point_t)(int, char *[], char**);
  62. /* Global linking state */
  63. static hashmap_t * dumb_symbol_table;
  64. static hashmap_t * glob_dat;
  65. static hashmap_t * objects_map;
  66. /* Used for dlerror */
  67. static char * last_error = NULL;
  68. static int _target_is_suid = 0;
  69. typedef struct elf_object {
  70. FILE * file;
  71. /* Full copy of the header. */
  72. Elf32_Header header;
  73. char * dyn_string_table;
  74. size_t dyn_string_table_size;
  75. Elf32_Sym * dyn_symbol_table;
  76. size_t dyn_symbol_table_size;
  77. Elf32_Dyn * dynamic;
  78. Elf32_Word * dyn_hash;
  79. void (*init)(void);
  80. void (**init_array)(void);
  81. size_t init_array_size;
  82. uintptr_t base;
  83. list_t * dependencies;
  84. int loaded;
  85. } elf_t;
  86. static elf_t * _main_obj = NULL;
  87. /* Locate library for LD_LIBRARY PATH */
  88. static char * find_lib(const char * file) {
  89. /* If it was an absolute path, there's no need to find it. */
  90. if (strchr(file, '/')) return strdup(file);
  91. /* Collect the environment variable. */
  92. char * path = _target_is_suid ? NULL : getenv("LD_LIBRARY_PATH");
  93. if (!path) {
  94. /* Not set - this is the default state. Should probably read from config file? */
  95. path = "/lib:/usr/lib";
  96. }
  97. /* Duplicate so we can tokenize without editing */
  98. char * xpath = strdup(path);
  99. char * p, * last;
  100. for ((p = strtok_r(xpath, ":", &last)); p; p = strtok_r(NULL, ":", &last)) {
  101. /* Go through each LD_LIBRARY_PATH entry */
  102. int r;
  103. struct stat stat_buf;
  104. /* Append the requested file to that path */
  105. char * exe = malloc(strlen(p) + strlen(file) + 2);
  106. *exe = '\0';
  107. strcat(exe, p);
  108. strcat(exe, "/");
  109. strcat(exe, file);
  110. /* See if it exists */
  111. r = stat(exe, &stat_buf);
  112. if (r != 0) {
  113. /* Nope. */
  114. free(exe);
  115. continue;
  116. }
  117. /* It exists, so this is what we want. */
  118. return exe;
  119. }
  120. free(xpath);
  121. /* No match found. */
  122. return NULL;
  123. }
  124. /* Open an object file */
  125. static elf_t * open_object(const char * path) {
  126. /* If no path (eg. dlopen(NULL)), return the main object (the executable). */
  127. if (!path) {
  128. return _main_obj;
  129. }
  130. /* If we've already opened a file with this name, return it - don't load things twice. */
  131. if (hashmap_has(objects_map, (void*)path)) {
  132. elf_t * object = hashmap_get(objects_map, (void*)path);
  133. return object;
  134. }
  135. /* Locate the library */
  136. char * file = find_lib(path);
  137. if (!file) {
  138. last_error = "Could not find library.";
  139. return NULL;
  140. }
  141. /* Open the library. */
  142. FILE * f = fopen(file, "r");
  143. /* Free the expanded path, we don't need it anymore. */
  144. free(file);
  145. /* Failed to open? Unlikely, but could mean permissions problems. */
  146. if (!f) {
  147. last_error = "Could not open library.";
  148. return NULL;
  149. }
  150. /* Initialize a fresh object object. */
  151. elf_t * object = malloc(sizeof(elf_t));
  152. memset(object, 0, sizeof(elf_t));
  153. hashmap_set(objects_map, (void*)path, object);
  154. /* Really unlikely... */
  155. if (!object) {
  156. last_error = "Could not allocate space.";
  157. return NULL;
  158. }
  159. object->file = f;
  160. /* Read the header */
  161. size_t r = fread(&object->header, sizeof(Elf32_Header), 1, object->file);
  162. /* Header failed to read? */
  163. if (!r) {
  164. last_error = "Failed to read object header.";
  165. free(object);
  166. return NULL;
  167. }
  168. /* Is this actually an ELF object? */
  169. if (object->header.e_ident[0] != ELFMAG0 ||
  170. object->header.e_ident[1] != ELFMAG1 ||
  171. object->header.e_ident[2] != ELFMAG2 ||
  172. object->header.e_ident[3] != ELFMAG3) {
  173. last_error = "Not an ELF object.";
  174. free(object);
  175. return NULL;
  176. }
  177. /* Prepare a list for tracking dependencies. */
  178. object->dependencies = list_create();
  179. return object;
  180. }
  181. /* Calculate the size of an object file by examining its phdrs */
  182. static size_t object_calculate_size(elf_t * object) {
  183. uintptr_t base_addr = 0xFFFFFFFF;
  184. uintptr_t end_addr = 0x0;
  185. size_t headers = 0;
  186. while (headers < object->header.e_phnum) {
  187. Elf32_Phdr phdr;
  188. /* Read the phdr */
  189. fseek(object->file, object->header.e_phoff + object->header.e_phentsize * headers, SEEK_SET);
  190. fread(&phdr, object->header.e_phentsize, 1, object->file);
  191. switch (phdr.p_type) {
  192. case PT_LOAD:
  193. {
  194. /* If this loads lower than our current base... */
  195. if (phdr.p_vaddr < base_addr) {
  196. base_addr = phdr.p_vaddr;
  197. }
  198. /* Or higher than our current end address... */
  199. if (phdr.p_memsz + phdr.p_vaddr > end_addr) {
  200. end_addr = phdr.p_memsz + phdr.p_vaddr;
  201. }
  202. }
  203. break;
  204. /* TODO: Do we care about other PHDR types here? */
  205. default:
  206. break;
  207. }
  208. headers++;
  209. }
  210. /* If base_addr is still -1, then no valid phdrs were found, and the object has no loaded size. */
  211. if (base_addr == 0xFFFFFFFF) return 0;
  212. return end_addr - base_addr;
  213. }
  214. /* Load an object into memory */
  215. static uintptr_t object_load(elf_t * object, uintptr_t base) {
  216. uintptr_t end_addr = 0x0;
  217. object->base = base;
  218. size_t headers = 0;
  219. while (headers < object->header.e_phnum) {
  220. Elf32_Phdr phdr;
  221. /* Read the phdr */
  222. fseek(object->file, object->header.e_phoff + object->header.e_phentsize * headers, SEEK_SET);
  223. fread(&phdr, object->header.e_phentsize, 1, object->file);
  224. switch (phdr.p_type) {
  225. case PT_LOAD:
  226. {
  227. /* Request memory to load this PHDR into */
  228. char * args[] = {(char *)(base + phdr.p_vaddr), (char *)phdr.p_memsz};
  229. sysfunc(TOARU_SYS_FUNC_MMAP, args);
  230. /* Copy the code into memory */
  231. fseek(object->file, phdr.p_offset, SEEK_SET);
  232. fread((void *)(base + phdr.p_vaddr), phdr.p_filesz, 1, object->file);
  233. /* Zero the remaining area */
  234. size_t r = phdr.p_filesz;
  235. while (r < phdr.p_memsz) {
  236. *(char *)(phdr.p_vaddr + base + r) = 0;
  237. r++;
  238. }
  239. /* If this expands our end address, be sure to update it */
  240. if (end_addr < phdr.p_vaddr + base + phdr.p_memsz) {
  241. end_addr = phdr.p_vaddr + base + phdr.p_memsz;
  242. }
  243. }
  244. break;
  245. case PT_DYNAMIC:
  246. {
  247. /* Keep a reference to the dynamic section, which is actually loaded by a PT_LOAD normally. */
  248. object->dynamic = (Elf32_Dyn *)(base + phdr.p_vaddr);
  249. }
  250. break;
  251. default:
  252. break;
  253. }
  254. headers++;
  255. }
  256. return end_addr;
  257. }
  258. /* Perform cleanup after loading */
  259. static int object_postload(elf_t * object) {
  260. /* If there is a dynamic table, parse it. */
  261. if (object->dynamic) {
  262. Elf32_Dyn * table;
  263. /* Locate string tables */
  264. table = object->dynamic;
  265. while (table->d_tag) {
  266. switch (table->d_tag) {
  267. case 4:
  268. object->dyn_hash = (Elf32_Word *)(object->base + table->d_un.d_ptr);
  269. object->dyn_symbol_table_size = object->dyn_hash[1];
  270. break;
  271. case 5: /* Dynamic String Table */
  272. object->dyn_string_table = (char *)(object->base + table->d_un.d_ptr);
  273. break;
  274. case 6: /* Dynamic Symbol Table */
  275. object->dyn_symbol_table = (Elf32_Sym *)(object->base + table->d_un.d_ptr);
  276. break;
  277. case 10: /* Size of string table */
  278. object->dyn_string_table_size = table->d_un.d_val;
  279. break;
  280. case 12: /* DT_INIT - initialization function */
  281. object->init = (void (*)(void))(table->d_un.d_ptr + object->base);
  282. break;
  283. case 25: /* DT_INIT_ARRAY - array of constructors */
  284. object->init_array = (void (**)(void))(table->d_un.d_ptr + object->base);
  285. break;
  286. case 27: /* DT_INIT_ARRAYSZ - size of the table of constructors */
  287. object->init_array_size = table->d_un.d_val / sizeof(uintptr_t);
  288. break;
  289. }
  290. table++;
  291. }
  292. /*
  293. * Read through dependencies
  294. * We have to do this separately from the above to make sure
  295. * we have the dynamic string tables loaded first, as they
  296. * are needed for the dependency names.
  297. */
  298. table = object->dynamic;
  299. while (table->d_tag) {
  300. switch (table->d_tag) {
  301. case 1:
  302. list_insert(object->dependencies, object->dyn_string_table + table->d_un.d_val);
  303. break;
  304. }
  305. table++;
  306. }
  307. }
  308. return 0;
  309. }
  310. /* Whether symbol addresses is needed for a relocation type */
  311. static int need_symbol_for_type(unsigned char type) {
  312. switch(type) {
  313. case 1:
  314. case 2:
  315. case 5:
  316. case 6:
  317. case 7:
  318. return 1;
  319. default:
  320. return 0;
  321. }
  322. }
  323. /* Apply ELF relocations */
  324. static int object_relocate(elf_t * object) {
  325. /* If there is a dynamic symbol table, load symbols */
  326. if (object->dyn_symbol_table) {
  327. Elf32_Sym * table = object->dyn_symbol_table;
  328. size_t i = 0;
  329. while (i < object->dyn_symbol_table_size) {
  330. char * symname = (char *)((uintptr_t)object->dyn_string_table + table->st_name);
  331. /* If we haven't added this symbol to our symbol table, do so now. */
  332. if (!hashmap_has(dumb_symbol_table, symname)) {
  333. if (table->st_shndx) {
  334. hashmap_set(dumb_symbol_table, symname, (void*)(table->st_value + object->base));
  335. }
  336. }
  337. table++;
  338. i++;
  339. }
  340. }
  341. /* Find relocation table */
  342. for (uintptr_t x = 0; x < object->header.e_shentsize * object->header.e_shnum; x += object->header.e_shentsize) {
  343. Elf32_Shdr shdr;
  344. /* Load section header */
  345. fseek(object->file, object->header.e_shoff + x, SEEK_SET);
  346. fread(&shdr, object->header.e_shentsize, 1, object->file);
  347. /* Relocation table found */
  348. if (shdr.sh_type == 9) {
  349. Elf32_Rel * table = (Elf32_Rel *)(shdr.sh_addr + object->base);
  350. while ((uintptr_t)table - ((uintptr_t)shdr.sh_addr + object->base) < shdr.sh_size) {
  351. unsigned int symbol = ELF32_R_SYM(table->r_info);
  352. unsigned char type = ELF32_R_TYPE(table->r_info);
  353. Elf32_Sym * sym = &object->dyn_symbol_table[symbol];
  354. /* If we need symbol for this, get it. */
  355. char * symname = NULL;
  356. uintptr_t x = sym->st_value + object->base;
  357. if (need_symbol_for_type(type) || (type == 5)) {
  358. symname = (char *)((uintptr_t)object->dyn_string_table + sym->st_name);
  359. if (symname && hashmap_has(dumb_symbol_table, symname)) {
  360. x = (uintptr_t)hashmap_get(dumb_symbol_table, symname);
  361. } else {
  362. /* This isn't fatal, but do log a message if debugging is enabled. */
  363. TRACE_LD("Symbol not found: %s", symname);
  364. x = 0x0;
  365. }
  366. }
  367. /* Relocations, symbol lookups, etc. */
  368. switch (type) {
  369. case 6: /* GLOB_DAT */
  370. if (symname && hashmap_has(glob_dat, symname)) {
  371. x = (uintptr_t)hashmap_get(glob_dat, symname);
  372. }
  373. case 7: /* JUMP_SLOT */
  374. memcpy((void *)(table->r_offset + object->base), &x, sizeof(uintptr_t));
  375. break;
  376. case 1: /* 32 */
  377. x += *((ssize_t *)(table->r_offset + object->base));
  378. memcpy((void *)(table->r_offset + object->base), &x, sizeof(uintptr_t));
  379. break;
  380. case 2: /* PC32 */
  381. x += *((ssize_t *)(table->r_offset + object->base));
  382. x -= (table->r_offset + object->base);
  383. memcpy((void *)(table->r_offset + object->base), &x, sizeof(uintptr_t));
  384. break;
  385. case 8: /* RELATIVE */
  386. x = object->base;
  387. x += *((ssize_t *)(table->r_offset + object->base));
  388. memcpy((void *)(table->r_offset + object->base), &x, sizeof(uintptr_t));
  389. break;
  390. case 5: /* COPY */
  391. memcpy((void *)(table->r_offset + object->base), (void *)x, sym->st_size);
  392. break;
  393. default:
  394. TRACE_LD("Unknown relocation type: %d", type);
  395. }
  396. table++;
  397. }
  398. }
  399. }
  400. return 0;
  401. }
  402. /* Copy relocations are special and need to be located before other relocations. */
  403. static void object_find_copy_relocations(elf_t * object) {
  404. for (uintptr_t x = 0; x < object->header.e_shentsize * object->header.e_shnum; x += object->header.e_shentsize) {
  405. Elf32_Shdr shdr;
  406. fseek(object->file, object->header.e_shoff + x, SEEK_SET);
  407. fread(&shdr, object->header.e_shentsize, 1, object->file);
  408. /* Relocation table found */
  409. if (shdr.sh_type == 9) {
  410. Elf32_Rel * table = (Elf32_Rel *)(shdr.sh_addr + object->base);
  411. while ((uintptr_t)table - ((uintptr_t)shdr.sh_addr + object->base) < shdr.sh_size) {
  412. unsigned char type = ELF32_R_TYPE(table->r_info);
  413. if (type == 5) {
  414. unsigned int symbol = ELF32_R_SYM(table->r_info);
  415. Elf32_Sym * sym = &object->dyn_symbol_table[symbol];
  416. char * symname = (char *)((uintptr_t)object->dyn_string_table + sym->st_name);
  417. hashmap_set(glob_dat, symname, (void *)table->r_offset);
  418. }
  419. table++;
  420. }
  421. }
  422. }
  423. }
  424. /* Find a symbol in a specific object. */
  425. static void * object_find_symbol(elf_t * object, const char * symbol_name) {
  426. if (!object->dyn_symbol_table) {
  427. last_error = "lib does not have a symbol table";
  428. return NULL;
  429. }
  430. Elf32_Sym * table = object->dyn_symbol_table;
  431. size_t i = 0;
  432. while (i < object->dyn_symbol_table_size) {
  433. if (!strcmp(symbol_name, (char *)((uintptr_t)object->dyn_string_table + table->st_name))) {
  434. return (void *)(table->st_value + object->base);
  435. }
  436. table++;
  437. i++;
  438. }
  439. last_error = "symbol not found in library";
  440. return NULL;
  441. }
  442. /* Fully load an object. */
  443. static void * do_actual_load(const char * filename, elf_t * lib, int flags) {
  444. (void)flags;
  445. if (!lib) {
  446. last_error = "could not open library (not found, or other failure)";
  447. TRACE_LD("could not open library");
  448. return NULL;
  449. }
  450. size_t lib_size = object_calculate_size(lib);
  451. /* Needs to be at least a page. */
  452. if (lib_size < 4096) {
  453. lib_size = 4096;
  454. }
  455. /*
  456. * Allocate space to load the library
  457. * This is where we should really be loading things into COW
  458. * but we don't have the functionality available.
  459. */
  460. uintptr_t load_addr = (uintptr_t)malloc(lib_size);
  461. object_load(lib, load_addr);
  462. /* Perform cleanup steps */
  463. object_postload(lib);
  464. /* Ensure dependencies are available */
  465. node_t * item;
  466. while ((item = list_pop(lib->dependencies))) {
  467. elf_t * _lib = open_object(item->value);
  468. if (!_lib) {
  469. /* Missing dependencies are fatal to this process, but
  470. * not to the entire application. */
  471. free((void *)load_addr);
  472. last_error = "Failed to load a dependency.";
  473. lib->loaded = 0;
  474. TRACE_LD("Failed to load object: %s", item->value);
  475. return NULL;
  476. }
  477. if (!_lib->loaded) {
  478. do_actual_load(item->value, _lib, 0);
  479. TRACE_LD("Loaded %s at 0x%x", item->value, lib->base);
  480. }
  481. }
  482. /* Perform relocations */
  483. TRACE_LD("Relocating %s", filename);
  484. object_relocate(lib);
  485. /* We're done with the file. */
  486. fclose(lib->file);
  487. /* If there was an init_array, call everything in it */
  488. if (lib->init_array) {
  489. for (size_t i = 0; i < lib->init_array_size; i++) {
  490. TRACE_LD(" 0x%x()", lib->init_array[i]);
  491. lib->init_array[i]();
  492. }
  493. }
  494. /* If the library has an init function, call that last. */
  495. if (lib->init) {
  496. lib->init();
  497. }
  498. lib->loaded = 1;
  499. /* And return an object for the loaded library */
  500. return (void *)lib;
  501. }
  502. /* exposed dlopen() method */
  503. static void * dlopen_ld(const char * filename, int flags) {
  504. TRACE_LD("dlopen(%s,0x%x)", filename, flags);
  505. elf_t * lib = open_object(filename);
  506. if (!lib) {
  507. return NULL;
  508. }
  509. if (lib->loaded) {
  510. return lib;
  511. }
  512. void * ret = do_actual_load(filename, lib, flags);
  513. if (!ret) {
  514. /* Dependency load failure, remove us from hash */
  515. TRACE_LD("Dependency load failure");
  516. hashmap_remove(objects_map, (void*)filename);
  517. }
  518. TRACE_LD("Loaded %s at 0x%x", filename, lib->base);
  519. return ret;
  520. }
  521. /* exposed dlclose() method - XXX not fully implemented */
  522. static int dlclose_ld(elf_t * lib) {
  523. /* TODO close dependencies? Make sure nothing references this. */
  524. free((void *)lib->base);
  525. return 0;
  526. }
  527. /* exposed dlerror() method */
  528. static char * dlerror_ld(void) {
  529. char * this_error = last_error;
  530. last_error = NULL;
  531. return this_error;
  532. }
  533. /* Specially used by libc */
  534. static void * _argv_value = NULL;
  535. static char * argv_value(void) {
  536. return _argv_value;
  537. }
  538. /* Exported methods (dlfcn) */
  539. typedef struct {
  540. char * name;
  541. void * symbol;
  542. } ld_exports_t;
  543. ld_exports_t ld_builtin_exports[] = {
  544. {"dlopen", dlopen_ld},
  545. {"dlsym", object_find_symbol},
  546. {"dlclose", dlclose_ld},
  547. {"dlerror", dlerror_ld},
  548. {"__get_argv", argv_value},
  549. {NULL, NULL},
  550. };
  551. int main(int argc, char * argv[]) {
  552. if (argc < 2) {
  553. fprintf(stderr,
  554. "ld.so - dynamic binary loader\n"
  555. "\n"
  556. "usage: %s [-e] [EXECUTABLE PATH]\n"
  557. "\n"
  558. " -e \033[3mAdjust argument offset\033[0m\n"
  559. "\n", argv[0]);
  560. return -1;
  561. }
  562. char * file = argv[1];
  563. size_t arg_offset = 1;
  564. if (!strcmp(argv[1], "-e")) {
  565. arg_offset = 3;
  566. file = argv[2];
  567. }
  568. _argv_value = argv+arg_offset;
  569. /* Enable tracing if requested */
  570. char * trace_ld_env = getenv("LD_DEBUG");
  571. if ((trace_ld_env && (!strcmp(trace_ld_env,"1") || !strcmp(trace_ld_env,"yes")))) {
  572. __trace_ld = 1;
  573. }
  574. /* Initialize hashmaps for symbols, GLOB_DATs, and objects */
  575. dumb_symbol_table = hashmap_create(10);
  576. glob_dat = hashmap_create(10);
  577. objects_map = hashmap_create(10);
  578. /* Setup symbols for built-in exports */
  579. ld_exports_t * ex = ld_builtin_exports;
  580. while (ex->name) {
  581. hashmap_set(dumb_symbol_table, ex->name, ex->symbol);
  582. ex++;
  583. }
  584. /* Technically there's a potential time-of-use probably if we check like this but
  585. * this is a toy linker for a toy OS so the fact that we even need to check suid
  586. * bits at all is outrageous
  587. */
  588. struct stat buf;
  589. if (stat(file, &buf)) {
  590. fprintf(stderr, "%s: target binary '%s' not available\n", argv[0], file);
  591. }
  592. /* Technically there's a way to know we're running suid, but let's check the actual file */
  593. if (buf.st_mode & S_ISUID) {
  594. _target_is_suid = 1;
  595. }
  596. /* Open the requested main object */
  597. elf_t * main_obj = open_object(file);
  598. _main_obj = main_obj;
  599. if (!main_obj) {
  600. fprintf(stderr, "%s: error: failed to open object '%s'.\n", argv[0], file);
  601. return 1;
  602. }
  603. /* Load the main object */
  604. uintptr_t end_addr = object_load(main_obj, 0x0);
  605. object_postload(main_obj);
  606. object_find_copy_relocations(main_obj);
  607. /* Load library dependencies */
  608. hashmap_t * libs = hashmap_create(10);
  609. while (end_addr & 0xFFF) {
  610. end_addr++;
  611. }
  612. list_t * ctor_libs = list_create();
  613. list_t * init_libs = list_create();
  614. TRACE_LD("Loading dependencies.");
  615. node_t * item;
  616. while ((item = list_pop(main_obj->dependencies))) {
  617. while (end_addr & 0xFFF) {
  618. end_addr++;
  619. }
  620. char * lib_name = item->value;
  621. /* Reject libg.so */
  622. if (!strcmp(lib_name, "libg.so")) goto nope;
  623. elf_t * lib = open_object(lib_name);
  624. if (!lib) {
  625. fprintf(stderr, "Failed to load dependency '%s'.\n", lib_name);
  626. return 1;
  627. }
  628. hashmap_set(libs, lib_name, lib);
  629. TRACE_LD("Loading %s at 0x%x", lib_name, end_addr);
  630. end_addr = object_load(lib, end_addr);
  631. object_postload(lib);
  632. TRACE_LD("Relocating %s", lib_name);
  633. object_relocate(lib);
  634. fclose(lib->file);
  635. /* Store constructors for later execution */
  636. if (lib->init_array) {
  637. list_insert(ctor_libs, lib);
  638. }
  639. if (lib->init) {
  640. list_insert(init_libs, lib);
  641. }
  642. lib->loaded = 1;
  643. nope:
  644. free(item);
  645. }
  646. /* Relocate the main object */
  647. TRACE_LD("Relocating main object");
  648. object_relocate(main_obj);
  649. fclose(main_obj->file);
  650. TRACE_LD("Placing heap at end");
  651. while (end_addr & 0xFFF) {
  652. end_addr++;
  653. }
  654. /* Call constructors for loaded dependencies */
  655. char * ld_no_ctors = getenv("LD_DISABLE_CTORS");
  656. if (ld_no_ctors && (!strcmp(ld_no_ctors,"1") || !strcmp(ld_no_ctors,"yes"))) {
  657. TRACE_LD("skipping ctors because LD_DISABLE_CTORS was set");
  658. } else {
  659. foreach(node, ctor_libs) {
  660. elf_t * lib = node->value;
  661. if (lib->init_array) {
  662. TRACE_LD("Executing init_array...");
  663. for (size_t i = 0; i < lib->init_array_size; i++) {
  664. TRACE_LD(" 0x%x()", lib->init_array[i]);
  665. lib->init_array[i]();
  666. }
  667. }
  668. }
  669. }
  670. foreach(node, init_libs) {
  671. elf_t * lib = node->value;
  672. lib->init();
  673. }
  674. /* If main object had constructors, call them. */
  675. if (main_obj->init_array) {
  676. for (size_t i = 0; i < main_obj->init_array_size; i++) {
  677. TRACE_LD(" 0x%x()", main_obj->init_array[i]);
  678. main_obj->init_array[i]();
  679. }
  680. }
  681. if (main_obj->init) {
  682. main_obj->init();
  683. }
  684. main_obj->loaded = 1;
  685. /* Move heap start (kind of like a weird sbrk) */
  686. {
  687. char * args[] = {(char*)end_addr};
  688. sysfunc(TOARU_SYS_FUNC_SETHEAP, args);
  689. }
  690. /* Set heap functions for later usage */
  691. if (hashmap_has(dumb_symbol_table, "malloc")) _malloc = hashmap_get(dumb_symbol_table, "malloc");
  692. if (hashmap_has(dumb_symbol_table, "free")) _free = hashmap_get(dumb_symbol_table, "free");
  693. _malloc_minimum = 0x40000000;
  694. /* Jump to the entry for the main object */
  695. TRACE_LD("Jumping to entry point");
  696. entry_point_t entry = (entry_point_t)main_obj->header.e_entry;
  697. entry(argc-arg_offset,argv+arg_offset,environ);
  698. return 0;
  699. }