dynlink.c 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470
  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 <link.h>
  17. #include <setjmp.h>
  18. #include <pthread.h>
  19. #include <ctype.h>
  20. #include <dlfcn.h>
  21. #include "pthread_impl.h"
  22. #include "libc.h"
  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. #define MAXP2(a,b) (-(-(a)&-(b)))
  40. #define ALIGN(x,y) ((x)+(y)-1 & -(y))
  41. struct debug {
  42. int ver;
  43. void *head;
  44. void (*bp)(void);
  45. int state;
  46. void *base;
  47. };
  48. struct dso {
  49. unsigned char *base;
  50. char *name;
  51. size_t *dynv;
  52. struct dso *next, *prev;
  53. Phdr *phdr;
  54. int phnum;
  55. int refcnt;
  56. Sym *syms;
  57. uint32_t *hashtab;
  58. uint32_t *ghashtab;
  59. int16_t *versym;
  60. char *strings;
  61. unsigned char *map;
  62. size_t map_len;
  63. dev_t dev;
  64. ino_t ino;
  65. signed char global;
  66. char relocated;
  67. char constructed;
  68. char kernel_mapped;
  69. struct dso **deps, *needed_by;
  70. char *rpath_orig, *rpath;
  71. void *tls_image;
  72. size_t tls_len, tls_size, tls_align, tls_id, tls_offset;
  73. void **new_dtv;
  74. unsigned char *new_tls;
  75. int new_dtv_idx, new_tls_idx;
  76. struct dso *fini_next;
  77. char *shortname;
  78. char buf[];
  79. };
  80. struct symdef {
  81. Sym *sym;
  82. struct dso *dso;
  83. };
  84. #include "reloc.h"
  85. void __init_ssp(size_t *);
  86. void *__install_initial_tls(void *);
  87. void __init_libc(char **, char *);
  88. static struct dso *head, *tail, *ldso, *fini_head;
  89. static char *env_path, *sys_path;
  90. static unsigned long long gencnt;
  91. static int ssp_used;
  92. static int runtime;
  93. static int ldd_mode;
  94. static int ldso_fail;
  95. static int noload;
  96. static jmp_buf *rtld_fail;
  97. static pthread_rwlock_t lock;
  98. static struct debug debug;
  99. static size_t tls_cnt, tls_offset, tls_align = 4*sizeof(size_t);
  100. static pthread_mutex_t init_fini_lock = { ._m_type = PTHREAD_MUTEX_RECURSIVE };
  101. struct debug *_dl_debug_addr = &debug;
  102. #define AUX_CNT 38
  103. #define DYN_CNT 34
  104. static void decode_vec(size_t *v, size_t *a, size_t cnt)
  105. {
  106. memset(a, 0, cnt*sizeof(size_t));
  107. for (; v[0]; v+=2) if (v[0]<cnt) {
  108. a[0] |= 1ULL<<v[0];
  109. a[v[0]] = v[1];
  110. }
  111. }
  112. static int search_vec(size_t *v, size_t *r, size_t key)
  113. {
  114. for (; v[0]!=key; v+=2)
  115. if (!v[0]) return 0;
  116. *r = v[1];
  117. return 1;
  118. }
  119. static uint32_t sysv_hash(const char *s0)
  120. {
  121. const unsigned char *s = (void *)s0;
  122. uint_fast32_t h = 0;
  123. while (*s) {
  124. h = 16*h + *s++;
  125. h ^= h>>24 & 0xf0;
  126. }
  127. return h & 0xfffffff;
  128. }
  129. static uint32_t gnu_hash(const char *s0)
  130. {
  131. const unsigned char *s = (void *)s0;
  132. uint_fast32_t h = 5381;
  133. for (; *s; s++)
  134. h = h*33 + *s;
  135. return h;
  136. }
  137. static Sym *sysv_lookup(const char *s, uint32_t h, struct dso *dso)
  138. {
  139. size_t i;
  140. Sym *syms = dso->syms;
  141. uint32_t *hashtab = dso->hashtab;
  142. char *strings = dso->strings;
  143. for (i=hashtab[2+h%hashtab[0]]; i; i=hashtab[2+hashtab[0]+i]) {
  144. if ((!dso->versym || dso->versym[i] >= 0)
  145. && (!strcmp(s, strings+syms[i].st_name)))
  146. return syms+i;
  147. }
  148. return 0;
  149. }
  150. static Sym *gnu_lookup(const char *s, uint32_t h1, struct dso *dso)
  151. {
  152. Sym *syms = dso->syms;
  153. char *strings = dso->strings;
  154. uint32_t *hashtab = dso->ghashtab;
  155. uint32_t nbuckets = hashtab[0];
  156. uint32_t *buckets = hashtab + 4 + hashtab[2]*(sizeof(size_t)/4);
  157. uint32_t h2;
  158. uint32_t *hashval;
  159. uint32_t i = buckets[h1 % nbuckets];
  160. if (!i) return 0;
  161. hashval = buckets + nbuckets + (i - hashtab[1]);
  162. for (h1 |= 1; ; i++) {
  163. h2 = *hashval++;
  164. if ((!dso->versym || dso->versym[i] >= 0)
  165. && (h1 == (h2|1)) && !strcmp(s, strings + syms[i].st_name))
  166. return syms+i;
  167. if (h2 & 1) break;
  168. }
  169. return 0;
  170. }
  171. #define OK_TYPES (1<<STT_NOTYPE | 1<<STT_OBJECT | 1<<STT_FUNC | 1<<STT_COMMON | 1<<STT_TLS)
  172. #define OK_BINDS (1<<STB_GLOBAL | 1<<STB_WEAK | 1<<STB_GNU_UNIQUE)
  173. static struct symdef find_sym(struct dso *dso, const char *s, int need_def)
  174. {
  175. uint32_t h = 0, gh = 0;
  176. struct symdef def = {0};
  177. if (dso->ghashtab) {
  178. gh = gnu_hash(s);
  179. if (gh == 0x1f4039c9 && !strcmp(s, "__stack_chk_fail")) ssp_used = 1;
  180. } else {
  181. h = sysv_hash(s);
  182. if (h == 0x595a4cc && !strcmp(s, "__stack_chk_fail")) ssp_used = 1;
  183. }
  184. for (; dso; dso=dso->next) {
  185. Sym *sym;
  186. if (!dso->global) continue;
  187. if (dso->ghashtab) {
  188. if (!gh) gh = gnu_hash(s);
  189. sym = gnu_lookup(s, gh, dso);
  190. } else {
  191. if (!h) h = sysv_hash(s);
  192. sym = sysv_lookup(s, h, dso);
  193. }
  194. if (!sym) continue;
  195. if (!sym->st_shndx)
  196. if (need_def || (sym->st_info&0xf) == STT_TLS)
  197. continue;
  198. if (!sym->st_value)
  199. if ((sym->st_info&0xf) != STT_TLS)
  200. continue;
  201. if (!(1<<(sym->st_info&0xf) & OK_TYPES)) continue;
  202. if (!(1<<(sym->st_info>>4) & OK_BINDS)) continue;
  203. if (def.sym && sym->st_info>>4 == STB_WEAK) continue;
  204. def.sym = sym;
  205. def.dso = dso;
  206. if (sym->st_info>>4 == STB_GLOBAL) break;
  207. }
  208. return def;
  209. }
  210. static void do_relocs(struct dso *dso, size_t *rel, size_t rel_size, size_t stride)
  211. {
  212. unsigned char *base = dso->base;
  213. Sym *syms = dso->syms;
  214. char *strings = dso->strings;
  215. Sym *sym;
  216. const char *name;
  217. void *ctx;
  218. int type;
  219. int sym_index;
  220. struct symdef def;
  221. for (; rel_size; rel+=stride, rel_size-=stride*sizeof(size_t)) {
  222. type = R_TYPE(rel[1]);
  223. sym_index = R_SYM(rel[1]);
  224. if (sym_index) {
  225. sym = syms + sym_index;
  226. name = strings + sym->st_name;
  227. ctx = IS_COPY(type) ? head->next : head;
  228. def = find_sym(ctx, name, IS_PLT(type));
  229. if (!def.sym && sym->st_info>>4 != STB_WEAK) {
  230. snprintf(errbuf, sizeof errbuf,
  231. "Error relocating %s: %s: symbol not found",
  232. dso->name, name);
  233. if (runtime) longjmp(*rtld_fail, 1);
  234. dprintf(2, "%s\n", errbuf);
  235. ldso_fail = 1;
  236. continue;
  237. }
  238. } else {
  239. sym = 0;
  240. def.sym = 0;
  241. def.dso = 0;
  242. }
  243. do_single_reloc(dso, base, (void *)(base + rel[0]), type,
  244. stride>2 ? rel[2] : 0, sym, sym?sym->st_size:0, def,
  245. def.sym?(size_t)(def.dso->base+def.sym->st_value):0);
  246. }
  247. }
  248. /* A huge hack: to make up for the wastefulness of shared libraries
  249. * needing at least a page of dirty memory even if they have no global
  250. * data, we reclaim the gaps at the beginning and end of writable maps
  251. * and "donate" them to the heap by setting up minimal malloc
  252. * structures and then freeing them. */
  253. static void reclaim(unsigned char *base, size_t start, size_t end)
  254. {
  255. size_t *a, *z;
  256. start = start + 6*sizeof(size_t)-1 & -4*sizeof(size_t);
  257. end = (end & -4*sizeof(size_t)) - 2*sizeof(size_t);
  258. if (start>end || end-start < 4*sizeof(size_t)) return;
  259. a = (size_t *)(base + start);
  260. z = (size_t *)(base + end);
  261. a[-2] = 1;
  262. a[-1] = z[0] = end-start + 2*sizeof(size_t) | 1;
  263. z[1] = 1;
  264. free(a);
  265. }
  266. static void reclaim_gaps(unsigned char *base, Phdr *ph, size_t phent, size_t phcnt)
  267. {
  268. for (; phcnt--; ph=(void *)((char *)ph+phent)) {
  269. if (ph->p_type!=PT_LOAD) continue;
  270. if ((ph->p_flags&(PF_R|PF_W))!=(PF_R|PF_W)) continue;
  271. reclaim(base, ph->p_vaddr & -PAGE_SIZE, ph->p_vaddr);
  272. reclaim(base, ph->p_vaddr+ph->p_memsz,
  273. ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE);
  274. }
  275. }
  276. static void *map_library(int fd, struct dso *dso)
  277. {
  278. Ehdr buf[(896+sizeof(Ehdr))/sizeof(Ehdr)];
  279. void *allocated_buf=0;
  280. size_t phsize;
  281. size_t addr_min=SIZE_MAX, addr_max=0, map_len;
  282. size_t this_min, this_max;
  283. off_t off_start;
  284. Ehdr *eh;
  285. Phdr *ph, *ph0;
  286. unsigned prot;
  287. unsigned char *map=MAP_FAILED, *base;
  288. size_t dyn=0;
  289. size_t tls_image=0;
  290. size_t i;
  291. ssize_t l = read(fd, buf, sizeof buf);
  292. eh = buf;
  293. if (l<0) return 0;
  294. if (l<sizeof *eh || (eh->e_type != ET_DYN && eh->e_type != ET_EXEC))
  295. goto noexec;
  296. phsize = eh->e_phentsize * eh->e_phnum;
  297. if (phsize > sizeof buf - sizeof *eh) {
  298. allocated_buf = malloc(phsize);
  299. if (!allocated_buf) return 0;
  300. l = pread(fd, allocated_buf, phsize, eh->e_phoff);
  301. if (l < 0) goto error;
  302. if (l != phsize) goto noexec;
  303. ph = ph0 = allocated_buf;
  304. } else if (eh->e_phoff + phsize > l) {
  305. l = pread(fd, buf+1, phsize, eh->e_phoff);
  306. if (l < 0) goto error;
  307. if (l != phsize) goto noexec;
  308. ph = ph0 = (void *)(buf + 1);
  309. } else {
  310. ph = ph0 = (void *)((char *)buf + eh->e_phoff);
  311. }
  312. for (i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
  313. if (ph->p_type == PT_DYNAMIC)
  314. dyn = ph->p_vaddr;
  315. if (ph->p_type == PT_TLS) {
  316. tls_image = ph->p_vaddr;
  317. dso->tls_align = ph->p_align;
  318. dso->tls_len = ph->p_filesz;
  319. dso->tls_size = ph->p_memsz;
  320. }
  321. if (ph->p_type != PT_LOAD) continue;
  322. if (ph->p_vaddr < addr_min) {
  323. addr_min = ph->p_vaddr;
  324. off_start = ph->p_offset;
  325. prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
  326. ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
  327. ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
  328. }
  329. if (ph->p_vaddr+ph->p_memsz > addr_max) {
  330. addr_max = ph->p_vaddr+ph->p_memsz;
  331. }
  332. }
  333. if (!dyn) goto noexec;
  334. addr_max += PAGE_SIZE-1;
  335. addr_max &= -PAGE_SIZE;
  336. addr_min &= -PAGE_SIZE;
  337. off_start &= -PAGE_SIZE;
  338. map_len = addr_max - addr_min + off_start;
  339. /* The first time, we map too much, possibly even more than
  340. * the length of the file. This is okay because we will not
  341. * use the invalid part; we just need to reserve the right
  342. * amount of virtual address space to map over later. */
  343. map = mmap((void *)addr_min, map_len, prot, MAP_PRIVATE, fd, off_start);
  344. if (map==MAP_FAILED) goto error;
  345. /* If the loaded file is not relocatable and the requested address is
  346. * not available, then the load operation must fail. */
  347. if (eh->e_type != ET_DYN && addr_min && map!=(void *)addr_min) {
  348. errno = EBUSY;
  349. goto error;
  350. }
  351. base = map - addr_min;
  352. dso->phdr = 0;
  353. dso->phnum = 0;
  354. for (ph=ph0, i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
  355. if (ph->p_type != PT_LOAD) continue;
  356. /* Check if the programs headers are in this load segment, and
  357. * if so, record the address for use by dl_iterate_phdr. */
  358. if (!dso->phdr && eh->e_phoff >= ph->p_offset
  359. && eh->e_phoff+phsize <= ph->p_offset+ph->p_filesz) {
  360. dso->phdr = (void *)(base + ph->p_vaddr
  361. + (eh->e_phoff-ph->p_offset));
  362. dso->phnum = eh->e_phnum;
  363. }
  364. /* Reuse the existing mapping for the lowest-address LOAD */
  365. if ((ph->p_vaddr & -PAGE_SIZE) == addr_min) continue;
  366. this_min = ph->p_vaddr & -PAGE_SIZE;
  367. this_max = ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE;
  368. off_start = ph->p_offset & -PAGE_SIZE;
  369. prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
  370. ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
  371. ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
  372. if (mmap(base+this_min, this_max-this_min, prot, MAP_PRIVATE|MAP_FIXED, fd, off_start) == MAP_FAILED)
  373. goto error;
  374. if (ph->p_memsz > ph->p_filesz) {
  375. size_t brk = (size_t)base+ph->p_vaddr+ph->p_filesz;
  376. size_t pgbrk = brk+PAGE_SIZE-1 & -PAGE_SIZE;
  377. memset((void *)brk, 0, pgbrk-brk & PAGE_SIZE-1);
  378. 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)
  379. goto error;
  380. }
  381. }
  382. for (i=0; ((size_t *)(base+dyn))[i]; i+=2)
  383. if (((size_t *)(base+dyn))[i]==DT_TEXTREL) {
  384. if (mprotect(map, map_len, PROT_READ|PROT_WRITE|PROT_EXEC) < 0)
  385. goto error;
  386. break;
  387. }
  388. if (!runtime) reclaim_gaps(base, ph0, eh->e_phentsize, eh->e_phnum);
  389. dso->map = map;
  390. dso->map_len = map_len;
  391. dso->base = base;
  392. dso->dynv = (void *)(base+dyn);
  393. if (dso->tls_size) dso->tls_image = (void *)(base+tls_image);
  394. free(allocated_buf);
  395. return map;
  396. noexec:
  397. errno = ENOEXEC;
  398. error:
  399. if (map!=MAP_FAILED) munmap(map, map_len);
  400. free(allocated_buf);
  401. return 0;
  402. }
  403. static int path_open(const char *name, const char *s, char *buf, size_t buf_size)
  404. {
  405. size_t l;
  406. int fd;
  407. for (;;) {
  408. s += strspn(s, ":\n");
  409. l = strcspn(s, ":\n");
  410. if (l-1 >= INT_MAX) return -1;
  411. if (snprintf(buf, buf_size, "%.*s/%s", (int)l, s, name) >= buf_size)
  412. continue;
  413. if ((fd = open(buf, O_RDONLY|O_CLOEXEC))>=0) return fd;
  414. s += l;
  415. }
  416. }
  417. static int fixup_rpath(struct dso *p, char *buf, size_t buf_size)
  418. {
  419. size_t n, l;
  420. const char *s, *t, *origin;
  421. char *d;
  422. if (p->rpath) return 0;
  423. if (!p->rpath_orig) return -1;
  424. if (!strchr(p->rpath_orig, '$')) {
  425. p->rpath = p->rpath_orig;
  426. return 0;
  427. }
  428. n = 0;
  429. s = p->rpath_orig;
  430. while ((t=strchr(s, '$'))) {
  431. if (strncmp(t, "$ORIGIN", 7) && strncmp(t, "${ORIGIN}", 9))
  432. return -1;
  433. s = t+1;
  434. n++;
  435. }
  436. if (n > SSIZE_MAX/PATH_MAX) return -1;
  437. if (p->kernel_mapped) {
  438. /* $ORIGIN searches cannot be performed for the main program
  439. * when it is suid/sgid/AT_SECURE. This is because the
  440. * pathname is under the control of the caller of execve.
  441. * For libraries, however, $ORIGIN can be processed safely
  442. * since the library's pathname came from a trusted source
  443. * (either system paths or a call to dlopen). */
  444. if (libc.secure)
  445. return -1;
  446. l = readlink("/proc/self/exe", buf, buf_size);
  447. if (l >= buf_size)
  448. return -1;
  449. buf[l] = 0;
  450. origin = buf;
  451. } else {
  452. origin = p->name;
  453. }
  454. t = strrchr(origin, '/');
  455. l = t ? t-origin : 0;
  456. p->rpath = malloc(strlen(p->rpath_orig) + n*l + 1);
  457. if (!p->rpath) return -1;
  458. d = p->rpath;
  459. s = p->rpath_orig;
  460. while ((t=strchr(s, '$'))) {
  461. memcpy(d, s, t-s);
  462. d += t-s;
  463. memcpy(d, origin, l);
  464. d += l;
  465. /* It was determined previously that the '$' is followed
  466. * either by "ORIGIN" or "{ORIGIN}". */
  467. s = t + 7 + 2*(t[1]=='{');
  468. }
  469. strcpy(d, s);
  470. return 0;
  471. }
  472. static void decode_dyn(struct dso *p)
  473. {
  474. size_t dyn[DYN_CNT] = {0};
  475. decode_vec(p->dynv, dyn, DYN_CNT);
  476. p->syms = (void *)(p->base + dyn[DT_SYMTAB]);
  477. p->strings = (void *)(p->base + dyn[DT_STRTAB]);
  478. if (dyn[0]&(1<<DT_HASH))
  479. p->hashtab = (void *)(p->base + dyn[DT_HASH]);
  480. if (dyn[0]&(1<<DT_RPATH))
  481. p->rpath_orig = (void *)(p->strings + dyn[DT_RPATH]);
  482. if (search_vec(p->dynv, dyn, DT_GNU_HASH))
  483. p->ghashtab = (void *)(p->base + *dyn);
  484. if (search_vec(p->dynv, dyn, DT_VERSYM))
  485. p->versym = (void *)(p->base + *dyn);
  486. }
  487. static struct dso *load_library(const char *name, struct dso *needed_by)
  488. {
  489. char buf[2*NAME_MAX+2];
  490. const char *pathname;
  491. unsigned char *map;
  492. struct dso *p, temp_dso = {0};
  493. int fd;
  494. struct stat st;
  495. size_t alloc_size;
  496. int n_th = 0;
  497. int is_self = 0;
  498. /* Catch and block attempts to reload the implementation itself */
  499. if (name[0]=='l' && name[1]=='i' && name[2]=='b') {
  500. static const char *rp, reserved[] =
  501. "c\0pthread\0rt\0m\0dl\0util\0xnet\0";
  502. char *z = strchr(name, '.');
  503. if (z) {
  504. size_t l = z-name;
  505. for (rp=reserved; *rp && strncmp(name+3, rp, l-3); rp+=strlen(rp)+1);
  506. if (*rp) {
  507. if (ldd_mode) {
  508. /* Track which names have been resolved
  509. * and only report each one once. */
  510. static unsigned reported;
  511. unsigned mask = 1U<<(rp-reserved);
  512. if (!(reported & mask)) {
  513. reported |= mask;
  514. dprintf(1, "\t%s => %s (%p)\n",
  515. name, ldso->name,
  516. ldso->base);
  517. }
  518. }
  519. is_self = 1;
  520. }
  521. }
  522. }
  523. if (!strcmp(name, ldso->name)) is_self = 1;
  524. if (is_self) {
  525. if (!ldso->prev) {
  526. tail->next = ldso;
  527. ldso->prev = tail;
  528. tail = ldso->next ? ldso->next : ldso;
  529. }
  530. return ldso;
  531. }
  532. if (strchr(name, '/')) {
  533. pathname = name;
  534. fd = open(name, O_RDONLY|O_CLOEXEC);
  535. } else {
  536. /* Search for the name to see if it's already loaded */
  537. for (p=head->next; p; p=p->next) {
  538. if (p->shortname && !strcmp(p->shortname, name)) {
  539. p->refcnt++;
  540. return p;
  541. }
  542. }
  543. if (strlen(name) > NAME_MAX) return 0;
  544. fd = -1;
  545. if (env_path) fd = path_open(name, env_path, buf, sizeof buf);
  546. for (p=needed_by; fd < 0 && p; p=p->needed_by)
  547. if (!fixup_rpath(p, buf, sizeof buf))
  548. fd = path_open(name, p->rpath, buf, sizeof buf);
  549. if (fd < 0) {
  550. if (!sys_path) {
  551. char *prefix = 0;
  552. size_t prefix_len;
  553. if (ldso->name[0]=='/') {
  554. char *s, *t, *z;
  555. for (s=t=z=ldso->name; *s; s++)
  556. if (*s=='/') z=t, t=s;
  557. prefix_len = z-ldso->name;
  558. if (prefix_len < PATH_MAX)
  559. prefix = ldso->name;
  560. }
  561. if (!prefix) {
  562. prefix = "";
  563. prefix_len = 0;
  564. }
  565. char etc_ldso_path[prefix_len + 1
  566. + sizeof "/etc/ld-musl-" LDSO_ARCH ".path"];
  567. snprintf(etc_ldso_path, sizeof etc_ldso_path,
  568. "%.*s/etc/ld-musl-" LDSO_ARCH ".path",
  569. (int)prefix_len, prefix);
  570. FILE *f = fopen(etc_ldso_path, "rbe");
  571. if (f) {
  572. if (getdelim(&sys_path, (size_t[1]){0}, 0, f) <= 0) {
  573. free(sys_path);
  574. sys_path = "";
  575. }
  576. fclose(f);
  577. } else if (errno != ENOENT) {
  578. sys_path = "";
  579. }
  580. }
  581. if (!sys_path) sys_path = "/lib:/usr/local/lib:/usr/lib";
  582. fd = path_open(name, sys_path, buf, sizeof buf);
  583. }
  584. pathname = buf;
  585. }
  586. if (fd < 0) return 0;
  587. if (fstat(fd, &st) < 0) {
  588. close(fd);
  589. return 0;
  590. }
  591. for (p=head->next; p; p=p->next) {
  592. if (p->dev == st.st_dev && p->ino == st.st_ino) {
  593. /* If this library was previously loaded with a
  594. * pathname but a search found the same inode,
  595. * setup its shortname so it can be found by name. */
  596. if (!p->shortname && pathname != name)
  597. p->shortname = strrchr(p->name, '/')+1;
  598. close(fd);
  599. p->refcnt++;
  600. return p;
  601. }
  602. }
  603. map = noload ? 0 : map_library(fd, &temp_dso);
  604. close(fd);
  605. if (!map) return 0;
  606. /* Allocate storage for the new DSO. When there is TLS, this
  607. * storage must include a reservation for all pre-existing
  608. * threads to obtain copies of both the new TLS, and an
  609. * extended DTV capable of storing an additional slot for
  610. * the newly-loaded DSO. */
  611. alloc_size = sizeof *p + strlen(pathname) + 1;
  612. if (runtime && temp_dso.tls_image) {
  613. size_t per_th = temp_dso.tls_size + temp_dso.tls_align
  614. + sizeof(void *) * (tls_cnt+3);
  615. n_th = libc.threads_minus_1 + 1;
  616. if (n_th > SSIZE_MAX / per_th) alloc_size = SIZE_MAX;
  617. else alloc_size += n_th * per_th;
  618. }
  619. p = calloc(1, alloc_size);
  620. if (!p) {
  621. munmap(map, temp_dso.map_len);
  622. return 0;
  623. }
  624. memcpy(p, &temp_dso, sizeof temp_dso);
  625. decode_dyn(p);
  626. p->dev = st.st_dev;
  627. p->ino = st.st_ino;
  628. p->refcnt = 1;
  629. p->needed_by = needed_by;
  630. p->name = p->buf;
  631. strcpy(p->name, pathname);
  632. /* Add a shortname only if name arg was not an explicit pathname. */
  633. if (pathname != name) p->shortname = strrchr(p->name, '/')+1;
  634. if (p->tls_image) {
  635. if (runtime && !__pthread_self_init()) {
  636. munmap(map, p->map_len);
  637. free(p);
  638. return 0;
  639. }
  640. p->tls_id = ++tls_cnt;
  641. tls_align = MAXP2(tls_align, p->tls_align);
  642. #ifdef TLS_ABOVE_TP
  643. p->tls_offset = tls_offset + ( (tls_align-1) &
  644. -(tls_offset + (uintptr_t)p->tls_image) );
  645. tls_offset += p->tls_size;
  646. #else
  647. tls_offset += p->tls_size + p->tls_align - 1;
  648. tls_offset -= (tls_offset + (uintptr_t)p->tls_image)
  649. & (p->tls_align-1);
  650. p->tls_offset = tls_offset;
  651. #endif
  652. p->new_dtv = (void *)(-sizeof(size_t) &
  653. (uintptr_t)(p->name+strlen(p->name)+sizeof(size_t)));
  654. p->new_tls = (void *)(p->new_dtv + n_th*(tls_cnt+1));
  655. }
  656. tail->next = p;
  657. p->prev = tail;
  658. tail = p;
  659. if (ldd_mode) dprintf(1, "\t%s => %s (%p)\n", name, pathname, p->base);
  660. return p;
  661. }
  662. static void load_deps(struct dso *p)
  663. {
  664. size_t i, ndeps=0;
  665. struct dso ***deps = &p->deps, **tmp, *dep;
  666. for (; p; p=p->next) {
  667. for (i=0; p->dynv[i]; i+=2) {
  668. if (p->dynv[i] != DT_NEEDED) continue;
  669. dep = load_library(p->strings + p->dynv[i+1], p);
  670. if (!dep) {
  671. snprintf(errbuf, sizeof errbuf,
  672. "Error loading shared library %s: %m (needed by %s)",
  673. p->strings + p->dynv[i+1], p->name);
  674. if (runtime) longjmp(*rtld_fail, 1);
  675. dprintf(2, "%s\n", errbuf);
  676. ldso_fail = 1;
  677. continue;
  678. }
  679. if (runtime) {
  680. tmp = realloc(*deps, sizeof(*tmp)*(ndeps+2));
  681. if (!tmp) longjmp(*rtld_fail, 1);
  682. tmp[ndeps++] = dep;
  683. tmp[ndeps] = 0;
  684. *deps = tmp;
  685. }
  686. }
  687. }
  688. }
  689. static void load_preload(char *s)
  690. {
  691. int tmp;
  692. char *z;
  693. for (z=s; *z; s=z) {
  694. for ( ; *s && isspace(*s); s++);
  695. for (z=s; *z && !isspace(*z); z++);
  696. tmp = *z;
  697. *z = 0;
  698. load_library(s, 0);
  699. *z = tmp;
  700. }
  701. }
  702. static void make_global(struct dso *p)
  703. {
  704. for (; p; p=p->next) p->global = 1;
  705. }
  706. static void reloc_all(struct dso *p)
  707. {
  708. size_t dyn[DYN_CNT] = {0};
  709. for (; p; p=p->next) {
  710. if (p->relocated) continue;
  711. decode_vec(p->dynv, dyn, DYN_CNT);
  712. #ifdef NEED_ARCH_RELOCS
  713. do_arch_relocs(p, head);
  714. #endif
  715. do_relocs(p, (void *)(p->base+dyn[DT_JMPREL]), dyn[DT_PLTRELSZ],
  716. 2+(dyn[DT_PLTREL]==DT_RELA));
  717. do_relocs(p, (void *)(p->base+dyn[DT_REL]), dyn[DT_RELSZ], 2);
  718. do_relocs(p, (void *)(p->base+dyn[DT_RELA]), dyn[DT_RELASZ], 3);
  719. p->relocated = 1;
  720. }
  721. }
  722. static size_t find_dyn(Phdr *ph, size_t cnt, size_t stride)
  723. {
  724. for (; cnt--; ph = (void *)((char *)ph + stride))
  725. if (ph->p_type == PT_DYNAMIC)
  726. return ph->p_vaddr;
  727. return 0;
  728. }
  729. static void find_map_range(Phdr *ph, size_t cnt, size_t stride, struct dso *p)
  730. {
  731. size_t min_addr = -1, max_addr = 0;
  732. for (; cnt--; ph = (void *)((char *)ph + stride)) {
  733. if (ph->p_type != PT_LOAD) continue;
  734. if (ph->p_vaddr < min_addr)
  735. min_addr = ph->p_vaddr;
  736. if (ph->p_vaddr+ph->p_memsz > max_addr)
  737. max_addr = ph->p_vaddr+ph->p_memsz;
  738. }
  739. min_addr &= -PAGE_SIZE;
  740. max_addr = (max_addr + PAGE_SIZE-1) & -PAGE_SIZE;
  741. p->map = p->base + min_addr;
  742. p->map_len = max_addr - min_addr;
  743. }
  744. static void do_fini()
  745. {
  746. struct dso *p;
  747. size_t dyn[DYN_CNT] = {0};
  748. for (p=fini_head; p; p=p->fini_next) {
  749. if (!p->constructed) continue;
  750. decode_vec(p->dynv, dyn, DYN_CNT);
  751. if (dyn[0] & (1<<DT_FINI_ARRAY)) {
  752. size_t n = dyn[DT_FINI_ARRAYSZ]/sizeof(size_t);
  753. size_t *fn = (size_t *)(p->base + dyn[DT_FINI_ARRAY])+n;
  754. while (n--) ((void (*)(void))*--fn)();
  755. }
  756. #ifndef NO_LEGACY_INITFINI
  757. if ((dyn[0] & (1<<DT_FINI)) && dyn[DT_FINI])
  758. ((void (*)(void))(p->base + dyn[DT_FINI]))();
  759. #endif
  760. }
  761. }
  762. static void do_init_fini(struct dso *p)
  763. {
  764. size_t dyn[DYN_CNT] = {0};
  765. int need_locking = libc.threads_minus_1;
  766. /* Allow recursive calls that arise when a library calls
  767. * dlopen from one of its constructors, but block any
  768. * other threads until all ctors have finished. */
  769. if (need_locking) pthread_mutex_lock(&init_fini_lock);
  770. for (; p; p=p->prev) {
  771. if (p->constructed) continue;
  772. p->constructed = 1;
  773. decode_vec(p->dynv, dyn, DYN_CNT);
  774. if (dyn[0] & ((1<<DT_FINI) | (1<<DT_FINI_ARRAY))) {
  775. p->fini_next = fini_head;
  776. fini_head = p;
  777. }
  778. #ifndef NO_LEGACY_INITFINI
  779. if ((dyn[0] & (1<<DT_INIT)) && dyn[DT_INIT])
  780. ((void (*)(void))(p->base + dyn[DT_INIT]))();
  781. #endif
  782. if (dyn[0] & (1<<DT_INIT_ARRAY)) {
  783. size_t n = dyn[DT_INIT_ARRAYSZ]/sizeof(size_t);
  784. size_t *fn = (void *)(p->base + dyn[DT_INIT_ARRAY]);
  785. while (n--) ((void (*)(void))*fn++)();
  786. }
  787. if (!need_locking && libc.threads_minus_1) {
  788. need_locking = 1;
  789. pthread_mutex_lock(&init_fini_lock);
  790. }
  791. }
  792. if (need_locking) pthread_mutex_unlock(&init_fini_lock);
  793. }
  794. void _dl_debug_state(void)
  795. {
  796. }
  797. void __reset_tls()
  798. {
  799. pthread_t self = __pthread_self();
  800. struct dso *p;
  801. for (p=head; p; p=p->next) {
  802. if (!p->tls_id || !self->dtv[p->tls_id]) continue;
  803. memcpy(self->dtv[p->tls_id], p->tls_image, p->tls_len);
  804. memset((char *)self->dtv[p->tls_id]+p->tls_len, 0,
  805. p->tls_size - p->tls_len);
  806. if (p->tls_id == (size_t)self->dtv[0]) break;
  807. }
  808. }
  809. void *__copy_tls(unsigned char *mem)
  810. {
  811. pthread_t td;
  812. struct dso *p;
  813. if (!tls_cnt) return mem;
  814. void **dtv = (void *)mem;
  815. dtv[0] = (void *)tls_cnt;
  816. #ifdef TLS_ABOVE_TP
  817. mem += sizeof(void *) * (tls_cnt+1);
  818. mem += -((uintptr_t)mem + sizeof(struct pthread)) & (tls_align-1);
  819. td = (pthread_t)mem;
  820. mem += sizeof(struct pthread);
  821. for (p=head; p; p=p->next) {
  822. if (!p->tls_id) continue;
  823. dtv[p->tls_id] = mem + p->tls_offset;
  824. memcpy(dtv[p->tls_id], p->tls_image, p->tls_len);
  825. }
  826. #else
  827. mem += libc.tls_size - sizeof(struct pthread);
  828. mem -= (uintptr_t)mem & (tls_align-1);
  829. td = (pthread_t)mem;
  830. for (p=head; p; p=p->next) {
  831. if (!p->tls_id) continue;
  832. dtv[p->tls_id] = mem - p->tls_offset;
  833. memcpy(dtv[p->tls_id], p->tls_image, p->tls_len);
  834. }
  835. #endif
  836. td->dtv = dtv;
  837. return td;
  838. }
  839. void *__tls_get_addr(size_t *v)
  840. {
  841. pthread_t self = __pthread_self();
  842. if (v[0]<=(size_t)self->dtv[0] && self->dtv[v[0]])
  843. return (char *)self->dtv[v[0]]+v[1];
  844. /* Block signals to make accessing new TLS async-signal-safe */
  845. sigset_t set;
  846. pthread_sigmask(SIG_BLOCK, SIGALL_SET, &set);
  847. if (v[0]<=(size_t)self->dtv[0] && self->dtv[v[0]]) {
  848. pthread_sigmask(SIG_SETMASK, &set, 0);
  849. return (char *)self->dtv[v[0]]+v[1];
  850. }
  851. /* This is safe without any locks held because, if the caller
  852. * is able to request the Nth entry of the DTV, the DSO list
  853. * must be valid at least that far out and it was synchronized
  854. * at program startup or by an already-completed call to dlopen. */
  855. struct dso *p;
  856. for (p=head; p->tls_id != v[0]; p=p->next);
  857. /* Get new DTV space from new DSO if needed */
  858. if (v[0] > (size_t)self->dtv[0]) {
  859. void **newdtv = p->new_dtv +
  860. (v[0]+1)*sizeof(void *)*a_fetch_add(&p->new_dtv_idx,1);
  861. memcpy(newdtv, self->dtv,
  862. ((size_t)self->dtv[0]+1) * sizeof(void *));
  863. newdtv[0] = (void *)v[0];
  864. self->dtv = newdtv;
  865. }
  866. /* Get new TLS memory from new DSO */
  867. unsigned char *mem = p->new_tls +
  868. (p->tls_size + p->tls_align) * a_fetch_add(&p->new_tls_idx,1);
  869. mem += ((uintptr_t)p->tls_image - (uintptr_t)mem) & (p->tls_align-1);
  870. self->dtv[v[0]] = mem;
  871. memcpy(mem, p->tls_image, p->tls_len);
  872. pthread_sigmask(SIG_SETMASK, &set, 0);
  873. return mem + v[1];
  874. }
  875. static void update_tls_size()
  876. {
  877. libc.tls_size = ALIGN(
  878. (1+tls_cnt) * sizeof(void *) +
  879. tls_offset +
  880. sizeof(struct pthread) +
  881. tls_align * 2,
  882. tls_align);
  883. }
  884. void *__dynlink(int argc, char **argv)
  885. {
  886. size_t aux[AUX_CNT] = {0};
  887. size_t i;
  888. Phdr *phdr;
  889. Ehdr *ehdr;
  890. static struct dso builtin_dsos[3];
  891. struct dso *const app = builtin_dsos+0;
  892. struct dso *const lib = builtin_dsos+1;
  893. struct dso *const vdso = builtin_dsos+2;
  894. char *env_preload=0;
  895. size_t vdso_base;
  896. size_t *auxv;
  897. char **envp = argv+argc+1;
  898. /* Find aux vector just past environ[] */
  899. for (i=argc+1; argv[i]; i++)
  900. if (!memcmp(argv[i], "LD_LIBRARY_PATH=", 16))
  901. env_path = argv[i]+16;
  902. else if (!memcmp(argv[i], "LD_PRELOAD=", 11))
  903. env_preload = argv[i]+11;
  904. auxv = (void *)(argv+i+1);
  905. decode_vec(auxv, aux, AUX_CNT);
  906. /* Only trust user/env if kernel says we're not suid/sgid */
  907. if ((aux[0]&0x7800)!=0x7800 || aux[AT_UID]!=aux[AT_EUID]
  908. || aux[AT_GID]!=aux[AT_EGID] || aux[AT_SECURE]) {
  909. env_path = 0;
  910. env_preload = 0;
  911. libc.secure = 1;
  912. }
  913. libc.page_size = aux[AT_PAGESZ];
  914. /* If the dynamic linker was invoked as a program itself, AT_BASE
  915. * will not be set. In that case, we assume the base address is
  916. * the start of the page containing the PHDRs; I don't know any
  917. * better approach... */
  918. if (!aux[AT_BASE]) {
  919. aux[AT_BASE] = aux[AT_PHDR] & -PAGE_SIZE;
  920. aux[AT_PHDR] = aux[AT_PHENT] = aux[AT_PHNUM] = 0;
  921. }
  922. /* The dynamic linker load address is passed by the kernel
  923. * in the AUX vector, so this is easy. */
  924. lib->base = (void *)aux[AT_BASE];
  925. lib->name = lib->shortname = "libc.so";
  926. lib->global = 1;
  927. lib->kernel_mapped = 1;
  928. ehdr = (void *)lib->base;
  929. lib->phnum = ehdr->e_phnum;
  930. lib->phdr = (void *)(aux[AT_BASE]+ehdr->e_phoff);
  931. find_map_range(lib->phdr, ehdr->e_phnum, ehdr->e_phentsize, lib);
  932. lib->dynv = (void *)(lib->base + find_dyn(lib->phdr,
  933. ehdr->e_phnum, ehdr->e_phentsize));
  934. decode_dyn(lib);
  935. if (aux[AT_PHDR]) {
  936. size_t interp_off = 0;
  937. size_t tls_image = 0;
  938. /* Find load address of the main program, via AT_PHDR vs PT_PHDR. */
  939. app->phdr = phdr = (void *)aux[AT_PHDR];
  940. app->phnum = aux[AT_PHNUM];
  941. for (i=aux[AT_PHNUM]; i; i--, phdr=(void *)((char *)phdr + aux[AT_PHENT])) {
  942. if (phdr->p_type == PT_PHDR)
  943. app->base = (void *)(aux[AT_PHDR] - phdr->p_vaddr);
  944. else if (phdr->p_type == PT_INTERP)
  945. interp_off = (size_t)phdr->p_vaddr;
  946. else if (phdr->p_type == PT_TLS) {
  947. tls_image = phdr->p_vaddr;
  948. app->tls_len = phdr->p_filesz;
  949. app->tls_size = phdr->p_memsz;
  950. app->tls_align = phdr->p_align;
  951. }
  952. }
  953. if (app->tls_size) app->tls_image = (char *)app->base + tls_image;
  954. if (interp_off) lib->name = (char *)app->base + interp_off;
  955. if ((aux[0] & (1UL<<AT_EXECFN))
  956. && strncmp((char *)aux[AT_EXECFN], "/proc/", 6))
  957. app->name = (char *)aux[AT_EXECFN];
  958. else
  959. app->name = argv[0];
  960. app->kernel_mapped = 1;
  961. app->dynv = (void *)(app->base + find_dyn(
  962. (void *)aux[AT_PHDR], aux[AT_PHNUM], aux[AT_PHENT]));
  963. find_map_range((void *)aux[AT_PHDR],
  964. aux[AT_PHNUM], aux[AT_PHENT], app);
  965. } else {
  966. int fd;
  967. char *ldname = argv[0];
  968. size_t l = strlen(ldname);
  969. if (l >= 3 && !strcmp(ldname+l-3, "ldd")) ldd_mode = 1;
  970. *argv++ = (void *)-1;
  971. if (argv[0] && !strcmp(argv[0], "--")) *argv++ = (void *)-1;
  972. if (!argv[0]) {
  973. dprintf(2, "musl libc/dynamic program loader\n");
  974. dprintf(2, "usage: %s pathname%s\n", ldname,
  975. ldd_mode ? "" : " [args]");
  976. _exit(1);
  977. }
  978. fd = open(argv[0], O_RDONLY);
  979. if (fd < 0) {
  980. dprintf(2, "%s: cannot load %s: %s\n", ldname, argv[0], strerror(errno));
  981. _exit(1);
  982. }
  983. runtime = 1;
  984. ehdr = (void *)map_library(fd, app);
  985. if (!ehdr) {
  986. dprintf(2, "%s: %s: Not a valid dynamic program\n", ldname, argv[0]);
  987. _exit(1);
  988. }
  989. runtime = 0;
  990. close(fd);
  991. lib->name = ldname;
  992. app->name = argv[0];
  993. aux[AT_ENTRY] = (size_t)app->base + ehdr->e_entry;
  994. /* Find the name that would have been used for the dynamic
  995. * linker had ldd not taken its place. */
  996. if (ldd_mode) {
  997. for (i=0; i<app->phnum; i++) {
  998. if (app->phdr[i].p_type == PT_INTERP)
  999. lib->name = (void *)(app->base
  1000. + app->phdr[i].p_vaddr);
  1001. }
  1002. dprintf(1, "\t%s (%p)\n", lib->name, lib->base);
  1003. }
  1004. }
  1005. if (app->tls_size) {
  1006. app->tls_id = tls_cnt = 1;
  1007. #ifdef TLS_ABOVE_TP
  1008. app->tls_offset = 0;
  1009. tls_offset = app->tls_size
  1010. + ( -((uintptr_t)app->tls_image + app->tls_size)
  1011. & (app->tls_align-1) );
  1012. #else
  1013. tls_offset = app->tls_offset = app->tls_size
  1014. + ( -((uintptr_t)app->tls_image + app->tls_size)
  1015. & (app->tls_align-1) );
  1016. #endif
  1017. tls_align = MAXP2(tls_align, app->tls_align);
  1018. }
  1019. app->global = 1;
  1020. decode_dyn(app);
  1021. /* Attach to vdso, if provided by the kernel */
  1022. if (search_vec(auxv, &vdso_base, AT_SYSINFO_EHDR)) {
  1023. ehdr = (void *)vdso_base;
  1024. vdso->phdr = phdr = (void *)(vdso_base + ehdr->e_phoff);
  1025. vdso->phnum = ehdr->e_phnum;
  1026. for (i=ehdr->e_phnum; i; i--, phdr=(void *)((char *)phdr + ehdr->e_phentsize)) {
  1027. if (phdr->p_type == PT_DYNAMIC)
  1028. vdso->dynv = (void *)(vdso_base + phdr->p_offset);
  1029. if (phdr->p_type == PT_LOAD)
  1030. vdso->base = (void *)(vdso_base - phdr->p_vaddr + phdr->p_offset);
  1031. }
  1032. vdso->name = "";
  1033. vdso->shortname = "linux-gate.so.1";
  1034. vdso->global = 1;
  1035. decode_dyn(vdso);
  1036. vdso->prev = lib;
  1037. lib->next = vdso;
  1038. }
  1039. /* Initial dso chain consists only of the app. We temporarily
  1040. * append the dynamic linker/libc so we can relocate it, then
  1041. * restore the initial chain in preparation for loading third
  1042. * party libraries (preload/needed). */
  1043. head = tail = app;
  1044. ldso = lib;
  1045. app->next = lib;
  1046. reloc_all(lib);
  1047. app->next = 0;
  1048. /* PAST THIS POINT, ALL LIBC INTERFACES ARE FULLY USABLE. */
  1049. /* Donate unused parts of app and library mapping to malloc */
  1050. reclaim_gaps(app->base, (void *)aux[AT_PHDR], aux[AT_PHENT], aux[AT_PHNUM]);
  1051. ehdr = (void *)lib->base;
  1052. reclaim_gaps(lib->base, (void *)(lib->base+ehdr->e_phoff),
  1053. ehdr->e_phentsize, ehdr->e_phnum);
  1054. /* Load preload/needed libraries, add their symbols to the global
  1055. * namespace, and perform all remaining relocations. The main
  1056. * program must be relocated LAST since it may contain copy
  1057. * relocations which depend on libraries' relocations. */
  1058. if (env_preload) load_preload(env_preload);
  1059. load_deps(app);
  1060. make_global(app);
  1061. reloc_all(app->next);
  1062. reloc_all(app);
  1063. update_tls_size();
  1064. if (tls_cnt) {
  1065. void *mem = mmap(0, libc.tls_size, PROT_READ|PROT_WRITE,
  1066. MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
  1067. if (mem==MAP_FAILED ||
  1068. !__install_initial_tls(__copy_tls(mem))) {
  1069. dprintf(2, "%s: Error getting %zu bytes thread-local storage: %m\n",
  1070. argv[0], libc.tls_size);
  1071. _exit(127);
  1072. }
  1073. }
  1074. if (ldso_fail) _exit(127);
  1075. if (ldd_mode) _exit(0);
  1076. /* Switch to runtime mode: any further failures in the dynamic
  1077. * linker are a reportable failure rather than a fatal startup
  1078. * error. If the dynamic loader (dlopen) will not be used, free
  1079. * all memory used by the dynamic linker. */
  1080. runtime = 1;
  1081. #ifndef DYNAMIC_IS_RO
  1082. for (i=0; app->dynv[i]; i+=2)
  1083. if (app->dynv[i]==DT_DEBUG)
  1084. app->dynv[i+1] = (size_t)&debug;
  1085. #endif
  1086. debug.ver = 1;
  1087. debug.bp = _dl_debug_state;
  1088. debug.head = head;
  1089. debug.base = lib->base;
  1090. debug.state = 0;
  1091. _dl_debug_state();
  1092. if (ssp_used) __init_ssp((void *)aux[AT_RANDOM]);
  1093. __init_libc(envp, argv[0]);
  1094. atexit(do_fini);
  1095. errno = 0;
  1096. do_init_fini(tail);
  1097. return (void *)aux[AT_ENTRY];
  1098. }
  1099. void *dlopen(const char *file, int mode)
  1100. {
  1101. struct dso *volatile p, *orig_tail, *next;
  1102. size_t orig_tls_cnt, orig_tls_offset, orig_tls_align;
  1103. size_t i;
  1104. int cs;
  1105. jmp_buf jb;
  1106. if (!file) return head;
  1107. pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
  1108. pthread_rwlock_wrlock(&lock);
  1109. __inhibit_ptc();
  1110. p = 0;
  1111. orig_tls_cnt = tls_cnt;
  1112. orig_tls_offset = tls_offset;
  1113. orig_tls_align = tls_align;
  1114. orig_tail = tail;
  1115. noload = mode & RTLD_NOLOAD;
  1116. rtld_fail = &jb;
  1117. if (setjmp(*rtld_fail)) {
  1118. /* Clean up anything new that was (partially) loaded */
  1119. if (p && p->deps) for (i=0; p->deps[i]; i++)
  1120. if (p->deps[i]->global < 0)
  1121. p->deps[i]->global = 0;
  1122. for (p=orig_tail->next; p; p=next) {
  1123. next = p->next;
  1124. munmap(p->map, p->map_len);
  1125. free(p->deps);
  1126. free(p);
  1127. }
  1128. tls_cnt = orig_tls_cnt;
  1129. tls_offset = orig_tls_offset;
  1130. tls_align = orig_tls_align;
  1131. tail = orig_tail;
  1132. tail->next = 0;
  1133. p = 0;
  1134. errflag = 1;
  1135. goto end;
  1136. } else p = load_library(file, head);
  1137. if (!p) {
  1138. snprintf(errbuf, sizeof errbuf, noload ?
  1139. "Library %s is not already loaded" :
  1140. "Error loading shared library %s: %m",
  1141. file);
  1142. errflag = 1;
  1143. goto end;
  1144. }
  1145. /* First load handling */
  1146. if (!p->deps) {
  1147. load_deps(p);
  1148. if (p->deps) for (i=0; p->deps[i]; i++)
  1149. if (!p->deps[i]->global)
  1150. p->deps[i]->global = -1;
  1151. if (!p->global) p->global = -1;
  1152. reloc_all(p);
  1153. if (p->deps) for (i=0; p->deps[i]; i++)
  1154. if (p->deps[i]->global < 0)
  1155. p->deps[i]->global = 0;
  1156. if (p->global < 0) p->global = 0;
  1157. }
  1158. if (mode & RTLD_GLOBAL) {
  1159. if (p->deps) for (i=0; p->deps[i]; i++)
  1160. p->deps[i]->global = 1;
  1161. p->global = 1;
  1162. }
  1163. update_tls_size();
  1164. if (ssp_used) __init_ssp(libc.auxv);
  1165. _dl_debug_state();
  1166. orig_tail = tail;
  1167. end:
  1168. __release_ptc();
  1169. if (p) gencnt++;
  1170. pthread_rwlock_unlock(&lock);
  1171. if (p) do_init_fini(orig_tail);
  1172. pthread_setcancelstate(cs, 0);
  1173. return p;
  1174. }
  1175. static int invalid_dso_handle(void *h)
  1176. {
  1177. struct dso *p;
  1178. for (p=head; p; p=p->next) if (h==p) return 0;
  1179. snprintf(errbuf, sizeof errbuf, "Invalid library handle %p", (void *)h);
  1180. errflag = 1;
  1181. return 1;
  1182. }
  1183. static void *do_dlsym(struct dso *p, const char *s, void *ra)
  1184. {
  1185. size_t i;
  1186. uint32_t h = 0, gh = 0;
  1187. Sym *sym;
  1188. if (p == head || p == RTLD_DEFAULT || p == RTLD_NEXT) {
  1189. if (p == RTLD_DEFAULT) {
  1190. p = head;
  1191. } else if (p == RTLD_NEXT) {
  1192. for (p=head; p && (unsigned char *)ra-p->map>p->map_len; p=p->next);
  1193. if (!p) p=head;
  1194. p = p->next;
  1195. }
  1196. struct symdef def = find_sym(p, s, 0);
  1197. if (!def.sym) goto failed;
  1198. if ((def.sym->st_info&0xf) == STT_TLS)
  1199. return __tls_get_addr((size_t []){def.dso->tls_id, def.sym->st_value});
  1200. return def.dso->base + def.sym->st_value;
  1201. }
  1202. if (p != RTLD_DEFAULT && p != RTLD_NEXT && invalid_dso_handle(p))
  1203. return 0;
  1204. if (p->ghashtab) {
  1205. gh = gnu_hash(s);
  1206. sym = gnu_lookup(s, gh, p);
  1207. } else {
  1208. h = sysv_hash(s);
  1209. sym = sysv_lookup(s, h, p);
  1210. }
  1211. if (sym && (sym->st_info&0xf) == STT_TLS)
  1212. return __tls_get_addr((size_t []){p->tls_id, sym->st_value});
  1213. if (sym && sym->st_value && (1<<(sym->st_info&0xf) & OK_TYPES))
  1214. return p->base + sym->st_value;
  1215. if (p->deps) for (i=0; p->deps[i]; i++) {
  1216. if (p->deps[i]->ghashtab) {
  1217. if (!gh) gh = gnu_hash(s);
  1218. sym = gnu_lookup(s, gh, p->deps[i]);
  1219. } else {
  1220. if (!h) h = sysv_hash(s);
  1221. sym = sysv_lookup(s, h, p->deps[i]);
  1222. }
  1223. if (sym && (sym->st_info&0xf) == STT_TLS)
  1224. return __tls_get_addr((size_t []){p->deps[i]->tls_id, sym->st_value});
  1225. if (sym && sym->st_value && (1<<(sym->st_info&0xf) & OK_TYPES))
  1226. return p->deps[i]->base + sym->st_value;
  1227. }
  1228. failed:
  1229. errflag = 1;
  1230. snprintf(errbuf, sizeof errbuf, "Symbol not found: %s", s);
  1231. return 0;
  1232. }
  1233. int __dladdr(void *addr, Dl_info *info)
  1234. {
  1235. struct dso *p;
  1236. Sym *sym;
  1237. uint32_t nsym;
  1238. char *strings;
  1239. size_t i;
  1240. void *best = 0;
  1241. char *bestname;
  1242. pthread_rwlock_rdlock(&lock);
  1243. for (p=head; p && (unsigned char *)addr-p->map>p->map_len; p=p->next);
  1244. pthread_rwlock_unlock(&lock);
  1245. if (!p) return 0;
  1246. sym = p->syms;
  1247. strings = p->strings;
  1248. if (p->hashtab) {
  1249. nsym = p->hashtab[1];
  1250. } else {
  1251. uint32_t *buckets;
  1252. uint32_t *hashval;
  1253. buckets = p->ghashtab + 4 + (p->ghashtab[2]*sizeof(size_t)/4);
  1254. sym += p->ghashtab[1];
  1255. for (i = 0; i < p->ghashtab[0]; i++) {
  1256. if (buckets[i] > nsym)
  1257. nsym = buckets[i];
  1258. }
  1259. if (nsym) {
  1260. nsym -= p->ghashtab[1];
  1261. hashval = buckets + p->ghashtab[0] + nsym;
  1262. do nsym++;
  1263. while (!(*hashval++ & 1));
  1264. }
  1265. }
  1266. for (; nsym; nsym--, sym++) {
  1267. if (sym->st_value
  1268. && (1<<(sym->st_info&0xf) & OK_TYPES)
  1269. && (1<<(sym->st_info>>4) & OK_BINDS)) {
  1270. void *symaddr = p->base + sym->st_value;
  1271. if (symaddr > addr || symaddr < best)
  1272. continue;
  1273. best = symaddr;
  1274. bestname = strings + sym->st_name;
  1275. if (addr == symaddr)
  1276. break;
  1277. }
  1278. }
  1279. if (!best) return 0;
  1280. info->dli_fname = p->name;
  1281. info->dli_fbase = p->base;
  1282. info->dli_sname = bestname;
  1283. info->dli_saddr = best;
  1284. return 1;
  1285. }
  1286. void *__dlsym(void *restrict p, const char *restrict s, void *restrict ra)
  1287. {
  1288. void *res;
  1289. pthread_rwlock_rdlock(&lock);
  1290. res = do_dlsym(p, s, ra);
  1291. pthread_rwlock_unlock(&lock);
  1292. return res;
  1293. }
  1294. int dl_iterate_phdr(int(*callback)(struct dl_phdr_info *info, size_t size, void *data), void *data)
  1295. {
  1296. struct dso *current;
  1297. struct dl_phdr_info info;
  1298. int ret = 0;
  1299. for(current = head; current;) {
  1300. info.dlpi_addr = (uintptr_t)current->base;
  1301. info.dlpi_name = current->name;
  1302. info.dlpi_phdr = current->phdr;
  1303. info.dlpi_phnum = current->phnum;
  1304. info.dlpi_adds = gencnt;
  1305. info.dlpi_subs = 0;
  1306. info.dlpi_tls_modid = current->tls_id;
  1307. info.dlpi_tls_data = current->tls_image;
  1308. ret = (callback)(&info, sizeof (info), data);
  1309. if (ret != 0) break;
  1310. pthread_rwlock_rdlock(&lock);
  1311. current = current->next;
  1312. pthread_rwlock_unlock(&lock);
  1313. }
  1314. return ret;
  1315. }
  1316. #else
  1317. static int invalid_dso_handle(void *h)
  1318. {
  1319. snprintf(errbuf, sizeof errbuf, "Invalid library handle %p", (void *)h);
  1320. errflag = 1;
  1321. return 1;
  1322. }
  1323. void *dlopen(const char *file, int mode)
  1324. {
  1325. return 0;
  1326. }
  1327. void *__dlsym(void *restrict p, const char *restrict s, void *restrict ra)
  1328. {
  1329. return 0;
  1330. }
  1331. int __dladdr (void *addr, Dl_info *info)
  1332. {
  1333. return 0;
  1334. }
  1335. #endif
  1336. int __dlinfo(void *dso, int req, void *res)
  1337. {
  1338. if (invalid_dso_handle(dso)) return -1;
  1339. if (req != RTLD_DI_LINKMAP) {
  1340. snprintf(errbuf, sizeof errbuf, "Unsupported request %d", req);
  1341. errflag = 1;
  1342. return -1;
  1343. }
  1344. *(struct link_map **)res = dso;
  1345. return 0;
  1346. }
  1347. char *dlerror()
  1348. {
  1349. if (!errflag) return 0;
  1350. errflag = 0;
  1351. return errbuf;
  1352. }
  1353. int dlclose(void *p)
  1354. {
  1355. return invalid_dso_handle(p);
  1356. }