db_rtld.c 43 KB

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