dynlink.c 41 KB

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