dynlink.c 38 KB

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