dynlink.c 42 KB

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