db_rtld.c 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360
  1. /* Copyright (C) 2014 Stony Brook University
  2. This file is part of Graphene Library OS.
  3. Graphene Library OS is free software: you can redistribute it and/or
  4. modify it under the terms of the GNU Lesser General Public License
  5. as published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. Graphene Library OS is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  13. /*
  14. * db_rtld.c
  15. *
  16. * This file contains utilities to load ELF binaries into the memory
  17. * and link them against each other.
  18. * The source code in this file is imported and modified from the GNU C
  19. * Library.
  20. */
  21. #include "pal_defs.h"
  22. #include "pal.h"
  23. #include "pal_internal.h"
  24. #include "pal_debug.h"
  25. #include "pal_error.h"
  26. #include "pal_rtld.h"
  27. #include "api.h"
  28. #include <sysdeps/generic/ldsodefs.h>
  29. #include <elf/elf.h>
  30. struct link_map * loaded_maps = NULL;
  31. struct link_map * exec_map = NULL;
  32. struct link_map * lookup_symbol (const char *undef_name, ElfW(Sym) **ref);
  33. /* This macro is used as a callback from the ELF_DYNAMIC_RELOCATE code. */
  34. static struct link_map * resolve_map (const char **strtab, ElfW(Sym) ** ref)
  35. {
  36. if (ELFW(ST_BIND) ((*ref)->st_info) != STB_LOCAL) {
  37. struct link_map * l = lookup_symbol((*strtab) + (*ref)->st_name, ref);
  38. if (l) {
  39. *strtab = (const void *) D_PTR (l->l_info[DT_STRTAB]);
  40. return l;
  41. }
  42. }
  43. return 0;
  44. }
  45. /* Define RESOLVE_RTLD as 0 since we rely on resolve_map on
  46. * all current PAL platforms */
  47. #define RESOLVE_RTLD(sym_name) 0
  48. #define RESOLVE_MAP(strtab, ref) resolve_map(strtab, ref)
  49. #include "dynamic_link.h"
  50. #include "dl-machine-x86_64.h"
  51. /* Allocate a `struct link_map' for a new object being loaded,
  52. and enter it into the _dl_loaded list. */
  53. struct link_map *
  54. new_elf_object (const char * realname, enum object_type type)
  55. {
  56. struct link_map *new;
  57. new = (struct link_map *) malloc(sizeof (struct link_map));
  58. if (new == NULL)
  59. return NULL;
  60. /* We apparently expect this to be zeroed. */
  61. memset(new, 0, sizeof(struct link_map));
  62. new->l_name = realname ?
  63. malloc_copy(realname, strlen(realname) + 1) :
  64. NULL;
  65. new->l_type = type;
  66. return new;
  67. }
  68. /* Cache the location of MAP's hash table. */
  69. void setup_elf_hash (struct link_map *map)
  70. {
  71. Elf_Symndx * hash;
  72. if (map->l_info[DT_ADDRTAGIDX(DT_GNU_HASH) + DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM
  73. + DT_EXTRANUM + DT_VALNUM] != NULL) {
  74. Elf32_Word *hash32
  75. = (void *) D_PTR (map->l_info[DT_ADDRTAGIDX (DT_GNU_HASH) + DT_NUM
  76. + DT_THISPROCNUM + DT_VERSIONTAGNUM
  77. + DT_EXTRANUM + DT_VALNUM]);
  78. map->l_nbuckets = *hash32++;
  79. Elf32_Word symbias = *hash32++;
  80. Elf32_Word bitmask_nwords = *hash32++;
  81. assert(IS_POWER_OF_2(bitmask_nwords));
  82. map->l_gnu_bitmask_idxbits = bitmask_nwords - 1;
  83. map->l_gnu_shift = *hash32++;
  84. map->l_gnu_bitmask = (ElfW(Addr) *) hash32;
  85. hash32 += __ELF_NATIVE_CLASS / 32 * bitmask_nwords;
  86. map->l_gnu_buckets = hash32;
  87. hash32 += map->l_nbuckets;
  88. map->l_gnu_chain_zero = hash32 - symbias;
  89. return;
  90. }
  91. if (!map->l_info[DT_HASH])
  92. return;
  93. hash = (void *) D_PTR (map->l_info[DT_HASH]);
  94. /* Structure of DT_HASH:
  95. The bucket array forms the hast table itself. The entries in the
  96. chain array parallel the symbol table.
  97. [ nbucket ]
  98. [ nchain ]
  99. [ bucket[0] ]
  100. [ ... ]
  101. [ bucket[nbucket-1] ]
  102. [ chain[0] ]
  103. [ ... ]
  104. [ chain[nchain-1] ] */
  105. map->l_nbuckets = *hash++;
  106. hash++;
  107. map->l_buckets = hash;
  108. hash += map->l_nbuckets;
  109. map->l_chain = hash;
  110. }
  111. /* Map in the shared object NAME, actually located in REALNAME, and already
  112. opened on FD */
  113. struct link_map *
  114. map_elf_object_by_handle (PAL_HANDLE handle, enum object_type type,
  115. void * fbp, size_t fbp_len,
  116. bool do_copy_dyn)
  117. {
  118. struct link_map * l = new_elf_object(_DkStreamRealpath(handle), type);
  119. int ret;
  120. if (handle == NULL) {
  121. print_error("cannot stat shared object", -PAL_ERROR_INVAL);
  122. return NULL;
  123. }
  124. /* This is the ELF header. We read it in `open_verify'. */
  125. const ElfW(Ehdr) * header = (void *) fbp;
  126. /* Extract the remaining details we need from the ELF header
  127. and then read in the program header table. */
  128. int e_type = header->e_type;
  129. l->l_entry = header->e_entry;
  130. l->l_phnum = header->e_phnum;
  131. size_t maplength = header->e_phnum * sizeof (ElfW(Phdr));
  132. ElfW(Phdr) * phdr;
  133. if (header->e_phoff + maplength <= fbp_len) {
  134. phdr = (void *) ((char *) fbp + header->e_phoff);
  135. } else {
  136. phdr = (ElfW(Phdr) *) malloc (maplength);
  137. if ((ret = _DkStreamRead(handle, header->e_phoff, maplength, phdr,
  138. NULL, 0)) < 0) {
  139. print_error("cannot read file data", ret);
  140. return NULL;
  141. }
  142. }
  143. /* Presumed absent PT_GNU_STACK. */
  144. //uint_fast16_t stack_flags = PF_R|PF_W|PF_X;
  145. /* Scan the program header table, collecting its load commands. */
  146. struct loadcmd {
  147. ElfW(Addr) mapstart, mapend, dataend, allocend;
  148. unsigned int mapoff;
  149. int prot;
  150. } * loadcmds, *c;
  151. loadcmds = __alloca(sizeof(struct loadcmd) * l->l_phnum);
  152. int nloadcmds = 0;
  153. bool has_holes = false;
  154. /* The struct is initialized to zero so this is not necessary:
  155. l->l_ld = 0;
  156. l->l_phdr = 0;
  157. l->l_addr = 0; */
  158. const ElfW(Phdr) * ph;
  159. for (ph = phdr; ph < &phdr[l->l_phnum]; ++ph)
  160. switch (ph->p_type)
  161. {
  162. /* These entries tell us where to find things once the file's
  163. segments are mapped in. We record the addresses it says
  164. verbatim, and later correct for the run-time load address. */
  165. case PT_DYNAMIC:
  166. l->l_ld = (void *) ph->p_vaddr;
  167. l->l_ldnum = ph->p_memsz / sizeof (ElfW(Dyn));
  168. break;
  169. case PT_PHDR:
  170. l->l_phdr = (void *) ph->p_vaddr;
  171. break;
  172. case PT_LOAD:
  173. /* A load command tells us to map in part of the file.
  174. We record the load commands and process them all later. */
  175. if (!IS_ALLOC_ALIGNED(ph->p_align)) {
  176. print_error("ELF load command alignment not aligned",
  177. -PAL_ERROR_NOMEM);
  178. return NULL;
  179. }
  180. if (!IS_ALIGNED_POW2(ph->p_vaddr - ph->p_offset, ph->p_align)) {
  181. print_error("ELF load command address/offset not properly aligned",
  182. -PAL_ERROR_NOMEM);
  183. return NULL;
  184. }
  185. c = &loadcmds[nloadcmds++];
  186. c->mapstart = ALLOC_ALIGN_DOWN(ph->p_vaddr);
  187. c->mapend = ALLOC_ALIGN_UP(ph->p_vaddr + ph->p_filesz);
  188. c->dataend = ph->p_vaddr + ph->p_filesz;
  189. c->allocend = ph->p_vaddr + ph->p_memsz;
  190. c->mapoff = ALLOC_ALIGN_DOWN(ph->p_offset);
  191. /* Determine whether there is a gap between the last segment
  192. and this one. */
  193. if (nloadcmds > 1 && c[-1].mapend != c->mapstart)
  194. has_holes = true;
  195. /* Optimize a common case. */
  196. c->prot = 0;
  197. if (ph->p_flags & PF_R)
  198. c->prot |= PAL_PROT_READ;
  199. if (ph->p_flags & PF_W)
  200. c->prot |= PAL_PROT_WRITE;
  201. if (ph->p_flags & PF_X)
  202. c->prot |= PAL_PROT_EXEC;
  203. break;
  204. case PT_TLS:
  205. if (ph->p_memsz == 0)
  206. /* Nothing to do for an empty segment. */
  207. break;
  208. case PT_GNU_STACK:
  209. //stack_flags = ph->p_flags;
  210. break;
  211. case PT_GNU_RELRO:
  212. l->l_relro_addr = ph->p_vaddr;
  213. l->l_relro_size = ph->p_memsz;
  214. break;
  215. }
  216. if (nloadcmds == 0) {
  217. /* This only happens for a bogus object that will be caught with
  218. another error below. But we don't want to go through the
  219. calculations below using NLOADCMDS - 1. */
  220. print_error("object file has no loadable segments", -PAL_ERROR_INVAL);
  221. return NULL;
  222. }
  223. /* Now process the load commands and map segments into memory. */
  224. c = loadcmds;
  225. /* Length of the sections to be loaded. */
  226. maplength = loadcmds[nloadcmds - 1].allocend - c->mapstart;
  227. #define APPEND_WRITECOPY(prot) ((prot)|PAL_PROT_WRITECOPY)
  228. if (e_type == ET_DYN) {
  229. /* This is a position-independent shared object. We can let the
  230. kernel map it anywhere it likes, but we must have space for all
  231. the segments in their specified positions relative to the first.
  232. So we map the first segment without MAP_FIXED, but with its
  233. extent increased to cover all the segments. Then we remove
  234. access from excess portion, and there is known sufficient space
  235. there to remap from the later segments.
  236. As a refinement, sometimes we have an address that we would
  237. prefer to map such objects at; but this is only a preference,
  238. the OS can do whatever it likes. */
  239. void * mapaddr = NULL;
  240. /* Remember which part of the address space this object uses. */
  241. ret = _DkStreamMap(handle, (void **) &mapaddr,
  242. APPEND_WRITECOPY(c->prot), c->mapoff, maplength);
  243. if (ret < 0) {
  244. print_error("failed to map dynamic segment from shared object",
  245. ret);
  246. return NULL;
  247. }
  248. l->l_map_start = (ElfW(Addr)) mapaddr;
  249. l->l_map_end = (ElfW(Addr)) mapaddr + maplength;
  250. l->l_addr = l->l_map_start - c->mapstart;
  251. if (has_holes)
  252. /* Change protection on the excess portion to disallow all access;
  253. the portions we do not remap later will be inaccessible as if
  254. unallocated. Then jump into the normal segment-mapping loop to
  255. handle the portion of the segment past the end of the file
  256. mapping. */
  257. _DkVirtualMemoryProtect((void *) (l->l_addr + c->mapend),
  258. loadcmds[nloadcmds - 1].mapstart - c->mapend,
  259. PAL_PROT_NONE);
  260. goto postmap;
  261. }
  262. /* Remember which part of the address space this object uses. */
  263. l->l_map_start = c->mapstart + l->l_addr;
  264. l->l_map_end = l->l_map_start + maplength;
  265. while (c < &loadcmds[nloadcmds]) {
  266. if (c->mapend > c->mapstart) {
  267. /* Map the segment contents from the file. */
  268. void * mapaddr = (void *) (l->l_addr + c->mapstart);
  269. if ((ret = _DkStreamMap(handle, &mapaddr, APPEND_WRITECOPY(c->prot),
  270. c->mapoff, c->mapend - c->mapstart)) < 0) {
  271. print_error("failed to map segment from shared object", ret);
  272. return NULL;
  273. }
  274. }
  275. postmap:
  276. if (l->l_phdr == 0
  277. && (ElfW(Off)) c->mapoff <= header->e_phoff
  278. && ((c->mapend - c->mapstart + c->mapoff)
  279. >= header->e_phoff + header->e_phnum * sizeof (ElfW(Phdr))))
  280. /* Found the program header in this segment. */
  281. l->l_phdr = (void *) (c->mapstart + header->e_phoff - c->mapoff);
  282. if (c->allocend > c->dataend) {
  283. /* Extra zero pages should appear at the end of this segment,
  284. after the data mapped from the file. */
  285. ElfW(Addr) zero, zeroend, zerosec;
  286. zero = l->l_addr + c->dataend;
  287. zeroend = ALLOC_ALIGN_UP(l->l_addr + c->allocend);
  288. zerosec = ALLOC_ALIGN_UP(zero);
  289. if (zeroend < zerosec)
  290. /* All the extra data is in the last section of the segment.
  291. We can just zero it. */
  292. zerosec = zeroend;
  293. if (zerosec > zero) {
  294. /* Zero the final part of the last section of the segment. */
  295. if ((c->prot & PAL_PROT_WRITE) == 0)
  296. {
  297. /* Dag nab it. */
  298. ret = _DkVirtualMemoryProtect(
  299. (void*)ALLOC_ALIGN_DOWN(zero), pal_state.alloc_align,
  300. c->prot | PAL_PROT_WRITE);
  301. if (ret < 0) {
  302. print_error("cannot change memory protections", ret);
  303. return NULL;
  304. }
  305. }
  306. memset ((void *) zero, '\0', zerosec - zero);
  307. if ((c->prot & PAL_PROT_WRITE) == 0)
  308. _DkVirtualMemoryProtect((void*)ALLOC_ALIGN_DOWN(zero),
  309. pal_state.alloc_align, c->prot);
  310. }
  311. if (zeroend > zerosec) {
  312. /* Map the remaining zero pages in from the zero fill FD. */
  313. void * mapat = (void *) zerosec;
  314. ret = _DkVirtualMemoryAlloc(&mapat, zeroend - zerosec,
  315. 0, c->prot);
  316. if (ret < 0) {
  317. print_error("cannot map zero-fill allocation", ret);
  318. return NULL;
  319. }
  320. }
  321. }
  322. ++c;
  323. }
  324. if (l->l_ld == 0) {
  325. if (e_type == ET_DYN) {
  326. print_error("object file has no dynamic section",
  327. -PAL_ERROR_INVAL);
  328. return NULL;
  329. }
  330. } else {
  331. l->l_real_ld = l->l_ld =
  332. (ElfW(Dyn) *) ((ElfW(Addr)) l->l_ld + l->l_addr);
  333. if (do_copy_dyn)
  334. l->l_ld = malloc_copy(l->l_ld, sizeof(ElfW(Dyn)) * l->l_ldnum);
  335. }
  336. elf_get_dynamic_info(l->l_ld, l->l_info, l->l_addr);
  337. if (l->l_phdr == NULL) {
  338. /* The program header is not contained in any of the segments.
  339. We have to allocate memory ourself and copy it over from out
  340. temporary place. */
  341. ElfW(Phdr) * newp = (ElfW(Phdr) *) malloc (header->e_phnum
  342. * sizeof (ElfW(Phdr)));
  343. if (!newp) {
  344. print_error("cannot allocate memory for program header",
  345. -PAL_ERROR_NOMEM);
  346. return NULL;
  347. }
  348. l->l_phdr = memcpy(newp, phdr,
  349. header->e_phnum * sizeof (ElfW(Phdr)));
  350. } else {
  351. /* Adjust the PT_PHDR value by the runtime load address. */
  352. l->l_phdr = (ElfW(Phdr) *) ((ElfW(Addr)) l->l_phdr + l->l_addr);
  353. }
  354. l->l_entry += l->l_addr;
  355. /* Set up the symbol hash table. */
  356. setup_elf_hash (l);
  357. return l;
  358. }
  359. int check_elf_object (PAL_HANDLE handle)
  360. {
  361. #define ELF_MAGIC_SIZE EI_CLASS
  362. unsigned char buffer[ELF_MAGIC_SIZE];
  363. int len = _DkStreamRead(handle, 0, ELF_MAGIC_SIZE, buffer, NULL, 0);
  364. if (len < 0)
  365. return -len;
  366. if (len < ELF_MAGIC_SIZE)
  367. return -PAL_ERROR_INVAL;
  368. ElfW(Ehdr) * ehdr = (ElfW(Ehdr) *) buffer;
  369. static const unsigned char expected[EI_CLASS] =
  370. {
  371. [EI_MAG0] = ELFMAG0,
  372. [EI_MAG1] = ELFMAG1,
  373. [EI_MAG2] = ELFMAG2,
  374. [EI_MAG3] = ELFMAG3,
  375. };
  376. /* See whether the ELF header is what we expect. */
  377. if (memcmp(ehdr->e_ident, expected, ELF_MAGIC_SIZE) != 0)
  378. return -PAL_ERROR_INVAL;
  379. return 0;
  380. }
  381. void free_elf_object (struct link_map * map)
  382. {
  383. _DkVirtualMemoryFree((void *) map->l_map_start,
  384. map->l_map_end - map->l_map_start);
  385. if (map->l_prev)
  386. map->l_prev->l_next = map->l_next;
  387. if (map->l_next)
  388. map->l_next->l_prev = map->l_prev;
  389. #ifdef DEBUG
  390. _DkDebugDelMap(map);
  391. #endif
  392. if (loaded_maps == map)
  393. loaded_maps = map->l_next;
  394. free(map);
  395. }
  396. /* Map in the shared object file loaded from URI. */
  397. int load_elf_object (const char * uri, enum object_type type)
  398. {
  399. PAL_HANDLE handle;
  400. /* First we open the file by uri, as the regular file handles */
  401. int ret = _DkStreamOpen(&handle, uri, PAL_ACCESS_RDONLY,
  402. 0, 0, 0);
  403. if (ret < 0)
  404. return ret;
  405. ret = load_elf_object_by_handle(handle, type);
  406. _DkObjectClose(handle);
  407. return ret;
  408. }
  409. int add_elf_object(void * addr, PAL_HANDLE handle, int type)
  410. {
  411. struct link_map * map = new_elf_object(_DkStreamRealpath(handle), type);
  412. const ElfW(Ehdr) * header = (void *) addr;
  413. const ElfW(Phdr) * ph, * phdr =
  414. (ElfW(Phdr) *) ((char *) addr + header->e_phoff);
  415. map->l_phdr = (void *) header->e_phoff;
  416. map->l_phnum = header->e_phnum;
  417. ElfW(Addr) mapstart = ~0; /* start with the highest possible address */
  418. ElfW(Addr) mapend = 0; /* start with the lowest possible address */
  419. for (ph = phdr; ph < &phdr[map->l_phnum]; ++ph)
  420. switch (ph->p_type) {
  421. case PT_DYNAMIC:
  422. map->l_ld = (void *) ph->p_vaddr;
  423. map->l_ldnum = ph->p_memsz / sizeof (ElfW(Dyn));
  424. break;
  425. case PT_LOAD: {
  426. ElfW(Addr) start = (ElfW(Addr))ALLOC_ALIGN_DOWN(map->l_addr + ph->p_vaddr);
  427. ElfW(Addr) end = (ElfW(Addr))
  428. ALLOC_ALIGN_UP(map->l_addr + ph->p_vaddr + ph->p_memsz);
  429. if (start < mapstart)
  430. mapstart = start;
  431. if (end > mapend)
  432. mapend = end;
  433. }
  434. }
  435. map->l_addr = (ElfW(Addr)) addr - mapstart;
  436. map->l_entry = header->e_entry;
  437. map->l_map_start = (ElfW(Addr)) addr;
  438. map->l_map_end = (ElfW(Addr)) addr + (mapend - mapstart);
  439. map->l_real_ld = (ElfW(Dyn) *)
  440. ((char *) map->l_addr + (unsigned long) map->l_ld);
  441. map->l_ld = malloc_copy(map->l_real_ld, sizeof(ElfW(Dyn)) * map->l_ldnum);
  442. elf_get_dynamic_info(map->l_ld, map->l_info, map->l_addr);
  443. setup_elf_hash(map);
  444. ELF_DYNAMIC_RELOCATE(map);
  445. /* append to list (to preserve order of libs specified in
  446. * manifest, e.g., loader.preload)
  447. */
  448. map->l_next = NULL;
  449. if (!loaded_maps) {
  450. map->l_prev = NULL;
  451. loaded_maps = map;
  452. } else {
  453. struct link_map * end = loaded_maps;
  454. while (end->l_next)
  455. end = end->l_next;
  456. end->l_next = map;
  457. map->l_prev = end;
  458. }
  459. if (type == OBJECT_EXEC)
  460. exec_map = map;
  461. #ifdef DEBUG
  462. _DkDebugAddMap(map);
  463. #endif
  464. return 0;
  465. }
  466. static int relocate_elf_object (struct link_map *l);
  467. #if CACHE_LOADED_BINARIES == 1
  468. #define MAX_CACHED_LOADCMDS 32
  469. struct cached_elf_object {
  470. PAL_NUM instance_id;
  471. void * loader_addr; /* get the address of DkStreamOpen */
  472. struct link_map map;
  473. char map_name[80];
  474. struct cached_loadcmd {
  475. void * mapstart;
  476. unsigned long mapsize;
  477. unsigned long mapoff;
  478. int mapprot;
  479. } loadcmds[MAX_CACHED_LOADCMDS];
  480. int nloadcmds;
  481. ElfW(Dyn) dyn[];
  482. };
  483. void cache_elf_object (PAL_HANDLE handle, struct link_map * map)
  484. {
  485. char uri[URI_MAX];
  486. unsigned long cached_size = 0;
  487. int ret = _DkStreamGetName(handle, uri, URI_MAX);
  488. if (ret < 0)
  489. return;
  490. strcpy_static(uri + ret, ".cached", URI_MAX - ret);
  491. PAL_HANDLE cached_file;
  492. while (1) {
  493. ret = _DkStreamOpen(&cached_file, uri,
  494. PAL_ACCESS_RDWR,
  495. PAL_SHARE_OWNER_W|PAL_SHARE_OWNER_R,
  496. PAL_CREATE_TRY|PAL_CREATE_ALWAYS, 0);
  497. if (ret != -PAL_ERROR_STREAMEXIST)
  498. break;
  499. if (_DkStreamOpen(&cached_file, uri, PAL_ACCESS_RDWR, 0, 0, 0) < 0)
  500. return;
  501. ret = _DkStreamDelete(cached_file, 0);
  502. _DkObjectClose(cached_file);
  503. if (ret < 0)
  504. return;
  505. }
  506. if (ret < 0)
  507. return;
  508. struct cached_elf_object * obj = NULL;
  509. unsigned long obj_size = sizeof(struct cached_elf_object);
  510. if (map->l_ld != map->l_real_ld)
  511. obj_size += sizeof(ElfW(Dyn)) * map->l_ldnum;
  512. obj_size = ALLOC_ALIGN_UP(obj_size);
  513. cached_size = obj_size;
  514. ret = _DkStreamSetLength(cached_file, obj_size);
  515. if (ret < 0)
  516. goto out;
  517. ret = _DkStreamMap(cached_file, (void **) &obj,
  518. PAL_PROT_READ|PAL_PROT_WRITE, 0, obj_size);
  519. if (ret < 0)
  520. goto out;
  521. obj->instance_id = pal_state.instance_id;
  522. obj->loader_addr = (void *) DkStreamOpen;
  523. memcpy(&obj->map, map, sizeof(struct link_map));
  524. if (map->l_ld != map->l_real_ld) {
  525. obj->map.l_ld = NULL;
  526. memcpy(obj->dyn, map->l_ld, sizeof(ElfW(Dyn)) * map->l_ldnum);
  527. for (int i = 0; i < ARRAY_SIZE(obj->map.l_info); i++)
  528. if (obj->map.l_info[i])
  529. obj->map.l_info[i] = (void *)obj->map.l_info[i] - (unsigned long)map->l_ld;
  530. }
  531. obj->map.l_name = NULL;
  532. memcpy(obj->map_name, map->l_name, sizeof(obj->map_name));
  533. obj->nloadcmds = 0;
  534. const ElfW(Ehdr) * header = (void *) map->l_map_start;
  535. const ElfW(Phdr) * phdr = (void *) header + header->e_phoff, * ph;
  536. for (ph = phdr ; ph < &phdr[header->e_phnum] ; ph++)
  537. if (ph->p_type == PT_LOAD) {
  538. assert(obj->nloadcmds < MAX_CACHED_LOADCMDS);
  539. void* mapstart = (void*)ALLOC_ALIGN_DOWN(map->l_addr + ph->p_vaddr);
  540. void* mapend = (void*)ALLOC_ALIGN_UP(map->l_addr + ph->p_vaddr + ph->p_memsz);
  541. unsigned long mapsize = mapend - mapstart;
  542. int mapprot = 0;
  543. void * cache_addr = NULL;
  544. if (ph->p_flags & PF_R)
  545. mapprot |= PAL_PROT_READ;
  546. if (ph->p_flags & PF_W)
  547. mapprot |= PAL_PROT_WRITE;
  548. if (ph->p_flags & PF_X)
  549. mapprot |= PAL_PROT_EXEC;
  550. ret = _DkStreamSetLength(cached_file, cached_size + mapsize);
  551. if (ret < 0)
  552. goto out_mapped;
  553. ret = _DkStreamMap(cached_file, &cache_addr,
  554. PAL_PROT_READ|PAL_PROT_WRITE, cached_size,
  555. mapsize);
  556. if (ret < 0)
  557. goto out_mapped;
  558. obj->loadcmds[obj->nloadcmds].mapstart = mapstart;
  559. obj->loadcmds[obj->nloadcmds].mapsize = mapsize;
  560. obj->loadcmds[obj->nloadcmds].mapprot = mapprot;
  561. obj->loadcmds[obj->nloadcmds].mapoff = cached_size;
  562. obj->nloadcmds++;
  563. cached_size += mapsize;
  564. memcpy(cache_addr, mapstart, mapsize);
  565. ret = _DkStreamUnmap(cache_addr, mapsize);
  566. if (ret < 0)
  567. goto out_mapped;
  568. }
  569. ret = _DkStreamUnmap(obj, obj_size);
  570. if (ret < 0)
  571. return;
  572. _DkObjectClose(cached_file);
  573. return;
  574. out_mapped:
  575. _DkStreamUnmap(obj, obj_size);
  576. out:
  577. _DkStreamDelete(cached_file, 0);
  578. _DkObjectClose(cached_file);
  579. }
  580. struct link_map * check_cached_elf_object (PAL_HANDLE handle)
  581. {
  582. char uri[URI_MAX];
  583. int ret = _DkStreamGetName(handle, uri, URI_MAX);
  584. if (ret < 0)
  585. return NULL;
  586. strcpy_static(uri + ret, ".cached", URI_MAX - ret);
  587. PAL_HANDLE cached_file;
  588. ret = _DkStreamOpen(&cached_file, uri, PAL_ACCESS_RDWR, 0, 0, 0);
  589. if (ret < 0)
  590. return NULL;
  591. struct cached_elf_object * obj = NULL;
  592. unsigned long obj_size = ALLOC_ALIGN_UP(sizeof(struct cached_elf_object));
  593. ret = _DkStreamMap(cached_file, (void **) &obj,
  594. PAL_PROT_READ|PAL_PROT_WRITE|PAL_PROT_WRITECOPY,
  595. 0, obj_size);
  596. if (ret < 0)
  597. goto out;
  598. /* we want to check if there is a previously cached one, but if the
  599. * process is the first one, force to update the cached binary. */
  600. if (pal_state.instance_id != obj->instance_id)
  601. goto out_mapped;
  602. if (!obj->map.l_ld) {
  603. obj->map.l_ld = obj->dyn;
  604. for (int i = 0; i < ARRAY_SIZE(obj->map.l_info); i++)
  605. if (obj->map.l_info[i])
  606. obj->map.l_info[i] = (void*)obj->map.l_info[i] + (unsigned long)obj->map.l_ld;
  607. }
  608. struct cached_loadcmd * l = obj->loadcmds;
  609. struct cached_loadcmd * last = &obj->loadcmds[obj->nloadcmds - 1];
  610. if (l < last) {
  611. ret = _DkStreamMap(cached_file, &l->mapstart,
  612. l->mapprot|PAL_PROT_WRITECOPY,
  613. l->mapoff,
  614. last->mapstart + last->mapsize - l->mapstart);
  615. if (ret < 0)
  616. goto out_more_mapped;
  617. ret = _DkVirtualMemoryProtect(l->mapstart + l->mapsize,
  618. last->mapstart - (l->mapstart + l->mapsize),
  619. PAL_PROT_NONE);
  620. if (ret < 0)
  621. goto out_more_mapped;
  622. l++;
  623. }
  624. for ( ; l <= last ; l++) {
  625. ret = _DkStreamMap(cached_file, &l->mapstart,
  626. l->mapprot|PAL_PROT_WRITECOPY,
  627. l->mapoff,
  628. l->mapsize);
  629. if (ret < 0)
  630. goto out_more_mapped;
  631. }
  632. if ((void *) DkStreamOpen != obj->loader_addr) {
  633. for (int i = 0 ; i < obj->map.nrelocs ; i++)
  634. *obj->map.relocs[i] += (void *) DkStreamOpen - obj->loader_addr;
  635. }
  636. obj->map.l_name = obj->map_name;
  637. _DkObjectClose(cached_file);
  638. return &obj->map;
  639. out_more_mapped:
  640. _DkStreamUnmap(obj->loadcmds[0].mapstart,
  641. last->mapstart + last->mapsize - obj->loadcmds[0].mapstart);
  642. out_mapped:
  643. _DkStreamUnmap(obj, obj_size);
  644. out:
  645. _DkObjectClose(cached_file);
  646. return NULL;
  647. }
  648. #endif /* CACHE_LOADED_BINARIES == 1 */
  649. int load_elf_object_by_handle (PAL_HANDLE handle, enum object_type type)
  650. {
  651. struct link_map * map = NULL;
  652. char fb[FILEBUF_SIZE], * errstring;
  653. int ret = 0;
  654. #if CACHE_LOADED_BINARIES == 1
  655. map = check_cached_elf_object(handle);
  656. if (map)
  657. goto done;
  658. #endif
  659. /* Now we will start verify the file as a ELF header. This part of code
  660. is borrow from open_verify() */
  661. ElfW(Ehdr) * ehdr = (ElfW(Ehdr) *) &fb;
  662. ElfW(Phdr) * phdr = NULL;
  663. int phdr_malloced = 0;
  664. int len = _DkStreamRead(handle, 0, FILEBUF_SIZE, &fb, NULL, 0);
  665. if ((size_t)len < sizeof(ElfW(Ehdr))) {
  666. errstring = "ELF file with a strange size";
  667. goto verify_failed;
  668. }
  669. #define ELF32_CLASS ELFCLASS32
  670. #define ELF64_CLASS ELFCLASS64
  671. static const unsigned char expected[EI_NIDENT] =
  672. {
  673. [EI_MAG0] = ELFMAG0,
  674. [EI_MAG1] = ELFMAG1,
  675. [EI_MAG2] = ELFMAG2,
  676. [EI_MAG3] = ELFMAG3,
  677. [EI_CLASS] = ELFW(CLASS),
  678. [EI_DATA] = byteorder,
  679. [EI_VERSION] = EV_CURRENT,
  680. [EI_OSABI] = 0,
  681. };
  682. #define ELFOSABI_LINUX 3 /* Linux. */
  683. /* See whether the ELF header is what we expect. */
  684. if (memcmp(ehdr->e_ident, expected, EI_OSABI) != 0 || (
  685. ehdr->e_ident[EI_OSABI] != ELFOSABI_SYSV &&
  686. ehdr->e_ident[EI_OSABI] != ELFOSABI_LINUX)) {
  687. errstring = "ELF file with invalid header";
  688. goto verify_failed;
  689. }
  690. /* Chia-Che 11/23/13: Removing other checks, comparing the header
  691. should be enough */
  692. size_t maplength = ehdr->e_phnum * sizeof (ElfW(Phdr));
  693. /* if e_phoff + maplength is smaller than the data read */
  694. if (ehdr->e_phoff + maplength <= (size_t) len) {
  695. phdr = (void *) (&fb + ehdr->e_phoff);
  696. } else {
  697. /* ...otherwise, we have to read again */
  698. phdr = malloc (maplength);
  699. phdr_malloced = 1;
  700. ret = _DkStreamRead(handle, ehdr->e_phoff, maplength, phdr, NULL, 0);
  701. if (ret < 0 || (size_t)ret != maplength) {
  702. errstring = "cannot read file data";
  703. goto verify_failed;
  704. }
  705. }
  706. if (!(map = map_elf_object_by_handle(handle, type, &fb, len, true))) {
  707. errstring = "unexpected failure";
  708. goto verify_failed;
  709. }
  710. relocate_elf_object(map);
  711. #if CACHE_LOADED_BINARIES == 1
  712. cache_elf_object(handle, map);
  713. done:
  714. #endif
  715. /* append to list (to preserve order of libs specified in
  716. * manifest, e.g., loader.preload)
  717. */
  718. map->l_next = NULL;
  719. if (!loaded_maps) {
  720. map->l_prev = NULL;
  721. loaded_maps = map;
  722. } else {
  723. struct link_map * end = loaded_maps;
  724. while (end->l_next)
  725. end = end->l_next;
  726. end->l_next = map;
  727. map->l_prev = end;
  728. }
  729. if (map->l_type == OBJECT_EXEC)
  730. exec_map = map;
  731. #ifdef DEBUG
  732. _DkDebugAddMap(map);
  733. #endif
  734. return 0;
  735. verify_failed:
  736. if (phdr && phdr_malloced)
  737. free(phdr);
  738. printf("%s\n", errstring);
  739. return ret;
  740. }
  741. struct sym_val {
  742. ElfW(Sym) *s;
  743. struct link_map *m;
  744. };
  745. /* This is the hashing function specified by the ELF ABI. In the
  746. first five operations no overflow is possible so we optimized it a
  747. bit. */
  748. unsigned long int elf_hash (const char *name_arg)
  749. {
  750. const unsigned char *name = (const unsigned char *) name_arg;
  751. unsigned long int hash = 0;
  752. if (*name == '\0')
  753. return hash;
  754. hash = *name++;
  755. if (*name == '\0')
  756. return hash;
  757. hash = (hash << 4) + *name++;
  758. if (*name == '\0')
  759. return hash;
  760. hash = (hash << 4) + *name++;
  761. if (*name == '\0')
  762. return hash;
  763. hash = (hash << 4) + *name++;
  764. if (*name == '\0')
  765. return hash;
  766. hash = (hash << 4) + *name++;
  767. while (*name != '\0') {
  768. unsigned long int hi;
  769. hash = (hash << 4) + *name++;
  770. hi = hash & 0xf0000000;
  771. /*
  772. * The algorithm specified in the ELF ABI is as follows:
  773. * if (hi != 0)
  774. * hash ^= hi >> 24;
  775. * hash &= ~hi;
  776. * But the following is equivalent and a lot faster, especially on
  777. * modern processors.
  778. */
  779. hash ^= hi;
  780. hash ^= hi >> 24;
  781. }
  782. return hash;
  783. }
  784. /* Nested routine to check whether the symbol matches. */
  785. static inline __attribute_always_inline
  786. ElfW(Sym) * check_match(ElfW(Sym) * sym, ElfW(Sym) * ref, const char * undef_name,
  787. const char * strtab)
  788. {
  789. unsigned int stt = ELFW(ST_TYPE) (sym->st_info);
  790. assert(ELF_RTYPE_CLASS_PLT == 1);
  791. if ((sym->st_value == 0 /* No value */ && stt != STT_TLS) || sym->st_shndx == SHN_UNDEF)
  792. return NULL;
  793. /* Ignore all but STT_NOTYPE, STT_OBJECT, STT_FUNC,
  794. STT_COMMON, STT_TLS, and STT_GNU_IFUNC since these are no
  795. code/data definitions. */
  796. #define ALLOWED_STT \
  797. ((1 << STT_NOTYPE) | (1 << STT_OBJECT) | (1 << STT_FUNC) \
  798. | (1 << STT_COMMON) | (1 << STT_TLS) | (1 << STT_GNU_IFUNC))
  799. if (((1 << stt) & ALLOWED_STT) == 0)
  800. return NULL;
  801. if (sym != ref && memcmp(strtab + sym->st_name, undef_name,
  802. strlen(undef_name)))
  803. /* Not the symbol we are looking for. */
  804. return NULL;
  805. /* There cannot be another entry for this symbol so stop here. */
  806. return sym;
  807. }
  808. ElfW(Sym) *
  809. do_lookup_map (ElfW(Sym) * ref, const char * undef_name,
  810. const uint_fast32_t hash, unsigned long int elf_hash,
  811. const struct link_map * map)
  812. {
  813. /* These variables are used in the nested function. */
  814. Elf_Symndx symidx;
  815. ElfW(Sym) * sym;
  816. /* The tables for this map. */
  817. ElfW(Sym) * symtab = (void *) D_PTR (map->l_info[DT_SYMTAB]);
  818. const char * strtab = (const void *) D_PTR (map->l_info[DT_STRTAB]);
  819. const ElfW(Addr) * bitmask = map->l_gnu_bitmask;
  820. if (bitmask != NULL) {
  821. ElfW(Addr) bitmask_word = bitmask[(hash / __ELF_NATIVE_CLASS)
  822. & map->l_gnu_bitmask_idxbits];
  823. unsigned int hashbit1 = hash & (__ELF_NATIVE_CLASS - 1);
  824. unsigned int hashbit2 = (hash >> map->l_gnu_shift)
  825. & (__ELF_NATIVE_CLASS - 1);
  826. if ((bitmask_word >> hashbit1) & (bitmask_word >> hashbit2) & 1) {
  827. Elf32_Word bucket = map->l_gnu_buckets
  828. [hash % map->l_nbuckets];
  829. if (bucket != 0) {
  830. const Elf32_Word *hasharr = &map->l_gnu_chain_zero[bucket];
  831. do
  832. if (((*hasharr ^ hash) >> 1) == 0) {
  833. symidx = hasharr - map->l_gnu_chain_zero;
  834. sym = check_match (&symtab[symidx], ref, undef_name, strtab);
  835. if (sym != NULL)
  836. return sym;
  837. }
  838. while ((*hasharr++ & 1u) == 0);
  839. }
  840. }
  841. /* No symbol found. */
  842. symidx = SHN_UNDEF;
  843. } else {
  844. /* Use the old SysV-style hash table. Search the appropriate
  845. hash bucket in this object's symbol table for a definition
  846. for the same symbol name. */
  847. for (symidx = map->l_buckets[elf_hash % map->l_nbuckets];
  848. symidx != STN_UNDEF;
  849. symidx = map->l_chain[symidx]) {
  850. sym = check_match (&symtab[symidx], ref, undef_name, strtab);
  851. if (sym != NULL)
  852. return sym;
  853. }
  854. }
  855. return NULL;
  856. }
  857. /* Inner part of the lookup functions. We return a value > 0 if we
  858. found the symbol, the value 0 if nothing is found and < 0 if
  859. something bad happened. */
  860. static int do_lookup (const char * undef_name, ElfW(Sym) * ref,
  861. struct sym_val * result)
  862. {
  863. const uint_fast32_t fast_hash = elf_fast_hash(undef_name);
  864. const long int hash = elf_hash(undef_name);
  865. ElfW(Sym) * sym;
  866. struct link_map * map = loaded_maps;
  867. struct sym_val weak_result = { .s = NULL, .m = NULL };
  868. for (; map ; map = map->l_next) {
  869. sym = do_lookup_map(ref, undef_name, fast_hash, hash, map);
  870. if (!sym)
  871. continue;
  872. switch (ELFW(ST_BIND)(sym->st_info)) {
  873. case STB_WEAK:
  874. /* Weak definition. Use this value if we don't find another. */
  875. if (!weak_result.s) {
  876. weak_result.s = sym;
  877. weak_result.m = (struct link_map *) map;
  878. }
  879. break;
  880. /* FALLTHROUGH */
  881. case STB_GLOBAL:
  882. case STB_GNU_UNIQUE:
  883. /* success: */
  884. /* Global definition. Just what we need. */
  885. result->s = sym;
  886. result->m = (struct link_map *) map;
  887. return 1;
  888. default:
  889. /* Local symbols are ignored. */
  890. break;
  891. }
  892. }
  893. if (weak_result.s) {
  894. *result = weak_result;
  895. return 1;
  896. }
  897. /* We have not found anything until now. */
  898. return 0;
  899. }
  900. /* Search loaded objects' symbol tables for a definition of the symbol
  901. UNDEF_NAME, perhaps with a requested version for the symbol.
  902. We must never have calls to the audit functions inside this function
  903. or in any function which gets called. If this would happen the audit
  904. code might create a thread which can throw off all the scope locking. */
  905. struct link_map * lookup_symbol (const char * undef_name, ElfW(Sym) ** ref)
  906. {
  907. struct sym_val current_value = { NULL, NULL };
  908. do_lookup(undef_name, *ref, &current_value);
  909. if (current_value.s == NULL) {
  910. *ref = NULL;
  911. return NULL;
  912. }
  913. *ref = current_value.s;
  914. return current_value.m;
  915. }
  916. static int protect_relro (struct link_map * l)
  917. {
  918. ElfW(Addr) start = ALLOC_ALIGN_DOWN(l->l_addr + l->l_relro_addr);
  919. ElfW(Addr) end = ALLOC_ALIGN_UP(l->l_addr + l->l_relro_addr +
  920. l->l_relro_size);
  921. if (start != end)
  922. _DkVirtualMemoryProtect((void *) start, end - start, PAL_PROT_READ);
  923. return 0;
  924. }
  925. static int relocate_elf_object (struct link_map * l)
  926. {
  927. struct textrels {
  928. ElfW(Addr) start;
  929. ElfW(Addr) len;
  930. int prot;
  931. struct textrels * next;
  932. } * textrels = NULL;
  933. int ret;
  934. const ElfW(Phdr) * ph;
  935. for (ph = l->l_phdr ; ph < &l->l_phdr[l->l_phnum] ; ph++)
  936. if (ph->p_type == PT_LOAD && (ph->p_flags & PF_W) == 0) {
  937. struct textrels * r = malloc(sizeof(struct textrels));
  938. r->start = ALLOC_ALIGN_DOWN(ph->p_vaddr) + l->l_addr;
  939. r->len = ALLOC_ALIGN_UP(ph->p_vaddr + ph->p_memsz)
  940. - ALLOC_ALIGN_DOWN(ph->p_vaddr);
  941. ret = _DkVirtualMemoryProtect((void *) r->start, r->len,
  942. PAL_PROT_READ|PAL_PROT_WRITE);
  943. if (ret < 0)
  944. return ret;
  945. r->prot = 0;
  946. if (ph->p_flags & PF_R)
  947. r->prot |= PAL_PROT_READ;
  948. if (ph->p_flags & PF_W)
  949. r->prot |= PAL_PROT_WRITE;
  950. if (ph->p_flags & PF_X)
  951. r->prot |= PAL_PROT_EXEC;
  952. r->next = textrels;
  953. textrels = r;
  954. }
  955. #if PROFILING == 1
  956. unsigned long before_relocate = _DkSystemTimeQuery();
  957. #endif
  958. /* Do the actual relocation of the object's GOT and other data. */
  959. ELF_DYNAMIC_RELOCATE(l);
  960. #if PROFILING == 1
  961. pal_state.relocation_time += _DkSystemTimeQuery() - before_relocate;
  962. #endif
  963. while (textrels) {
  964. ret = _DkVirtualMemoryProtect((void *) textrels->start, textrels->len,
  965. textrels->prot);
  966. if (ret < 0)
  967. return ret;
  968. struct textrels * next = textrels->next;
  969. free(textrels);
  970. textrels = next;
  971. }
  972. /* In case we can protect the data now that the relocations are
  973. done, do it. */
  974. if (l->l_type != OBJECT_EXEC && l->l_relro_size != 0)
  975. if ((ret = protect_relro(l)) < 0)
  976. return ret;
  977. return 0;
  978. }
  979. void DkDebugAttachBinary (PAL_STR uri, PAL_PTR start_addr)
  980. {
  981. #ifndef DEBUG
  982. __UNUSED(uri);
  983. __UNUSED(start_addr);
  984. #else
  985. if (!strstartswith_static(uri, URI_PREFIX_FILE))
  986. return;
  987. const char * realname = uri + URI_PREFIX_FILE_LEN;
  988. struct link_map * l = new_elf_object(realname, OBJECT_EXTERNAL);
  989. /* This is the ELF header. We read it in `open_verify'. */
  990. const ElfW(Ehdr) * header = (ElfW(Ehdr) *) start_addr;
  991. l->l_entry = header->e_entry;
  992. l->l_phnum = header->e_phnum;
  993. l->l_map_start = (ElfW(Addr)) start_addr;
  994. ElfW(Phdr) * phdr = (void *) ((char *) start_addr + header->e_phoff);
  995. const ElfW(Phdr) * ph;
  996. ElfW(Addr) map_start = 0, map_end = 0;
  997. for (ph = phdr; ph < &phdr[l->l_phnum]; ++ph)
  998. if (ph->p_type == PT_PHDR) {
  999. if (!map_start || ph->p_vaddr < map_start)
  1000. map_start = ph->p_vaddr;
  1001. if (!map_end || ph->p_vaddr + ph->p_memsz > map_end)
  1002. map_end = ph->p_vaddr + ph->p_memsz;
  1003. }
  1004. l->l_addr = l->l_map_start - map_start;
  1005. l->l_map_end = l->l_addr + map_end;
  1006. for (ph = phdr; ph < &phdr[l->l_phnum]; ++ph)
  1007. switch (ph->p_type) {
  1008. /* These entries tell us where to find things once the file's
  1009. segments are mapped in. We record the addresses it says
  1010. verbatim, and later correct for the run-time load address. */
  1011. case PT_DYNAMIC:
  1012. l->l_ld = l->l_real_ld = (ElfW(Dyn) *)
  1013. ((char *) l->l_addr + ph->p_vaddr);
  1014. l->l_ldnum = ph->p_memsz / sizeof (ElfW(Dyn));
  1015. break;
  1016. case PT_PHDR:
  1017. l->l_phdr = (ElfW(Phdr) *) ((char *) l->l_addr + ph->p_vaddr);
  1018. break;
  1019. case PT_GNU_RELRO:
  1020. l->l_relro_addr = l->l_addr + ph->p_vaddr;
  1021. l->l_relro_size = ph->p_memsz;
  1022. break;
  1023. }
  1024. _DkDebugAddMap(l);
  1025. free(l);
  1026. #endif
  1027. }
  1028. void DkDebugDetachBinary (PAL_PTR start_addr)
  1029. {
  1030. #ifndef DEBUG
  1031. __UNUSED(start_addr);
  1032. #else
  1033. for (struct link_map * l = loaded_maps; l; l = l->l_next)
  1034. if (l->l_map_start == (ElfW(Addr)) start_addr) {
  1035. _DkDebugDelMap(l);
  1036. if (l->l_type == OBJECT_EXTERNAL)
  1037. free_elf_object(l);
  1038. break;
  1039. }
  1040. #endif
  1041. }
  1042. #ifndef CALL_ENTRY
  1043. #ifdef __x86_64__
  1044. void * stack_before_call __attribute_unused = NULL;
  1045. #define CALL_ENTRY(l, cookies) \
  1046. ({ long ret; \
  1047. __asm__ volatile( \
  1048. "pushq $0\r\n" \
  1049. "popfq\r\n" \
  1050. "movq %%rsp, stack_before_call(%%rip)\r\n" \
  1051. "leaq 1f(%%rip), %%rdx\r\n" \
  1052. "movq %2, %%rsp\r\n" \
  1053. "jmp *%1\r\n" \
  1054. "1: movq stack_before_call(%%rip), %%rsp\r\n" \
  1055. \
  1056. : "=a"(ret) : "a"((l)->l_entry), "b"(cookies) \
  1057. : "rcx", "rdx", "rdi", "rsi", "r8", "r9", \
  1058. "r10", "r11", "memory", "cc"); \
  1059. ret; })
  1060. #else
  1061. # error "unsupported architecture"
  1062. #endif
  1063. #endif /* !CALL_ENTRY */
  1064. noreturn void start_execution(const char** arguments, const char** environs) {
  1065. /* First we will try to run all the preloaded libraries which come with
  1066. entry points */
  1067. if (exec_map) {
  1068. __pal_control.executable_range.start = (PAL_PTR) exec_map->l_map_start;
  1069. __pal_control.executable_range.end = (PAL_PTR) exec_map->l_map_end;
  1070. }
  1071. #if PROFILING == 1
  1072. unsigned long before_tail = _DkSystemTimeQuery();
  1073. #endif
  1074. int narguments = 0;
  1075. for (const char** a = arguments; *a ; a++, narguments++);
  1076. /* Let's count the number of cookies, first we will have argc & argv */
  1077. int ncookies = narguments + 3; /* 1 for argc, argc + 2 for argv */
  1078. /* Then we count envp */
  1079. for (const char** e = environs; *e; e++)
  1080. ncookies++;
  1081. ncookies++; /* for NULL-end */
  1082. int cookiesz = sizeof(unsigned long int) * ncookies
  1083. + sizeof(ElfW(auxv_t)) * 1 /* only AT_NULL */
  1084. + sizeof(void *) * 4 + 16;
  1085. unsigned long int* cookies = __alloca(cookiesz);
  1086. int cnt = 0;
  1087. /* Let's copy the cookies */
  1088. cookies[cnt++] = (unsigned long int) narguments;
  1089. for (int i = 0 ; arguments[i] ; i++)
  1090. cookies[cnt++] = (unsigned long int) arguments[i];
  1091. cookies[cnt++] = 0;
  1092. for (int i = 0 ; environs[i]; i++)
  1093. cookies[cnt++] = (unsigned long int) environs[i];
  1094. cookies[cnt++] = 0;
  1095. /* NOTE: LibOS implements its own ELF aux vectors. Any info from host's
  1096. * aux vectors must be passed in PAL_CONTROL. Here we pass an empty list
  1097. * of aux vectors for sanity. */
  1098. ElfW(auxv_t) * auxv = (ElfW(auxv_t) *) &cookies[cnt];
  1099. auxv[0].a_type = AT_NULL;
  1100. auxv[0].a_un.a_val = 0;
  1101. #if PROFILING == 1
  1102. __pal_control.startup_time = _DkSystemTimeQuery() - pal_state.start_time;
  1103. __pal_control.tail_startup_time =
  1104. pal_state.tail_startup_time += _DkSystemTimeQuery() - before_tail;
  1105. #endif
  1106. for (struct link_map * l = loaded_maps; l ; l = l->l_next)
  1107. if (l->l_type == OBJECT_PRELOAD && l->l_entry)
  1108. CALL_ENTRY(l, cookies);
  1109. if (exec_map)
  1110. CALL_ENTRY(exec_map, cookies);
  1111. _DkThreadExit(/*clear_child_tid=*/NULL);
  1112. }