dynlink.c 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153
  1. #define _GNU_SOURCE
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <unistd.h>
  6. #include <stdint.h>
  7. #include <elf.h>
  8. #include <sys/mman.h>
  9. #include <limits.h>
  10. #include <stdint.h>
  11. #include <fcntl.h>
  12. #include <sys/stat.h>
  13. #include <errno.h>
  14. #include <limits.h>
  15. #include <elf.h>
  16. #include <setjmp.h>
  17. #include <pthread.h>
  18. #include <ctype.h>
  19. #include <dlfcn.h>
  20. #include "pthread_impl.h"
  21. #include "libc.h"
  22. #undef libc
  23. static int errflag;
  24. static char errbuf[128];
  25. #ifdef SHARED
  26. #if ULONG_MAX == 0xffffffff
  27. typedef Elf32_Ehdr Ehdr;
  28. typedef Elf32_Phdr Phdr;
  29. typedef Elf32_Sym Sym;
  30. #define R_TYPE(x) ((x)&255)
  31. #define R_SYM(x) ((x)>>8)
  32. #else
  33. typedef Elf64_Ehdr Ehdr;
  34. typedef Elf64_Phdr Phdr;
  35. typedef Elf64_Sym Sym;
  36. #define R_TYPE(x) ((x)&0xffffffff)
  37. #define R_SYM(x) ((x)>>32)
  38. #endif
  39. struct debug {
  40. int ver;
  41. void *head;
  42. void (*bp)(void);
  43. int state;
  44. void *base;
  45. };
  46. struct dso {
  47. unsigned char *base;
  48. char *name;
  49. size_t *dynv;
  50. struct dso *next, *prev;
  51. int refcnt;
  52. Sym *syms;
  53. uint32_t *hashtab;
  54. uint32_t *ghashtab;
  55. char *strings;
  56. unsigned char *map;
  57. size_t map_len;
  58. dev_t dev;
  59. ino_t ino;
  60. signed char global;
  61. char relocated;
  62. char constructed;
  63. struct dso **deps;
  64. void *tls_image;
  65. size_t tls_len, tls_size, tls_align, tls_id, tls_offset;
  66. void **new_dtv;
  67. unsigned char *new_tls;
  68. int new_dtv_idx, new_tls_idx;
  69. char *shortname;
  70. char buf[];
  71. };
  72. struct symdef {
  73. Sym *sym;
  74. struct dso *dso;
  75. };
  76. #include "reloc.h"
  77. void __init_ssp(size_t *);
  78. void *__install_initial_tls(void *);
  79. static struct dso *head, *tail, *libc;
  80. static char *env_path, *sys_path, *r_path;
  81. static int ssp_used;
  82. static int runtime;
  83. static int ldd_mode;
  84. static int ldso_fail;
  85. static jmp_buf rtld_fail;
  86. static pthread_rwlock_t lock;
  87. static struct debug debug;
  88. static size_t *auxv;
  89. static size_t tls_cnt, tls_size;
  90. struct debug *_dl_debug_addr = &debug;
  91. #define AUX_CNT 24
  92. #define DYN_CNT 34
  93. static void decode_vec(size_t *v, size_t *a, size_t cnt)
  94. {
  95. memset(a, 0, cnt*sizeof(size_t));
  96. for (; v[0]; v+=2) if (v[0]<cnt) {
  97. a[0] |= 1ULL<<v[0];
  98. a[v[0]] = v[1];
  99. }
  100. }
  101. static int search_vec(size_t *v, size_t *r, size_t key)
  102. {
  103. for (; v[0]!=key; v+=2)
  104. if (!v[0]) return 0;
  105. *r = v[1];
  106. return 1;
  107. }
  108. static uint32_t sysv_hash(const char *s0)
  109. {
  110. const unsigned char *s = (void *)s0;
  111. uint_fast32_t h = 0;
  112. while (*s) {
  113. h = 16*h + *s++;
  114. h ^= h>>24 & 0xf0;
  115. }
  116. return h & 0xfffffff;
  117. }
  118. static uint32_t gnu_hash(const char *s0)
  119. {
  120. const unsigned char *s = (void *)s0;
  121. uint_fast32_t h = 5381;
  122. for (; *s; s++)
  123. h = h*33 + *s;
  124. return h;
  125. }
  126. static Sym *sysv_lookup(const char *s, uint32_t h, struct dso *dso)
  127. {
  128. size_t i;
  129. Sym *syms = dso->syms;
  130. uint32_t *hashtab = dso->hashtab;
  131. char *strings = dso->strings;
  132. for (i=hashtab[2+h%hashtab[0]]; i; i=hashtab[2+hashtab[0]+i]) {
  133. if (!strcmp(s, strings+syms[i].st_name))
  134. return syms+i;
  135. }
  136. return 0;
  137. }
  138. static Sym *gnu_lookup(const char *s, uint32_t h1, struct dso *dso)
  139. {
  140. Sym *sym;
  141. char *strings;
  142. uint32_t *hashtab = dso->ghashtab;
  143. uint32_t nbuckets = hashtab[0];
  144. uint32_t *buckets = hashtab + 4 + hashtab[2]*(sizeof(size_t)/4);
  145. uint32_t h2;
  146. uint32_t *hashval;
  147. uint32_t n = buckets[h1 % nbuckets];
  148. if (!n) return 0;
  149. strings = dso->strings;
  150. sym = dso->syms + n;
  151. hashval = buckets + nbuckets + (n - hashtab[1]);
  152. for (h1 |= 1; ; sym++) {
  153. h2 = *hashval++;
  154. if ((h1 == (h2|1)) && !strcmp(s, strings + sym->st_name))
  155. return sym;
  156. if (h2 & 1) break;
  157. }
  158. return 0;
  159. }
  160. #define OK_TYPES (1<<STT_NOTYPE | 1<<STT_OBJECT | 1<<STT_FUNC | 1<<STT_COMMON | 1<<STT_TLS)
  161. #define OK_BINDS (1<<STB_GLOBAL | 1<<STB_WEAK)
  162. static struct symdef find_sym(struct dso *dso, const char *s, int need_def)
  163. {
  164. uint32_t h = 0, gh = 0;
  165. struct symdef def = {0};
  166. if (dso->ghashtab) {
  167. gh = gnu_hash(s);
  168. if (gh == 0x1f4039c9 && !strcmp(s, "__stack_chk_fail")) ssp_used = 1;
  169. } else {
  170. h = sysv_hash(s);
  171. if (h == 0x595a4cc && !strcmp(s, "__stack_chk_fail")) ssp_used = 1;
  172. }
  173. for (; dso; dso=dso->next) {
  174. Sym *sym;
  175. if (!dso->global) continue;
  176. if (dso->ghashtab) {
  177. if (!gh) gh = gnu_hash(s);
  178. sym = gnu_lookup(s, gh, dso);
  179. } else {
  180. if (!h) h = sysv_hash(s);
  181. sym = sysv_lookup(s, h, dso);
  182. }
  183. if (sym && (!need_def || sym->st_shndx) && sym->st_value
  184. && (1<<(sym->st_info&0xf) & OK_TYPES)
  185. && (1<<(sym->st_info>>4) & OK_BINDS)) {
  186. if (def.sym && sym->st_info>>4 == STB_WEAK) continue;
  187. def.sym = sym;
  188. def.dso = dso;
  189. if (sym->st_info>>4 == STB_GLOBAL) break;
  190. }
  191. }
  192. return def;
  193. }
  194. static void do_relocs(struct dso *dso, size_t *rel, size_t rel_size, size_t stride)
  195. {
  196. unsigned char *base = dso->base;
  197. Sym *syms = dso->syms;
  198. char *strings = dso->strings;
  199. Sym *sym;
  200. const char *name;
  201. void *ctx;
  202. int type;
  203. int sym_index;
  204. struct symdef def;
  205. for (; rel_size; rel+=stride, rel_size-=stride*sizeof(size_t)) {
  206. type = R_TYPE(rel[1]);
  207. sym_index = R_SYM(rel[1]);
  208. if (sym_index) {
  209. sym = syms + sym_index;
  210. name = strings + sym->st_name;
  211. ctx = IS_COPY(type) ? head->next : head;
  212. def = find_sym(ctx, name, IS_PLT(type));
  213. if (!def.sym && sym->st_info>>4 != STB_WEAK) {
  214. snprintf(errbuf, sizeof errbuf,
  215. "Error relocating %s: %s: symbol not found",
  216. dso->name, name);
  217. if (runtime) longjmp(rtld_fail, 1);
  218. dprintf(2, "%s\n", errbuf);
  219. ldso_fail = 1;
  220. continue;
  221. }
  222. } else {
  223. sym = 0;
  224. def.sym = 0;
  225. def.dso = 0;
  226. }
  227. do_single_reloc(dso, base, (void *)(base + rel[0]), type,
  228. stride>2 ? rel[2] : 0, sym, sym?sym->st_size:0, def,
  229. def.sym?(size_t)(def.dso->base+def.sym->st_value):0);
  230. }
  231. }
  232. /* A huge hack: to make up for the wastefulness of shared libraries
  233. * needing at least a page of dirty memory even if they have no global
  234. * data, we reclaim the gaps at the beginning and end of writable maps
  235. * and "donate" them to the heap by setting up minimal malloc
  236. * structures and then freeing them. */
  237. static void reclaim(unsigned char *base, size_t start, size_t end)
  238. {
  239. size_t *a, *z;
  240. start = start + 6*sizeof(size_t)-1 & -4*sizeof(size_t);
  241. end = (end & -4*sizeof(size_t)) - 2*sizeof(size_t);
  242. if (start>end || end-start < 4*sizeof(size_t)) return;
  243. a = (size_t *)(base + start);
  244. z = (size_t *)(base + end);
  245. a[-2] = 1;
  246. a[-1] = z[0] = end-start + 2*sizeof(size_t) | 1;
  247. z[1] = 1;
  248. free(a);
  249. }
  250. static void reclaim_gaps(unsigned char *base, Phdr *ph, size_t phent, size_t phcnt)
  251. {
  252. for (; phcnt--; ph=(void *)((char *)ph+phent)) {
  253. if (ph->p_type!=PT_LOAD) continue;
  254. if ((ph->p_flags&(PF_R|PF_W))!=(PF_R|PF_W)) continue;
  255. reclaim(base, ph->p_vaddr & -PAGE_SIZE, ph->p_vaddr);
  256. reclaim(base, ph->p_vaddr+ph->p_memsz,
  257. ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE);
  258. }
  259. }
  260. static void *map_library(int fd, struct dso *dso)
  261. {
  262. Ehdr buf[(896+sizeof(Ehdr))/sizeof(Ehdr)];
  263. size_t phsize;
  264. size_t addr_min=SIZE_MAX, addr_max=0, map_len;
  265. size_t this_min, this_max;
  266. off_t off_start;
  267. Ehdr *eh;
  268. Phdr *ph;
  269. unsigned prot;
  270. unsigned char *map, *base;
  271. size_t dyn;
  272. size_t tls_image=0;
  273. size_t i;
  274. ssize_t l = read(fd, buf, sizeof buf);
  275. if (l<sizeof *eh) return 0;
  276. eh = buf;
  277. phsize = eh->e_phentsize * eh->e_phnum;
  278. if (phsize + sizeof *eh > l) return 0;
  279. if (eh->e_phoff + phsize > l) {
  280. l = pread(fd, buf+1, phsize, eh->e_phoff);
  281. if (l != phsize) return 0;
  282. eh->e_phoff = sizeof *eh;
  283. }
  284. ph = (void *)((char *)buf + eh->e_phoff);
  285. for (i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
  286. if (ph->p_type == PT_DYNAMIC)
  287. dyn = ph->p_vaddr;
  288. if (ph->p_type == PT_TLS) {
  289. tls_image = ph->p_vaddr;
  290. dso->tls_align = ph->p_align;
  291. dso->tls_len = ph->p_filesz;
  292. dso->tls_size = ph->p_memsz;
  293. }
  294. if (ph->p_type != PT_LOAD) continue;
  295. if (ph->p_vaddr < addr_min) {
  296. addr_min = ph->p_vaddr;
  297. off_start = ph->p_offset;
  298. prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
  299. ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
  300. ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
  301. }
  302. if (ph->p_vaddr+ph->p_memsz > addr_max) {
  303. addr_max = ph->p_vaddr+ph->p_memsz;
  304. }
  305. }
  306. if (!dyn) return 0;
  307. addr_max += PAGE_SIZE-1;
  308. addr_max &= -PAGE_SIZE;
  309. addr_min &= -PAGE_SIZE;
  310. off_start &= -PAGE_SIZE;
  311. map_len = addr_max - addr_min + off_start;
  312. /* The first time, we map too much, possibly even more than
  313. * the length of the file. This is okay because we will not
  314. * use the invalid part; we just need to reserve the right
  315. * amount of virtual address space to map over later. */
  316. map = mmap((void *)addr_min, map_len, prot, MAP_PRIVATE, fd, off_start);
  317. if (map==MAP_FAILED) return 0;
  318. base = map - addr_min;
  319. ph = (void *)((char *)buf + eh->e_phoff);
  320. for (i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
  321. if (ph->p_type != PT_LOAD) continue;
  322. /* Reuse the existing mapping for the lowest-address LOAD */
  323. if ((ph->p_vaddr & -PAGE_SIZE) == addr_min) continue;
  324. this_min = ph->p_vaddr & -PAGE_SIZE;
  325. this_max = ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE;
  326. off_start = ph->p_offset & -PAGE_SIZE;
  327. prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
  328. ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
  329. ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
  330. if (mmap(base+this_min, this_max-this_min, prot, MAP_PRIVATE|MAP_FIXED, fd, off_start) == MAP_FAILED)
  331. goto error;
  332. if (ph->p_memsz > ph->p_filesz) {
  333. size_t brk = (size_t)base+ph->p_vaddr+ph->p_filesz;
  334. size_t pgbrk = brk+PAGE_SIZE-1 & -PAGE_SIZE;
  335. memset((void *)brk, 0, pgbrk-brk & PAGE_SIZE-1);
  336. if (pgbrk-(size_t)base < this_max && mmap((void *)pgbrk, (size_t)base+this_max-pgbrk, prot, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) == MAP_FAILED)
  337. goto error;
  338. }
  339. }
  340. for (i=0; ((size_t *)(base+dyn))[i]; i+=2)
  341. if (((size_t *)(base+dyn))[i]==DT_TEXTREL) {
  342. if (mprotect(map, map_len, PROT_READ|PROT_WRITE|PROT_EXEC) < 0)
  343. goto error;
  344. break;
  345. }
  346. if (!runtime) reclaim_gaps(base, (void *)((char *)buf + eh->e_phoff),
  347. eh->e_phentsize, eh->e_phnum);
  348. dso->map = map;
  349. dso->map_len = map_len;
  350. dso->base = base;
  351. dso->dynv = (void *)(base+dyn);
  352. if (dso->tls_size) dso->tls_image = (void *)(base+tls_image);
  353. return map;
  354. error:
  355. munmap(map, map_len);
  356. return 0;
  357. }
  358. static int path_open(const char *name, const char *search, char *buf, size_t buf_size)
  359. {
  360. const char *s=search, *z;
  361. int l, fd;
  362. for (;;) {
  363. while (*s==':') s++;
  364. if (!*s) return -1;
  365. z = strchr(s, ':');
  366. l = z ? z-s : strlen(s);
  367. snprintf(buf, buf_size, "%.*s/%s", l, s, name);
  368. if ((fd = open(buf, O_RDONLY|O_CLOEXEC))>=0) return fd;
  369. s += l;
  370. }
  371. }
  372. static void decode_dyn(struct dso *p)
  373. {
  374. size_t dyn[DYN_CNT] = {0};
  375. decode_vec(p->dynv, dyn, DYN_CNT);
  376. p->syms = (void *)(p->base + dyn[DT_SYMTAB]);
  377. p->strings = (void *)(p->base + dyn[DT_STRTAB]);
  378. if (dyn[0]&(1<<DT_HASH))
  379. p->hashtab = (void *)(p->base + dyn[DT_HASH]);
  380. if (search_vec(p->dynv, dyn, DT_GNU_HASH))
  381. p->ghashtab = (void *)(p->base + *dyn);
  382. }
  383. static struct dso *load_library(const char *name)
  384. {
  385. char buf[2*NAME_MAX+2];
  386. const char *pathname;
  387. unsigned char *base, *map;
  388. size_t dyno, map_len;
  389. struct dso *p, temp_dso = {0};
  390. int fd;
  391. struct stat st;
  392. size_t alloc_size;
  393. int n_th = 0;
  394. /* Catch and block attempts to reload the implementation itself */
  395. if (name[0]=='l' && name[1]=='i' && name[2]=='b') {
  396. static const char *rp, reserved[] =
  397. "c\0pthread\0rt\0m\0dl\0util\0xnet\0";
  398. char *z = strchr(name, '.');
  399. if (z) {
  400. size_t l = z-name;
  401. for (rp=reserved; *rp && memcmp(name+3, rp, l-3); rp+=strlen(rp)+1);
  402. if (*rp) {
  403. if (!libc->prev) {
  404. tail->next = libc;
  405. libc->prev = tail;
  406. tail = libc->next ? libc->next : libc;
  407. }
  408. return libc;
  409. }
  410. }
  411. }
  412. if (strchr(name, '/')) {
  413. pathname = name;
  414. fd = open(name, O_RDONLY|O_CLOEXEC);
  415. } else {
  416. /* Search for the name to see if it's already loaded */
  417. for (p=head->next; p; p=p->next) {
  418. if (p->shortname && !strcmp(p->shortname, name)) {
  419. p->refcnt++;
  420. return p;
  421. }
  422. }
  423. if (strlen(name) > NAME_MAX) return 0;
  424. fd = -1;
  425. if (r_path) fd = path_open(name, r_path, buf, sizeof buf);
  426. if (fd < 0 && env_path) fd = path_open(name, env_path, buf, sizeof buf);
  427. if (fd < 0) {
  428. if (!sys_path) {
  429. FILE *f = fopen(ETC_LDSO_PATH, "rbe");
  430. if (f) {
  431. if (getline(&sys_path, (size_t[1]){0}, f) > 0)
  432. sys_path[strlen(sys_path)-1]=0;
  433. fclose(f);
  434. }
  435. }
  436. if (sys_path) fd = path_open(name, sys_path, buf, sizeof buf);
  437. else fd = path_open(name, "/lib:/usr/local/lib:/usr/lib", buf, sizeof buf);
  438. }
  439. pathname = buf;
  440. }
  441. if (fd < 0) return 0;
  442. if (fstat(fd, &st) < 0) {
  443. close(fd);
  444. return 0;
  445. }
  446. for (p=head->next; p; p=p->next) {
  447. if (p->dev == st.st_dev && p->ino == st.st_ino) {
  448. /* If this library was previously loaded with a
  449. * pathname but a search found the same inode,
  450. * setup its shortname so it can be found by name. */
  451. if (!p->shortname && pathname != name)
  452. p->shortname = strrchr(p->name, '/')+1;
  453. close(fd);
  454. p->refcnt++;
  455. return p;
  456. }
  457. }
  458. map = map_library(fd, &temp_dso);
  459. close(fd);
  460. if (!map) return 0;
  461. /* Allocate storage for the new DSO. When there is TLS, this
  462. * storage must include a reservation for all pre-existing
  463. * threads to obtain copies of both the new TLS, and an
  464. * extended DTV capable of storing an additional slot for
  465. * the newly-loaded DSO. */
  466. alloc_size = sizeof *p + strlen(pathname) + 1;
  467. if (runtime && temp_dso.tls_image) {
  468. size_t per_th = temp_dso.tls_size + temp_dso.tls_align
  469. + sizeof(void *) * (tls_cnt+3);
  470. n_th = __libc.threads_minus_1 + 1;
  471. if (n_th > SSIZE_MAX / per_th) alloc_size = SIZE_MAX;
  472. else alloc_size += n_th * per_th;
  473. }
  474. p = calloc(1, alloc_size);
  475. if (!p) {
  476. munmap(map, map_len);
  477. return 0;
  478. }
  479. memcpy(p, &temp_dso, sizeof temp_dso);
  480. decode_dyn(p);
  481. p->dev = st.st_dev;
  482. p->ino = st.st_ino;
  483. p->refcnt = 1;
  484. p->name = p->buf;
  485. strcpy(p->name, pathname);
  486. /* Add a shortname only if name arg was not an explicit pathname. */
  487. if (pathname != name) p->shortname = strrchr(p->name, '/')+1;
  488. if (p->tls_image) {
  489. p->tls_id = ++tls_cnt;
  490. tls_size += p->tls_size + p->tls_align + 8*sizeof(size_t) - 1
  491. & -4*sizeof(size_t);
  492. p->new_dtv = (void *)(-sizeof(size_t) &
  493. (uintptr_t)(p->name+strlen(p->name)+sizeof(size_t)));
  494. p->new_tls = (void *)(p->new_dtv + n_th*(tls_cnt+1));
  495. }
  496. tail->next = p;
  497. p->prev = tail;
  498. tail = p;
  499. if (ldd_mode) dprintf(1, "\t%s => %s (%p)\n", name, pathname, base);
  500. return p;
  501. }
  502. static void load_deps(struct dso *p)
  503. {
  504. size_t i, ndeps=0;
  505. struct dso ***deps = &p->deps, **tmp, *dep;
  506. for (; p; p=p->next) {
  507. for (i=0; p->dynv[i]; i+=2) {
  508. if (p->dynv[i] != DT_RPATH) continue;
  509. r_path = (void *)(p->strings + p->dynv[i+1]);
  510. }
  511. for (i=0; p->dynv[i]; i+=2) {
  512. if (p->dynv[i] != DT_NEEDED) continue;
  513. dep = load_library(p->strings + p->dynv[i+1]);
  514. if (!dep) {
  515. snprintf(errbuf, sizeof errbuf,
  516. "Error loading shared library %s: %m (needed by %s)",
  517. p->strings + p->dynv[i+1], p->name);
  518. if (runtime) longjmp(rtld_fail, 1);
  519. dprintf(2, "%s\n", errbuf);
  520. ldso_fail = 1;
  521. continue;
  522. }
  523. if (runtime) {
  524. tmp = realloc(*deps, sizeof(*tmp)*(ndeps+2));
  525. if (!tmp) longjmp(rtld_fail, 1);
  526. tmp[ndeps++] = dep;
  527. tmp[ndeps] = 0;
  528. *deps = tmp;
  529. }
  530. }
  531. r_path = 0;
  532. }
  533. }
  534. static void load_preload(char *s)
  535. {
  536. int tmp;
  537. char *z;
  538. for (z=s; *z; s=z) {
  539. for ( ; *s && isspace(*s); s++);
  540. for (z=s; *z && !isspace(*z); z++);
  541. tmp = *z;
  542. *z = 0;
  543. load_library(s);
  544. *z = tmp;
  545. }
  546. }
  547. static void make_global(struct dso *p)
  548. {
  549. for (; p; p=p->next) p->global = 1;
  550. }
  551. static void reloc_all(struct dso *p)
  552. {
  553. size_t dyn[DYN_CNT] = {0};
  554. for (; p; p=p->next) {
  555. if (p->relocated) continue;
  556. decode_vec(p->dynv, dyn, DYN_CNT);
  557. #ifdef NEED_ARCH_RELOCS
  558. do_arch_relocs(p, head);
  559. #endif
  560. do_relocs(p, (void *)(p->base+dyn[DT_JMPREL]), dyn[DT_PLTRELSZ],
  561. 2+(dyn[DT_PLTREL]==DT_RELA));
  562. do_relocs(p, (void *)(p->base+dyn[DT_REL]), dyn[DT_RELSZ], 2);
  563. do_relocs(p, (void *)(p->base+dyn[DT_RELA]), dyn[DT_RELASZ], 3);
  564. p->relocated = 1;
  565. }
  566. }
  567. static void free_all(struct dso *p)
  568. {
  569. struct dso *n;
  570. while (p) {
  571. n = p->next;
  572. if (p->map && p!=libc && p!=head) free(p);
  573. p = n;
  574. }
  575. }
  576. static size_t find_dyn(Phdr *ph, size_t cnt, size_t stride)
  577. {
  578. for (; cnt--; ph = (void *)((char *)ph + stride))
  579. if (ph->p_type == PT_DYNAMIC)
  580. return ph->p_vaddr;
  581. return 0;
  582. }
  583. static void find_map_range(Phdr *ph, size_t cnt, size_t stride, struct dso *p)
  584. {
  585. size_t min_addr = -1, max_addr = 0;
  586. for (; cnt--; ph = (void *)((char *)ph + stride)) {
  587. if (ph->p_type != PT_LOAD) continue;
  588. if (ph->p_vaddr < min_addr)
  589. min_addr = ph->p_vaddr;
  590. if (ph->p_vaddr+ph->p_memsz > max_addr)
  591. max_addr = ph->p_vaddr+ph->p_memsz;
  592. }
  593. min_addr &= -PAGE_SIZE;
  594. max_addr = (max_addr + PAGE_SIZE-1) & -PAGE_SIZE;
  595. p->map = p->base + min_addr;
  596. p->map_len = max_addr - min_addr;
  597. }
  598. static void do_init_fini(struct dso *p)
  599. {
  600. size_t dyn[DYN_CNT] = {0};
  601. for (; p; p=p->prev) {
  602. if (p->constructed) return;
  603. decode_vec(p->dynv, dyn, DYN_CNT);
  604. if (dyn[0] & (1<<DT_FINI))
  605. atexit((void (*)(void))(p->base + dyn[DT_FINI]));
  606. if (dyn[0] & (1<<DT_INIT))
  607. ((void (*)(void))(p->base + dyn[DT_INIT]))();
  608. p->constructed = 1;
  609. }
  610. }
  611. void _dl_debug_state(void)
  612. {
  613. }
  614. void *__copy_tls(unsigned char *mem)
  615. {
  616. struct dso *p;
  617. void **dtv = (void *)mem;
  618. dtv[0] = (void *)tls_cnt;
  619. mem = (void *)(dtv + tls_cnt + 1);
  620. for (p=tail; p; p=p->prev) {
  621. if (!p->tls_id) continue;
  622. mem += -p->tls_len & (4*sizeof(size_t)-1);
  623. mem += ((uintptr_t)p->tls_image - (uintptr_t)mem)
  624. & (p->tls_align-1);
  625. dtv[p->tls_id] = mem;
  626. memcpy(mem, p->tls_image, p->tls_len);
  627. mem += p->tls_size;
  628. }
  629. ((pthread_t)mem)->dtv = dtv;
  630. return mem;
  631. }
  632. void *__tls_get_addr(size_t *v)
  633. {
  634. pthread_t self = __pthread_self();
  635. if (self->dtv && v[0]<=(size_t)self->dtv[0] && self->dtv[v[0]])
  636. return (char *)self->dtv[v[0]]+v[1];
  637. /* Block signals to make accessing new TLS async-signal-safe */
  638. sigset_t set;
  639. sigfillset(&set);
  640. pthread_sigmask(SIG_BLOCK, &set, &set);
  641. if (self->dtv && v[0]<=(size_t)self->dtv[0] && self->dtv[v[0]]) {
  642. pthread_sigmask(SIG_SETMASK, &set, 0);
  643. return (char *)self->dtv[v[0]]+v[1];
  644. }
  645. /* This is safe without any locks held because, if the caller
  646. * is able to request the Nth entry of the DTV, the DSO list
  647. * must be valid at least that far out and it was synchronized
  648. * at program startup or by an already-completed call to dlopen. */
  649. struct dso *p;
  650. for (p=head; p->tls_id != v[0]; p=p->next);
  651. /* Get new DTV space from new DSO if needed */
  652. if (!self->dtv || v[0] > (size_t)self->dtv[0]) {
  653. void **newdtv = p->new_dtv +
  654. (v[0]+1)*sizeof(void *)*a_fetch_add(&p->new_dtv_idx,1);
  655. if (self->dtv) memcpy(newdtv, self->dtv,
  656. ((size_t)self->dtv[0]+1) * sizeof(void *));
  657. newdtv[0] = (void *)v[0];
  658. self->dtv = newdtv;
  659. }
  660. /* Get new TLS memory from new DSO */
  661. unsigned char *mem = p->new_tls +
  662. (p->tls_size + p->tls_align) * a_fetch_add(&p->new_tls_idx,1);
  663. mem += ((uintptr_t)p->tls_image - (uintptr_t)mem) & (p->tls_align-1);
  664. self->dtv[v[0]] = mem;
  665. memcpy(mem, p->tls_image, p->tls_size);
  666. pthread_sigmask(SIG_SETMASK, &set, 0);
  667. return mem + v[1];
  668. }
  669. void *__dynlink(int argc, char **argv)
  670. {
  671. size_t aux[AUX_CNT] = {0};
  672. size_t i;
  673. Phdr *phdr;
  674. Ehdr *ehdr;
  675. static struct dso builtin_dsos[3];
  676. struct dso *const app = builtin_dsos+0;
  677. struct dso *const lib = builtin_dsos+1;
  678. struct dso *const vdso = builtin_dsos+2;
  679. char *env_preload=0;
  680. size_t vdso_base;
  681. /* Find aux vector just past environ[] */
  682. for (i=argc+1; argv[i]; i++)
  683. if (!memcmp(argv[i], "LD_LIBRARY_PATH=", 16))
  684. env_path = argv[i]+16;
  685. else if (!memcmp(argv[i], "LD_PRELOAD=", 11))
  686. env_preload = argv[i]+11;
  687. auxv = (void *)(argv+i+1);
  688. decode_vec(auxv, aux, AUX_CNT);
  689. /* Only trust user/env if kernel says we're not suid/sgid */
  690. if ((aux[0]&0x7800)!=0x7800 || aux[AT_UID]!=aux[AT_EUID]
  691. || aux[AT_GID]!=aux[AT_EGID] || aux[AT_SECURE]) {
  692. env_path = 0;
  693. env_preload = 0;
  694. }
  695. /* If the dynamic linker was invoked as a program itself, AT_BASE
  696. * will not be set. In that case, we assume the base address is
  697. * the start of the page containing the PHDRs; I don't know any
  698. * better approach... */
  699. if (!aux[AT_BASE]) {
  700. aux[AT_BASE] = aux[AT_PHDR] & -PAGE_SIZE;
  701. aux[AT_PHDR] = aux[AT_PHENT] = aux[AT_PHNUM] = 0;
  702. }
  703. /* The dynamic linker load address is passed by the kernel
  704. * in the AUX vector, so this is easy. */
  705. lib->base = (void *)aux[AT_BASE];
  706. lib->name = lib->shortname = "libc.so";
  707. lib->global = 1;
  708. ehdr = (void *)lib->base;
  709. find_map_range((void *)(aux[AT_BASE]+ehdr->e_phoff),
  710. ehdr->e_phnum, ehdr->e_phentsize, lib);
  711. lib->dynv = (void *)(lib->base + find_dyn(
  712. (void *)(aux[AT_BASE]+ehdr->e_phoff),
  713. ehdr->e_phnum, ehdr->e_phentsize));
  714. decode_dyn(lib);
  715. if (aux[AT_PHDR]) {
  716. size_t interp_off = 0;
  717. size_t tls_image = 0;
  718. /* Find load address of the main program, via AT_PHDR vs PT_PHDR. */
  719. phdr = (void *)aux[AT_PHDR];
  720. for (i=aux[AT_PHNUM]; i; i--, phdr=(void *)((char *)phdr + aux[AT_PHENT])) {
  721. if (phdr->p_type == PT_PHDR)
  722. app->base = (void *)(aux[AT_PHDR] - phdr->p_vaddr);
  723. else if (phdr->p_type == PT_INTERP)
  724. interp_off = (size_t)phdr->p_vaddr;
  725. else if (phdr->p_type == PT_TLS) {
  726. tls_image = phdr->p_vaddr;
  727. app->tls_len = phdr->p_filesz;
  728. app->tls_size = phdr->p_memsz;
  729. app->tls_align = phdr->p_align;
  730. }
  731. }
  732. if (app->tls_size) app->tls_image = (char *)app->base + tls_image;
  733. if (interp_off) lib->name = (char *)app->base + interp_off;
  734. app->name = argv[0];
  735. app->dynv = (void *)(app->base + find_dyn(
  736. (void *)aux[AT_PHDR], aux[AT_PHNUM], aux[AT_PHENT]));
  737. find_map_range((void *)aux[AT_PHDR],
  738. aux[AT_PHNUM], aux[AT_PHENT], app);
  739. } else {
  740. int fd;
  741. char *ldname = argv[0];
  742. size_t dyno, l = strlen(ldname);
  743. if (l >= 3 && !strcmp(ldname+l-3, "ldd")) ldd_mode = 1;
  744. *argv++ = (void *)-1;
  745. if (argv[0] && !strcmp(argv[0], "--")) *argv++ = (void *)-1;
  746. if (!argv[0]) {
  747. dprintf(2, "musl libc/dynamic program loader\n");
  748. dprintf(2, "usage: %s pathname%s\n", ldname,
  749. ldd_mode ? "" : " [args]");
  750. _exit(1);
  751. }
  752. fd = open(argv[0], O_RDONLY);
  753. if (fd < 0) {
  754. dprintf(2, "%s: cannot load %s: %s\n", ldname, argv[0], strerror(errno));
  755. _exit(1);
  756. }
  757. runtime = 1;
  758. ehdr = (void *)map_library(fd, app);
  759. if (!ehdr) {
  760. dprintf(2, "%s: %s: Not a valid dynamic program\n", ldname, argv[0]);
  761. _exit(1);
  762. }
  763. runtime = 0;
  764. close(fd);
  765. lib->name = ldname;
  766. app->name = argv[0];
  767. aux[AT_ENTRY] = ehdr->e_entry;
  768. }
  769. if (app->tls_size) {
  770. app->tls_id = ++tls_cnt;
  771. tls_size += app->tls_size+app->tls_align + 8*sizeof(size_t)-1
  772. & -4*sizeof(size_t);
  773. }
  774. app->global = 1;
  775. app->constructed = 1;
  776. decode_dyn(app);
  777. /* Attach to vdso, if provided by the kernel */
  778. if (search_vec(auxv, &vdso_base, AT_SYSINFO_EHDR)) {
  779. ehdr = (void *)vdso_base;
  780. phdr = (void *)(vdso_base + ehdr->e_phoff);
  781. for (i=ehdr->e_phnum; i; i--, phdr=(void *)((char *)phdr + ehdr->e_phentsize)) {
  782. if (phdr->p_type == PT_DYNAMIC)
  783. vdso->dynv = (void *)(vdso_base + phdr->p_offset);
  784. if (phdr->p_type == PT_LOAD)
  785. vdso->base = (void *)(vdso_base - phdr->p_vaddr + phdr->p_offset);
  786. }
  787. vdso->name = vdso->shortname = "linux-gate.so.1";
  788. vdso->global = 1;
  789. decode_dyn(vdso);
  790. vdso->prev = lib;
  791. lib->next = vdso;
  792. }
  793. /* Initial dso chain consists only of the app. We temporarily
  794. * append the dynamic linker/libc so we can relocate it, then
  795. * restore the initial chain in preparation for loading third
  796. * party libraries (preload/needed). */
  797. head = tail = app;
  798. libc = lib;
  799. app->next = lib;
  800. reloc_all(lib);
  801. app->next = 0;
  802. /* PAST THIS POINT, ALL LIBC INTERFACES ARE FULLY USABLE. */
  803. /* Donate unused parts of app and library mapping to malloc */
  804. reclaim_gaps(app->base, (void *)aux[AT_PHDR], aux[AT_PHENT], aux[AT_PHNUM]);
  805. ehdr = (void *)lib->base;
  806. reclaim_gaps(lib->base, (void *)(lib->base+ehdr->e_phoff),
  807. ehdr->e_phentsize, ehdr->e_phnum);
  808. /* Load preload/needed libraries, add their symbols to the global
  809. * namespace, and perform all remaining relocations. The main
  810. * program must be relocated LAST since it may contain copy
  811. * relocations which depend on libraries' relocations. */
  812. if (env_preload) load_preload(env_preload);
  813. load_deps(app);
  814. make_global(app);
  815. /* Make an initial pass setting up TLS before performing relocs.
  816. * This provides the TP-based offset of each DSO's TLS for
  817. * use in TP-relative relocations. After relocations, we need
  818. * to copy the TLS images again in case they had relocs. */
  819. tls_size += sizeof(struct pthread) + 4*sizeof(size_t);
  820. __libc.tls_size = tls_size;
  821. if (tls_cnt) {
  822. struct dso *p;
  823. void *mem = mmap(0, __libc.tls_size, PROT_READ|PROT_WRITE,
  824. MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
  825. if (mem==MAP_FAILED ||
  826. !__install_initial_tls(__copy_tls(mem))) {
  827. dprintf(2, "%s: Error getting %zu bytes thread-local storage: %m\n",
  828. argv[0], tls_size);
  829. _exit(127);
  830. }
  831. for (p=head; p; p=p->next) {
  832. if (!p->tls_id) continue;
  833. p->tls_offset = (char *)__pthread_self()
  834. - (char *)__pthread_self()->dtv[p->tls_id];
  835. }
  836. }
  837. reloc_all(app->next);
  838. reloc_all(app);
  839. /* The initial DTV is located at the base of the memory
  840. * allocated for TLS. Repeat copying TLS to pick up relocs. */
  841. if (tls_cnt) __copy_tls((void *)__pthread_self()->dtv);
  842. if (ldso_fail) _exit(127);
  843. if (ldd_mode) _exit(0);
  844. /* Switch to runtime mode: any further failures in the dynamic
  845. * linker are a reportable failure rather than a fatal startup
  846. * error. If the dynamic loader (dlopen) will not be used, free
  847. * all memory used by the dynamic linker. */
  848. runtime = 1;
  849. #ifndef DYNAMIC_IS_RO
  850. for (i=0; app->dynv[i]; i+=2)
  851. if (app->dynv[i]==DT_DEBUG)
  852. app->dynv[i+1] = (size_t)&debug;
  853. #endif
  854. debug.ver = 1;
  855. debug.bp = _dl_debug_state;
  856. debug.head = head;
  857. debug.base = lib->base;
  858. debug.state = 0;
  859. _dl_debug_state();
  860. if (ssp_used) __init_ssp(auxv);
  861. do_init_fini(tail);
  862. errno = 0;
  863. return (void *)aux[AT_ENTRY];
  864. }
  865. void *dlopen(const char *file, int mode)
  866. {
  867. struct dso *volatile p, *orig_tail, *next;
  868. size_t orig_tls_cnt;
  869. size_t i;
  870. int cs;
  871. if (!file) return head;
  872. pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
  873. pthread_rwlock_wrlock(&lock);
  874. __inhibit_ptc();
  875. p = 0;
  876. orig_tls_cnt = tls_cnt;
  877. orig_tail = tail;
  878. if (setjmp(rtld_fail)) {
  879. /* Clean up anything new that was (partially) loaded */
  880. if (p && p->deps) for (i=0; p->deps[i]; i++)
  881. if (p->deps[i]->global < 0)
  882. p->deps[i]->global = 0;
  883. for (p=orig_tail->next; p; p=next) {
  884. next = p->next;
  885. munmap(p->map, p->map_len);
  886. free(p->deps);
  887. free(p);
  888. }
  889. tls_cnt = orig_tls_cnt;
  890. tls_size = __libc.tls_size;
  891. tail = orig_tail;
  892. tail->next = 0;
  893. p = 0;
  894. errflag = 1;
  895. goto end;
  896. } else p = load_library(file);
  897. if (!p) {
  898. snprintf(errbuf, sizeof errbuf,
  899. "Error loading shared library %s: %m", file);
  900. errflag = 1;
  901. goto end;
  902. }
  903. /* First load handling */
  904. if (!p->deps) {
  905. load_deps(p);
  906. if (p->deps) for (i=0; p->deps[i]; i++)
  907. if (!p->deps[i]->global)
  908. p->deps[i]->global = -1;
  909. if (!p->global) p->global = -1;
  910. reloc_all(p);
  911. if (p->deps) for (i=0; p->deps[i]; i++)
  912. if (p->deps[i]->global < 0)
  913. p->deps[i]->global = 0;
  914. if (p->global < 0) p->global = 0;
  915. }
  916. if (mode & RTLD_GLOBAL) {
  917. if (p->deps) for (i=0; p->deps[i]; i++)
  918. p->deps[i]->global = 1;
  919. p->global = 1;
  920. }
  921. __libc.tls_size = tls_size;
  922. if (ssp_used) __init_ssp(auxv);
  923. _dl_debug_state();
  924. do_init_fini(tail);
  925. end:
  926. __release_ptc();
  927. pthread_rwlock_unlock(&lock);
  928. pthread_setcancelstate(cs, 0);
  929. return p;
  930. }
  931. static void *do_dlsym(struct dso *p, const char *s, void *ra)
  932. {
  933. size_t i;
  934. uint32_t h = 0, gh = 0;
  935. Sym *sym;
  936. if (p == head || p == RTLD_DEFAULT || p == RTLD_NEXT) {
  937. if (p == RTLD_NEXT) {
  938. for (p=head; p && (unsigned char *)ra-p->map>p->map_len; p=p->next);
  939. if (!p) p=head;
  940. }
  941. struct symdef def = find_sym(p->next, s, 0);
  942. if (!def.sym) goto failed;
  943. return def.dso->base + def.sym->st_value;
  944. }
  945. if (p->ghashtab) {
  946. gh = gnu_hash(s);
  947. sym = gnu_lookup(s, gh, p);
  948. } else {
  949. h = sysv_hash(s);
  950. sym = sysv_lookup(s, h, p);
  951. }
  952. if (sym && sym->st_value && (1<<(sym->st_info&0xf) & OK_TYPES))
  953. return p->base + sym->st_value;
  954. if (p->deps) for (i=0; p->deps[i]; i++) {
  955. if (p->deps[i]->ghashtab) {
  956. if (!gh) gh = gnu_hash(s);
  957. sym = gnu_lookup(s, gh, p->deps[i]);
  958. } else {
  959. if (!h) h = sysv_hash(s);
  960. sym = sysv_lookup(s, h, p->deps[i]);
  961. }
  962. if (sym && sym->st_value && (1<<(sym->st_info&0xf) & OK_TYPES))
  963. return p->deps[i]->base + sym->st_value;
  964. }
  965. failed:
  966. errflag = 1;
  967. snprintf(errbuf, sizeof errbuf, "Symbol not found: %s", s);
  968. return 0;
  969. }
  970. int __dladdr(void *addr, Dl_info *info)
  971. {
  972. struct dso *p;
  973. Sym *sym;
  974. uint32_t nsym;
  975. char *strings;
  976. size_t i;
  977. void *best = 0;
  978. char *bestname;
  979. pthread_rwlock_rdlock(&lock);
  980. for (p=head; p && (unsigned char *)addr-p->map>p->map_len; p=p->next);
  981. pthread_rwlock_unlock(&lock);
  982. if (!p) return 0;
  983. sym = p->syms;
  984. strings = p->strings;
  985. if (p->hashtab) {
  986. nsym = p->hashtab[1];
  987. } else {
  988. uint32_t *buckets;
  989. uint32_t *hashval;
  990. buckets = p->ghashtab + 4 + (p->ghashtab[2]*sizeof(size_t)/4);
  991. sym += p->ghashtab[1];
  992. for (i = 0; i < p->ghashtab[0]; i++) {
  993. if (buckets[i] > nsym)
  994. nsym = buckets[i];
  995. }
  996. if (nsym) {
  997. nsym -= p->ghashtab[1];
  998. hashval = buckets + p->ghashtab[0] + nsym;
  999. do nsym++;
  1000. while (!(*hashval++ & 1));
  1001. }
  1002. }
  1003. for (; nsym; nsym--, sym++) {
  1004. if (sym->st_shndx && sym->st_value
  1005. && (1<<(sym->st_info&0xf) & OK_TYPES)
  1006. && (1<<(sym->st_info>>4) & OK_BINDS)) {
  1007. void *symaddr = p->base + sym->st_value;
  1008. if (symaddr > addr || symaddr < best)
  1009. continue;
  1010. best = symaddr;
  1011. bestname = strings + sym->st_name;
  1012. if (addr == symaddr)
  1013. break;
  1014. }
  1015. }
  1016. if (!best) return 0;
  1017. info->dli_fname = p->name;
  1018. info->dli_fbase = p->base;
  1019. info->dli_sname = bestname;
  1020. info->dli_saddr = best;
  1021. return 1;
  1022. }
  1023. void *__dlsym(void *restrict p, const char *restrict s, void *restrict ra)
  1024. {
  1025. void *res;
  1026. pthread_rwlock_rdlock(&lock);
  1027. res = do_dlsym(p, s, ra);
  1028. pthread_rwlock_unlock(&lock);
  1029. return res;
  1030. }
  1031. #else
  1032. void *dlopen(const char *file, int mode)
  1033. {
  1034. return 0;
  1035. }
  1036. void *__dlsym(void *restrict p, const char *restrict s, void *restrict ra)
  1037. {
  1038. return 0;
  1039. }
  1040. int __dladdr (void *addr, Dl_info *info)
  1041. {
  1042. return 0;
  1043. }
  1044. #endif
  1045. char *dlerror()
  1046. {
  1047. if (!errflag) return 0;
  1048. errflag = 0;
  1049. return errbuf;
  1050. }
  1051. int dlclose(void *p)
  1052. {
  1053. return 0;
  1054. }