dynlink.c 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934
  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. #include "dynlink.h"
  23. static void error(const char *, ...);
  24. #define MAXP2(a,b) (-(-(a)&-(b)))
  25. #define ALIGN(x,y) ((x)+(y)-1 & -(y))
  26. struct debug {
  27. int ver;
  28. void *head;
  29. void (*bp)(void);
  30. int state;
  31. void *base;
  32. };
  33. struct td_index {
  34. size_t args[2];
  35. struct td_index *next;
  36. };
  37. struct dso {
  38. #if DL_FDPIC
  39. struct fdpic_loadmap *loadmap;
  40. #else
  41. unsigned char *base;
  42. #endif
  43. char *name;
  44. size_t *dynv;
  45. struct dso *next, *prev;
  46. Phdr *phdr;
  47. int phnum;
  48. size_t phentsize;
  49. int refcnt;
  50. Sym *syms;
  51. Elf_Symndx *hashtab;
  52. uint32_t *ghashtab;
  53. int16_t *versym;
  54. char *strings;
  55. unsigned char *map;
  56. size_t map_len;
  57. dev_t dev;
  58. ino_t ino;
  59. signed char global;
  60. char relocated;
  61. char constructed;
  62. char kernel_mapped;
  63. struct dso **deps, *needed_by;
  64. char *rpath_orig, *rpath;
  65. struct tls_module tls;
  66. size_t tls_id;
  67. size_t relro_start, relro_end;
  68. void **new_dtv;
  69. unsigned char *new_tls;
  70. volatile int new_dtv_idx, new_tls_idx;
  71. struct td_index *td_index;
  72. struct dso *fini_next;
  73. char *shortname;
  74. #if DL_FDPIC
  75. unsigned char *base;
  76. #else
  77. struct fdpic_loadmap *loadmap;
  78. #endif
  79. struct funcdesc {
  80. void *addr;
  81. size_t *got;
  82. } *funcdescs;
  83. size_t *got;
  84. char buf[];
  85. };
  86. struct symdef {
  87. Sym *sym;
  88. struct dso *dso;
  89. };
  90. int __init_tp(void *);
  91. void __init_libc(char **, char *);
  92. void *__copy_tls(unsigned char *);
  93. __attribute__((__visibility__("hidden")))
  94. const char *__libc_get_version(void);
  95. static struct builtin_tls {
  96. char c;
  97. struct pthread pt;
  98. void *space[16];
  99. } builtin_tls[1];
  100. #define MIN_TLS_ALIGN offsetof(struct builtin_tls, pt)
  101. #define ADDEND_LIMIT 4096
  102. static size_t *saved_addends, *apply_addends_to;
  103. static struct dso ldso;
  104. static struct dso *head, *tail, *fini_head;
  105. static char *env_path, *sys_path;
  106. static unsigned long long gencnt;
  107. static int runtime;
  108. static int ldd_mode;
  109. static int ldso_fail;
  110. static int noload;
  111. static jmp_buf *rtld_fail;
  112. static pthread_rwlock_t lock;
  113. static struct debug debug;
  114. static struct tls_module *tls_tail;
  115. static size_t tls_cnt, tls_offset, tls_align = MIN_TLS_ALIGN;
  116. static size_t static_tls_cnt;
  117. static pthread_mutex_t init_fini_lock = { ._m_type = PTHREAD_MUTEX_RECURSIVE };
  118. static struct fdpic_loadmap *app_loadmap;
  119. static struct fdpic_dummy_loadmap app_dummy_loadmap;
  120. struct debug *_dl_debug_addr = &debug;
  121. __attribute__((__visibility__("hidden")))
  122. void (*const __init_array_start)(void)=0, (*const __fini_array_start)(void)=0;
  123. __attribute__((__visibility__("hidden")))
  124. extern void (*const __init_array_end)(void), (*const __fini_array_end)(void);
  125. weak_alias(__init_array_start, __init_array_end);
  126. weak_alias(__fini_array_start, __fini_array_end);
  127. static int dl_strcmp(const char *l, const char *r)
  128. {
  129. for (; *l==*r && *l; l++, r++);
  130. return *(unsigned char *)l - *(unsigned char *)r;
  131. }
  132. #define strcmp(l,r) dl_strcmp(l,r)
  133. /* Compute load address for a virtual address in a given dso. */
  134. #if DL_FDPIC
  135. static void *laddr(const struct dso *p, size_t v)
  136. {
  137. size_t j=0;
  138. if (!p->loadmap) return p->base + v;
  139. for (j=0; v-p->loadmap->segs[j].p_vaddr >= p->loadmap->segs[j].p_memsz; j++);
  140. return (void *)(v - p->loadmap->segs[j].p_vaddr + p->loadmap->segs[j].addr);
  141. }
  142. #define fpaddr(p, v) ((void (*)())&(struct funcdesc){ \
  143. laddr(p, v), (p)->got })
  144. #else
  145. #define laddr(p, v) (void *)((p)->base + (v))
  146. #define fpaddr(p, v) ((void (*)())laddr(p, v))
  147. #endif
  148. static void decode_vec(size_t *v, size_t *a, size_t cnt)
  149. {
  150. size_t i;
  151. for (i=0; i<cnt; i++) a[i] = 0;
  152. for (; v[0]; v+=2) if (v[0]-1<cnt-1) {
  153. a[0] |= 1UL<<v[0];
  154. a[v[0]] = v[1];
  155. }
  156. }
  157. static int search_vec(size_t *v, size_t *r, size_t key)
  158. {
  159. for (; v[0]!=key; v+=2)
  160. if (!v[0]) return 0;
  161. *r = v[1];
  162. return 1;
  163. }
  164. static uint32_t sysv_hash(const char *s0)
  165. {
  166. const unsigned char *s = (void *)s0;
  167. uint_fast32_t h = 0;
  168. while (*s) {
  169. h = 16*h + *s++;
  170. h ^= h>>24 & 0xf0;
  171. }
  172. return h & 0xfffffff;
  173. }
  174. static uint32_t gnu_hash(const char *s0)
  175. {
  176. const unsigned char *s = (void *)s0;
  177. uint_fast32_t h = 5381;
  178. for (; *s; s++)
  179. h += h*32 + *s;
  180. return h;
  181. }
  182. static Sym *sysv_lookup(const char *s, uint32_t h, struct dso *dso)
  183. {
  184. size_t i;
  185. Sym *syms = dso->syms;
  186. Elf_Symndx *hashtab = dso->hashtab;
  187. char *strings = dso->strings;
  188. for (i=hashtab[2+h%hashtab[0]]; i; i=hashtab[2+hashtab[0]+i]) {
  189. if ((!dso->versym || dso->versym[i] >= 0)
  190. && (!strcmp(s, strings+syms[i].st_name)))
  191. return syms+i;
  192. }
  193. return 0;
  194. }
  195. static Sym *gnu_lookup(uint32_t h1, uint32_t *hashtab, struct dso *dso, const char *s)
  196. {
  197. uint32_t nbuckets = hashtab[0];
  198. uint32_t *buckets = hashtab + 4 + hashtab[2]*(sizeof(size_t)/4);
  199. uint32_t i = buckets[h1 % nbuckets];
  200. if (!i) return 0;
  201. uint32_t *hashval = buckets + nbuckets + (i - hashtab[1]);
  202. for (h1 |= 1; ; i++) {
  203. uint32_t h2 = *hashval++;
  204. if ((h1 == (h2|1)) && (!dso->versym || dso->versym[i] >= 0)
  205. && !strcmp(s, dso->strings + dso->syms[i].st_name))
  206. return dso->syms+i;
  207. if (h2 & 1) break;
  208. }
  209. return 0;
  210. }
  211. static Sym *gnu_lookup_filtered(uint32_t h1, uint32_t *hashtab, struct dso *dso, const char *s, uint32_t fofs, size_t fmask)
  212. {
  213. const size_t *bloomwords = (const void *)(hashtab+4);
  214. size_t f = bloomwords[fofs & (hashtab[2]-1)];
  215. if (!(f & fmask)) return 0;
  216. f >>= (h1 >> hashtab[3]) % (8 * sizeof f);
  217. if (!(f & 1)) return 0;
  218. return gnu_lookup(h1, hashtab, dso, s);
  219. }
  220. #define OK_TYPES (1<<STT_NOTYPE | 1<<STT_OBJECT | 1<<STT_FUNC | 1<<STT_COMMON | 1<<STT_TLS)
  221. #define OK_BINDS (1<<STB_GLOBAL | 1<<STB_WEAK | 1<<STB_GNU_UNIQUE)
  222. #ifndef ARCH_SYM_REJECT_UND
  223. #define ARCH_SYM_REJECT_UND(s) 0
  224. #endif
  225. static struct symdef find_sym(struct dso *dso, const char *s, int need_def)
  226. {
  227. uint32_t h = 0, gh, gho, *ght;
  228. size_t ghm = 0;
  229. struct symdef def = {0};
  230. for (; dso; dso=dso->next) {
  231. Sym *sym;
  232. if (!dso->global) continue;
  233. if ((ght = dso->ghashtab)) {
  234. if (!ghm) {
  235. gh = gnu_hash(s);
  236. int maskbits = 8 * sizeof ghm;
  237. gho = gh / maskbits;
  238. ghm = 1ul << gh % maskbits;
  239. }
  240. sym = gnu_lookup_filtered(gh, ght, dso, s, gho, ghm);
  241. } else {
  242. if (!h) h = sysv_hash(s);
  243. sym = sysv_lookup(s, h, dso);
  244. }
  245. if (!sym) continue;
  246. if (!sym->st_shndx)
  247. if (need_def || (sym->st_info&0xf) == STT_TLS
  248. || ARCH_SYM_REJECT_UND(sym))
  249. continue;
  250. if (!sym->st_value)
  251. if ((sym->st_info&0xf) != STT_TLS)
  252. continue;
  253. if (!(1<<(sym->st_info&0xf) & OK_TYPES)) continue;
  254. if (!(1<<(sym->st_info>>4) & OK_BINDS)) continue;
  255. def.sym = sym;
  256. def.dso = dso;
  257. break;
  258. }
  259. return def;
  260. }
  261. __attribute__((__visibility__("hidden")))
  262. ptrdiff_t __tlsdesc_static(), __tlsdesc_dynamic();
  263. static void do_relocs(struct dso *dso, size_t *rel, size_t rel_size, size_t stride)
  264. {
  265. unsigned char *base = dso->base;
  266. Sym *syms = dso->syms;
  267. char *strings = dso->strings;
  268. Sym *sym;
  269. const char *name;
  270. void *ctx;
  271. int type;
  272. int sym_index;
  273. struct symdef def;
  274. size_t *reloc_addr;
  275. size_t sym_val;
  276. size_t tls_val;
  277. size_t addend;
  278. int skip_relative = 0, reuse_addends = 0, save_slot = 0;
  279. if (dso == &ldso) {
  280. /* Only ldso's REL table needs addend saving/reuse. */
  281. if (rel == apply_addends_to)
  282. reuse_addends = 1;
  283. skip_relative = 1;
  284. }
  285. for (; rel_size; rel+=stride, rel_size-=stride*sizeof(size_t)) {
  286. if (skip_relative && IS_RELATIVE(rel[1], dso->syms)) continue;
  287. type = R_TYPE(rel[1]);
  288. if (type == REL_NONE) continue;
  289. sym_index = R_SYM(rel[1]);
  290. reloc_addr = laddr(dso, rel[0]);
  291. if (sym_index) {
  292. sym = syms + sym_index;
  293. name = strings + sym->st_name;
  294. ctx = type==REL_COPY ? head->next : head;
  295. def = (sym->st_info&0xf) == STT_SECTION
  296. ? (struct symdef){ .dso = dso, .sym = sym }
  297. : find_sym(ctx, name, type==REL_PLT);
  298. if (!def.sym && (sym->st_shndx != SHN_UNDEF
  299. || sym->st_info>>4 != STB_WEAK)) {
  300. error("Error relocating %s: %s: symbol not found",
  301. dso->name, name);
  302. if (runtime) longjmp(*rtld_fail, 1);
  303. continue;
  304. }
  305. } else {
  306. sym = 0;
  307. def.sym = 0;
  308. def.dso = dso;
  309. }
  310. if (stride > 2) {
  311. addend = rel[2];
  312. } else if (type==REL_GOT || type==REL_PLT|| type==REL_COPY) {
  313. addend = 0;
  314. } else if (reuse_addends) {
  315. /* Save original addend in stage 2 where the dso
  316. * chain consists of just ldso; otherwise read back
  317. * saved addend since the inline one was clobbered. */
  318. if (head==&ldso)
  319. saved_addends[save_slot] = *reloc_addr;
  320. addend = saved_addends[save_slot++];
  321. } else {
  322. addend = *reloc_addr;
  323. }
  324. sym_val = def.sym ? (size_t)laddr(def.dso, def.sym->st_value) : 0;
  325. tls_val = def.sym ? def.sym->st_value : 0;
  326. switch(type) {
  327. case REL_NONE:
  328. break;
  329. case REL_OFFSET:
  330. addend -= (size_t)reloc_addr;
  331. case REL_SYMBOLIC:
  332. case REL_GOT:
  333. case REL_PLT:
  334. *reloc_addr = sym_val + addend;
  335. break;
  336. case REL_RELATIVE:
  337. *reloc_addr = (size_t)base + addend;
  338. break;
  339. case REL_SYM_OR_REL:
  340. if (sym) *reloc_addr = sym_val + addend;
  341. else *reloc_addr = (size_t)base + addend;
  342. break;
  343. case REL_COPY:
  344. memcpy(reloc_addr, (void *)sym_val, sym->st_size);
  345. break;
  346. case REL_OFFSET32:
  347. *(uint32_t *)reloc_addr = sym_val + addend
  348. - (size_t)reloc_addr;
  349. break;
  350. case REL_FUNCDESC:
  351. *reloc_addr = def.sym ? (size_t)(def.dso->funcdescs
  352. + (def.sym - def.dso->syms)) : 0;
  353. break;
  354. case REL_FUNCDESC_VAL:
  355. if ((sym->st_info&0xf) == STT_SECTION) *reloc_addr += sym_val;
  356. else *reloc_addr = sym_val;
  357. reloc_addr[1] = def.sym ? (size_t)def.dso->got : 0;
  358. break;
  359. case REL_DTPMOD:
  360. *reloc_addr = def.dso->tls_id;
  361. break;
  362. case REL_DTPOFF:
  363. *reloc_addr = tls_val + addend - DTP_OFFSET;
  364. break;
  365. #ifdef TLS_ABOVE_TP
  366. case REL_TPOFF:
  367. *reloc_addr = tls_val + def.dso->tls.offset + TPOFF_K + addend;
  368. break;
  369. #else
  370. case REL_TPOFF:
  371. *reloc_addr = tls_val - def.dso->tls.offset + addend;
  372. break;
  373. case REL_TPOFF_NEG:
  374. *reloc_addr = def.dso->tls.offset - tls_val + addend;
  375. break;
  376. #endif
  377. case REL_TLSDESC:
  378. if (stride<3) addend = reloc_addr[1];
  379. if (runtime && def.dso->tls_id >= static_tls_cnt) {
  380. struct td_index *new = malloc(sizeof *new);
  381. if (!new) {
  382. error(
  383. "Error relocating %s: cannot allocate TLSDESC for %s",
  384. dso->name, sym ? name : "(local)" );
  385. longjmp(*rtld_fail, 1);
  386. }
  387. new->next = dso->td_index;
  388. dso->td_index = new;
  389. new->args[0] = def.dso->tls_id;
  390. new->args[1] = tls_val + addend;
  391. reloc_addr[0] = (size_t)__tlsdesc_dynamic;
  392. reloc_addr[1] = (size_t)new;
  393. } else {
  394. reloc_addr[0] = (size_t)__tlsdesc_static;
  395. #ifdef TLS_ABOVE_TP
  396. reloc_addr[1] = tls_val + def.dso->tls.offset
  397. + TPOFF_K + addend;
  398. #else
  399. reloc_addr[1] = tls_val - def.dso->tls.offset
  400. + addend;
  401. #endif
  402. }
  403. break;
  404. default:
  405. error("Error relocating %s: unsupported relocation type %d",
  406. dso->name, type);
  407. if (runtime) longjmp(*rtld_fail, 1);
  408. continue;
  409. }
  410. }
  411. }
  412. /* A huge hack: to make up for the wastefulness of shared libraries
  413. * needing at least a page of dirty memory even if they have no global
  414. * data, we reclaim the gaps at the beginning and end of writable maps
  415. * and "donate" them to the heap by setting up minimal malloc
  416. * structures and then freeing them. */
  417. static void reclaim(struct dso *dso, size_t start, size_t end)
  418. {
  419. size_t *a, *z;
  420. if (start >= dso->relro_start && start < dso->relro_end) start = dso->relro_end;
  421. if (end >= dso->relro_start && end < dso->relro_end) end = dso->relro_start;
  422. start = start + 6*sizeof(size_t)-1 & -4*sizeof(size_t);
  423. end = (end & -4*sizeof(size_t)) - 2*sizeof(size_t);
  424. if (start>end || end-start < 4*sizeof(size_t)) return;
  425. a = laddr(dso, start);
  426. z = laddr(dso, end);
  427. a[-2] = 1;
  428. a[-1] = z[0] = end-start + 2*sizeof(size_t) | 1;
  429. z[1] = 1;
  430. free(a);
  431. }
  432. static void reclaim_gaps(struct dso *dso)
  433. {
  434. Phdr *ph = dso->phdr;
  435. size_t phcnt = dso->phnum;
  436. if (DL_FDPIC) return; // FIXME
  437. for (; phcnt--; ph=(void *)((char *)ph+dso->phentsize)) {
  438. if (ph->p_type!=PT_LOAD) continue;
  439. if ((ph->p_flags&(PF_R|PF_W))!=(PF_R|PF_W)) continue;
  440. reclaim(dso, ph->p_vaddr & -PAGE_SIZE, ph->p_vaddr);
  441. reclaim(dso, ph->p_vaddr+ph->p_memsz,
  442. ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE);
  443. }
  444. }
  445. static void *mmap_fixed(void *p, size_t n, int prot, int flags, int fd, off_t off)
  446. {
  447. static int no_map_fixed;
  448. char *q;
  449. if (!no_map_fixed) {
  450. q = mmap(p, n, prot, flags|MAP_FIXED, fd, off);
  451. if (!DL_NOMMU_SUPPORT || q != MAP_FAILED || errno != EINVAL)
  452. return q;
  453. no_map_fixed = 1;
  454. }
  455. /* Fallbacks for MAP_FIXED failure on NOMMU kernels. */
  456. if (flags & MAP_ANONYMOUS) {
  457. memset(p, 0, n);
  458. return p;
  459. }
  460. ssize_t r;
  461. if (lseek(fd, off, SEEK_SET) < 0) return MAP_FAILED;
  462. for (q=p; n; q+=r, off+=r, n-=r) {
  463. r = read(fd, q, n);
  464. if (r < 0 && errno != EINTR) return MAP_FAILED;
  465. if (!r) {
  466. memset(q, 0, n);
  467. break;
  468. }
  469. }
  470. return p;
  471. }
  472. static void unmap_library(struct dso *dso)
  473. {
  474. if (dso->loadmap) {
  475. size_t i;
  476. for (i=0; i<dso->loadmap->nsegs; i++) {
  477. if (!dso->loadmap->segs[i].p_memsz)
  478. continue;
  479. munmap((void *)dso->loadmap->segs[i].addr,
  480. dso->loadmap->segs[i].p_memsz);
  481. }
  482. free(dso->loadmap);
  483. } else if (dso->map && dso->map_len) {
  484. munmap(dso->map, dso->map_len);
  485. }
  486. }
  487. static void *map_library(int fd, struct dso *dso)
  488. {
  489. Ehdr buf[(896+sizeof(Ehdr))/sizeof(Ehdr)];
  490. void *allocated_buf=0;
  491. size_t phsize;
  492. size_t addr_min=SIZE_MAX, addr_max=0, map_len;
  493. size_t this_min, this_max;
  494. size_t nsegs = 0;
  495. off_t off_start;
  496. Ehdr *eh;
  497. Phdr *ph, *ph0;
  498. unsigned prot;
  499. unsigned char *map=MAP_FAILED, *base;
  500. size_t dyn=0;
  501. size_t tls_image=0;
  502. size_t i;
  503. ssize_t l = read(fd, buf, sizeof buf);
  504. eh = buf;
  505. if (l<0) return 0;
  506. if (l<sizeof *eh || (eh->e_type != ET_DYN && eh->e_type != ET_EXEC))
  507. goto noexec;
  508. phsize = eh->e_phentsize * eh->e_phnum;
  509. if (phsize > sizeof buf - sizeof *eh) {
  510. allocated_buf = malloc(phsize);
  511. if (!allocated_buf) return 0;
  512. l = pread(fd, allocated_buf, phsize, eh->e_phoff);
  513. if (l < 0) goto error;
  514. if (l != phsize) goto noexec;
  515. ph = ph0 = allocated_buf;
  516. } else if (eh->e_phoff + phsize > l) {
  517. l = pread(fd, buf+1, phsize, eh->e_phoff);
  518. if (l < 0) goto error;
  519. if (l != phsize) goto noexec;
  520. ph = ph0 = (void *)(buf + 1);
  521. } else {
  522. ph = ph0 = (void *)((char *)buf + eh->e_phoff);
  523. }
  524. for (i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
  525. if (ph->p_type == PT_DYNAMIC) {
  526. dyn = ph->p_vaddr;
  527. } else if (ph->p_type == PT_TLS) {
  528. tls_image = ph->p_vaddr;
  529. dso->tls.align = ph->p_align;
  530. dso->tls.len = ph->p_filesz;
  531. dso->tls.size = ph->p_memsz;
  532. } else if (ph->p_type == PT_GNU_RELRO) {
  533. dso->relro_start = ph->p_vaddr & -PAGE_SIZE;
  534. dso->relro_end = (ph->p_vaddr + ph->p_memsz) & -PAGE_SIZE;
  535. }
  536. if (ph->p_type != PT_LOAD) continue;
  537. nsegs++;
  538. if (ph->p_vaddr < addr_min) {
  539. addr_min = ph->p_vaddr;
  540. off_start = ph->p_offset;
  541. prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
  542. ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
  543. ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
  544. }
  545. if (ph->p_vaddr+ph->p_memsz > addr_max) {
  546. addr_max = ph->p_vaddr+ph->p_memsz;
  547. }
  548. }
  549. if (!dyn) goto noexec;
  550. if (DL_FDPIC && !(eh->e_flags & FDPIC_CONSTDISP_FLAG)) {
  551. dso->loadmap = calloc(1, sizeof *dso->loadmap
  552. + nsegs * sizeof *dso->loadmap->segs);
  553. if (!dso->loadmap) goto error;
  554. dso->loadmap->nsegs = nsegs;
  555. for (ph=ph0, i=0; i<nsegs; ph=(void *)((char *)ph+eh->e_phentsize)) {
  556. if (ph->p_type != PT_LOAD) continue;
  557. prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
  558. ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
  559. ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
  560. map = mmap(0, ph->p_memsz + (ph->p_vaddr & PAGE_SIZE-1),
  561. prot, MAP_PRIVATE,
  562. fd, ph->p_offset & -PAGE_SIZE);
  563. if (map == MAP_FAILED) {
  564. unmap_library(dso);
  565. goto error;
  566. }
  567. dso->loadmap->segs[i].addr = (size_t)map +
  568. (ph->p_vaddr & PAGE_SIZE-1);
  569. dso->loadmap->segs[i].p_vaddr = ph->p_vaddr;
  570. dso->loadmap->segs[i].p_memsz = ph->p_memsz;
  571. i++;
  572. if (prot & PROT_WRITE) {
  573. size_t brk = (ph->p_vaddr & PAGE_SIZE-1)
  574. + ph->p_filesz;
  575. size_t pgbrk = brk + PAGE_SIZE-1 & -PAGE_SIZE;
  576. size_t pgend = brk + ph->p_memsz - ph->p_filesz
  577. + PAGE_SIZE-1 & -PAGE_SIZE;
  578. if (pgend > pgbrk && mmap_fixed(map+pgbrk,
  579. pgend-pgbrk, prot,
  580. MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS,
  581. -1, off_start) == MAP_FAILED)
  582. goto error;
  583. memset(map + brk, 0, pgbrk-brk);
  584. }
  585. }
  586. map = (void *)dso->loadmap->segs[0].addr;
  587. map_len = 0;
  588. goto done_mapping;
  589. }
  590. addr_max += PAGE_SIZE-1;
  591. addr_max &= -PAGE_SIZE;
  592. addr_min &= -PAGE_SIZE;
  593. off_start &= -PAGE_SIZE;
  594. map_len = addr_max - addr_min + off_start;
  595. /* The first time, we map too much, possibly even more than
  596. * the length of the file. This is okay because we will not
  597. * use the invalid part; we just need to reserve the right
  598. * amount of virtual address space to map over later. */
  599. map = DL_NOMMU_SUPPORT
  600. ? mmap((void *)addr_min, map_len, PROT_READ|PROT_WRITE|PROT_EXEC,
  601. MAP_PRIVATE|MAP_ANONYMOUS, -1, 0)
  602. : mmap((void *)addr_min, map_len, prot,
  603. MAP_PRIVATE, fd, off_start);
  604. if (map==MAP_FAILED) goto error;
  605. dso->map = map;
  606. dso->map_len = map_len;
  607. /* If the loaded file is not relocatable and the requested address is
  608. * not available, then the load operation must fail. */
  609. if (eh->e_type != ET_DYN && addr_min && map!=(void *)addr_min) {
  610. errno = EBUSY;
  611. goto error;
  612. }
  613. base = map - addr_min;
  614. dso->phdr = 0;
  615. dso->phnum = 0;
  616. for (ph=ph0, i=eh->e_phnum; i; i--, ph=(void *)((char *)ph+eh->e_phentsize)) {
  617. if (ph->p_type != PT_LOAD) continue;
  618. /* Check if the programs headers are in this load segment, and
  619. * if so, record the address for use by dl_iterate_phdr. */
  620. if (!dso->phdr && eh->e_phoff >= ph->p_offset
  621. && eh->e_phoff+phsize <= ph->p_offset+ph->p_filesz) {
  622. dso->phdr = (void *)(base + ph->p_vaddr
  623. + (eh->e_phoff-ph->p_offset));
  624. dso->phnum = eh->e_phnum;
  625. dso->phentsize = eh->e_phentsize;
  626. }
  627. /* Reuse the existing mapping for the lowest-address LOAD */
  628. if ((ph->p_vaddr & -PAGE_SIZE) == addr_min && !DL_NOMMU_SUPPORT)
  629. continue;
  630. this_min = ph->p_vaddr & -PAGE_SIZE;
  631. this_max = ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE;
  632. off_start = ph->p_offset & -PAGE_SIZE;
  633. prot = (((ph->p_flags&PF_R) ? PROT_READ : 0) |
  634. ((ph->p_flags&PF_W) ? PROT_WRITE: 0) |
  635. ((ph->p_flags&PF_X) ? PROT_EXEC : 0));
  636. if (mmap_fixed(base+this_min, this_max-this_min, prot, MAP_PRIVATE|MAP_FIXED, fd, off_start) == MAP_FAILED)
  637. goto error;
  638. if (ph->p_memsz > ph->p_filesz) {
  639. size_t brk = (size_t)base+ph->p_vaddr+ph->p_filesz;
  640. size_t pgbrk = brk+PAGE_SIZE-1 & -PAGE_SIZE;
  641. memset((void *)brk, 0, pgbrk-brk & PAGE_SIZE-1);
  642. if (pgbrk-(size_t)base < this_max && mmap_fixed((void *)pgbrk, (size_t)base+this_max-pgbrk, prot, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) == MAP_FAILED)
  643. goto error;
  644. }
  645. }
  646. for (i=0; ((size_t *)(base+dyn))[i]; i+=2)
  647. if (((size_t *)(base+dyn))[i]==DT_TEXTREL) {
  648. if (mprotect(map, map_len, PROT_READ|PROT_WRITE|PROT_EXEC)
  649. && errno != ENOSYS)
  650. goto error;
  651. break;
  652. }
  653. done_mapping:
  654. dso->base = base;
  655. dso->dynv = laddr(dso, dyn);
  656. if (dso->tls.size) dso->tls.image = laddr(dso, tls_image);
  657. if (!runtime) reclaim_gaps(dso);
  658. free(allocated_buf);
  659. return map;
  660. noexec:
  661. errno = ENOEXEC;
  662. error:
  663. if (map!=MAP_FAILED) unmap_library(dso);
  664. free(allocated_buf);
  665. return 0;
  666. }
  667. static int path_open(const char *name, const char *s, char *buf, size_t buf_size)
  668. {
  669. size_t l;
  670. int fd;
  671. for (;;) {
  672. s += strspn(s, ":\n");
  673. l = strcspn(s, ":\n");
  674. if (l-1 >= INT_MAX) return -1;
  675. if (snprintf(buf, buf_size, "%.*s/%s", (int)l, s, name) < buf_size) {
  676. if ((fd = open(buf, O_RDONLY|O_CLOEXEC))>=0) return fd;
  677. switch (errno) {
  678. case ENOENT:
  679. case ENOTDIR:
  680. case EACCES:
  681. case ENAMETOOLONG:
  682. break;
  683. default:
  684. /* Any negative value but -1 will inhibit
  685. * futher path search. */
  686. return -2;
  687. }
  688. }
  689. s += l;
  690. }
  691. }
  692. static int fixup_rpath(struct dso *p, char *buf, size_t buf_size)
  693. {
  694. size_t n, l;
  695. const char *s, *t, *origin;
  696. char *d;
  697. if (p->rpath || !p->rpath_orig) return 0;
  698. if (!strchr(p->rpath_orig, '$')) {
  699. p->rpath = p->rpath_orig;
  700. return 0;
  701. }
  702. n = 0;
  703. s = p->rpath_orig;
  704. while ((t=strchr(s, '$'))) {
  705. if (strncmp(t, "$ORIGIN", 7) && strncmp(t, "${ORIGIN}", 9))
  706. return 0;
  707. s = t+1;
  708. n++;
  709. }
  710. if (n > SSIZE_MAX/PATH_MAX) return 0;
  711. if (p->kernel_mapped) {
  712. /* $ORIGIN searches cannot be performed for the main program
  713. * when it is suid/sgid/AT_SECURE. This is because the
  714. * pathname is under the control of the caller of execve.
  715. * For libraries, however, $ORIGIN can be processed safely
  716. * since the library's pathname came from a trusted source
  717. * (either system paths or a call to dlopen). */
  718. if (libc.secure)
  719. return 0;
  720. l = readlink("/proc/self/exe", buf, buf_size);
  721. if (l == -1) switch (errno) {
  722. case ENOENT:
  723. case ENOTDIR:
  724. case EACCES:
  725. break;
  726. default:
  727. return -1;
  728. }
  729. if (l >= buf_size)
  730. return 0;
  731. buf[l] = 0;
  732. origin = buf;
  733. } else {
  734. origin = p->name;
  735. }
  736. t = strrchr(origin, '/');
  737. l = t ? t-origin : 0;
  738. p->rpath = malloc(strlen(p->rpath_orig) + n*l + 1);
  739. if (!p->rpath) return -1;
  740. d = p->rpath;
  741. s = p->rpath_orig;
  742. while ((t=strchr(s, '$'))) {
  743. memcpy(d, s, t-s);
  744. d += t-s;
  745. memcpy(d, origin, l);
  746. d += l;
  747. /* It was determined previously that the '$' is followed
  748. * either by "ORIGIN" or "{ORIGIN}". */
  749. s = t + 7 + 2*(t[1]=='{');
  750. }
  751. strcpy(d, s);
  752. return 0;
  753. }
  754. static void decode_dyn(struct dso *p)
  755. {
  756. size_t dyn[DYN_CNT];
  757. decode_vec(p->dynv, dyn, DYN_CNT);
  758. p->syms = laddr(p, dyn[DT_SYMTAB]);
  759. p->strings = laddr(p, dyn[DT_STRTAB]);
  760. if (dyn[0]&(1<<DT_HASH))
  761. p->hashtab = laddr(p, dyn[DT_HASH]);
  762. if (dyn[0]&(1<<DT_RPATH))
  763. p->rpath_orig = p->strings + dyn[DT_RPATH];
  764. if (dyn[0]&(1<<DT_RUNPATH))
  765. p->rpath_orig = p->strings + dyn[DT_RUNPATH];
  766. if (dyn[0]&(1<<DT_PLTGOT))
  767. p->got = laddr(p, dyn[DT_PLTGOT]);
  768. if (search_vec(p->dynv, dyn, DT_GNU_HASH))
  769. p->ghashtab = laddr(p, *dyn);
  770. if (search_vec(p->dynv, dyn, DT_VERSYM))
  771. p->versym = laddr(p, *dyn);
  772. }
  773. static size_t count_syms(struct dso *p)
  774. {
  775. if (p->hashtab) return p->hashtab[1];
  776. size_t nsym, i;
  777. uint32_t *buckets = p->ghashtab + 4 + (p->ghashtab[2]*sizeof(size_t)/4);
  778. uint32_t *hashval;
  779. for (i = nsym = 0; i < p->ghashtab[0]; i++) {
  780. if (buckets[i] > nsym)
  781. nsym = buckets[i];
  782. }
  783. if (nsym) {
  784. hashval = buckets + p->ghashtab[0] + (nsym - p->ghashtab[1]);
  785. do nsym++;
  786. while (!(*hashval++ & 1));
  787. }
  788. return nsym;
  789. }
  790. static void *dl_mmap(size_t n)
  791. {
  792. void *p;
  793. int prot = PROT_READ|PROT_WRITE, flags = MAP_ANONYMOUS|MAP_PRIVATE;
  794. #ifdef SYS_mmap2
  795. p = (void *)__syscall(SYS_mmap2, 0, n, prot, flags, -1, 0);
  796. #else
  797. p = (void *)__syscall(SYS_mmap, 0, n, prot, flags, -1, 0);
  798. #endif
  799. return p == MAP_FAILED ? 0 : p;
  800. }
  801. static void makefuncdescs(struct dso *p)
  802. {
  803. static int self_done;
  804. size_t nsym = count_syms(p);
  805. size_t i, size = nsym * sizeof(*p->funcdescs);
  806. if (!self_done) {
  807. p->funcdescs = dl_mmap(size);
  808. self_done = 1;
  809. } else {
  810. p->funcdescs = malloc(size);
  811. }
  812. if (!p->funcdescs) {
  813. if (!runtime) a_crash();
  814. error("Error allocating function descriptors for %s", p->name);
  815. longjmp(*rtld_fail, 1);
  816. }
  817. for (i=0; i<nsym; i++) {
  818. if ((p->syms[i].st_info&0xf)==STT_FUNC && p->syms[i].st_shndx) {
  819. p->funcdescs[i].addr = laddr(p, p->syms[i].st_value);
  820. p->funcdescs[i].got = p->got;
  821. } else {
  822. p->funcdescs[i].addr = 0;
  823. p->funcdescs[i].got = 0;
  824. }
  825. }
  826. }
  827. static struct dso *load_library(const char *name, struct dso *needed_by)
  828. {
  829. char buf[2*NAME_MAX+2];
  830. const char *pathname;
  831. unsigned char *map;
  832. struct dso *p, temp_dso = {0};
  833. int fd;
  834. struct stat st;
  835. size_t alloc_size;
  836. int n_th = 0;
  837. int is_self = 0;
  838. if (!*name) {
  839. errno = EINVAL;
  840. return 0;
  841. }
  842. /* Catch and block attempts to reload the implementation itself */
  843. if (name[0]=='l' && name[1]=='i' && name[2]=='b') {
  844. static const char reserved[] =
  845. "c.pthread.rt.m.dl.util.xnet.";
  846. const char *rp, *next;
  847. for (rp=reserved; *rp; rp=next) {
  848. next = strchr(rp, '.') + 1;
  849. if (strncmp(name+3, rp, next-rp) == 0)
  850. break;
  851. }
  852. if (*rp) {
  853. if (ldd_mode) {
  854. /* Track which names have been resolved
  855. * and only report each one once. */
  856. static unsigned reported;
  857. unsigned mask = 1U<<(rp-reserved);
  858. if (!(reported & mask)) {
  859. reported |= mask;
  860. dprintf(1, "\t%s => %s (%p)\n",
  861. name, ldso.name,
  862. ldso.base);
  863. }
  864. }
  865. is_self = 1;
  866. }
  867. }
  868. if (!strcmp(name, ldso.name)) is_self = 1;
  869. if (is_self) {
  870. if (!ldso.prev) {
  871. tail->next = &ldso;
  872. ldso.prev = tail;
  873. tail = ldso.next ? ldso.next : &ldso;
  874. }
  875. return &ldso;
  876. }
  877. if (strchr(name, '/')) {
  878. pathname = name;
  879. fd = open(name, O_RDONLY|O_CLOEXEC);
  880. } else {
  881. /* Search for the name to see if it's already loaded */
  882. for (p=head->next; p; p=p->next) {
  883. if (p->shortname && !strcmp(p->shortname, name)) {
  884. p->refcnt++;
  885. return p;
  886. }
  887. }
  888. if (strlen(name) > NAME_MAX) return 0;
  889. fd = -1;
  890. if (env_path) fd = path_open(name, env_path, buf, sizeof buf);
  891. for (p=needed_by; fd == -1 && p; p=p->needed_by) {
  892. if (fixup_rpath(p, buf, sizeof buf) < 0)
  893. fd = -2; /* Inhibit further search. */
  894. if (p->rpath)
  895. fd = path_open(name, p->rpath, buf, sizeof buf);
  896. }
  897. if (fd == -1) {
  898. if (!sys_path) {
  899. char *prefix = 0;
  900. size_t prefix_len;
  901. if (ldso.name[0]=='/') {
  902. char *s, *t, *z;
  903. for (s=t=z=ldso.name; *s; s++)
  904. if (*s=='/') z=t, t=s;
  905. prefix_len = z-ldso.name;
  906. if (prefix_len < PATH_MAX)
  907. prefix = ldso.name;
  908. }
  909. if (!prefix) {
  910. prefix = "";
  911. prefix_len = 0;
  912. }
  913. char etc_ldso_path[prefix_len + 1
  914. + sizeof "/etc/ld-musl-" LDSO_ARCH ".path"];
  915. snprintf(etc_ldso_path, sizeof etc_ldso_path,
  916. "%.*s/etc/ld-musl-" LDSO_ARCH ".path",
  917. (int)prefix_len, prefix);
  918. FILE *f = fopen(etc_ldso_path, "rbe");
  919. if (f) {
  920. if (getdelim(&sys_path, (size_t[1]){0}, 0, f) <= 0) {
  921. free(sys_path);
  922. sys_path = "";
  923. }
  924. fclose(f);
  925. } else if (errno != ENOENT) {
  926. sys_path = "";
  927. }
  928. }
  929. if (!sys_path) sys_path = "/lib:/usr/local/lib:/usr/lib";
  930. fd = path_open(name, sys_path, buf, sizeof buf);
  931. }
  932. pathname = buf;
  933. }
  934. if (fd < 0) return 0;
  935. if (fstat(fd, &st) < 0) {
  936. close(fd);
  937. return 0;
  938. }
  939. for (p=head->next; p; p=p->next) {
  940. if (p->dev == st.st_dev && p->ino == st.st_ino) {
  941. /* If this library was previously loaded with a
  942. * pathname but a search found the same inode,
  943. * setup its shortname so it can be found by name. */
  944. if (!p->shortname && pathname != name)
  945. p->shortname = strrchr(p->name, '/')+1;
  946. close(fd);
  947. p->refcnt++;
  948. return p;
  949. }
  950. }
  951. map = noload ? 0 : map_library(fd, &temp_dso);
  952. close(fd);
  953. if (!map) return 0;
  954. /* Allocate storage for the new DSO. When there is TLS, this
  955. * storage must include a reservation for all pre-existing
  956. * threads to obtain copies of both the new TLS, and an
  957. * extended DTV capable of storing an additional slot for
  958. * the newly-loaded DSO. */
  959. alloc_size = sizeof *p + strlen(pathname) + 1;
  960. if (runtime && temp_dso.tls.image) {
  961. size_t per_th = temp_dso.tls.size + temp_dso.tls.align
  962. + sizeof(void *) * (tls_cnt+3);
  963. n_th = libc.threads_minus_1 + 1;
  964. if (n_th > SSIZE_MAX / per_th) alloc_size = SIZE_MAX;
  965. else alloc_size += n_th * per_th;
  966. }
  967. p = calloc(1, alloc_size);
  968. if (!p) {
  969. unmap_library(&temp_dso);
  970. return 0;
  971. }
  972. memcpy(p, &temp_dso, sizeof temp_dso);
  973. decode_dyn(p);
  974. p->dev = st.st_dev;
  975. p->ino = st.st_ino;
  976. p->refcnt = 1;
  977. p->needed_by = needed_by;
  978. p->name = p->buf;
  979. strcpy(p->name, pathname);
  980. /* Add a shortname only if name arg was not an explicit pathname. */
  981. if (pathname != name) p->shortname = strrchr(p->name, '/')+1;
  982. if (p->tls.image) {
  983. p->tls_id = ++tls_cnt;
  984. tls_align = MAXP2(tls_align, p->tls.align);
  985. #ifdef TLS_ABOVE_TP
  986. p->tls.offset = tls_offset + ( (tls_align-1) &
  987. -(tls_offset + (uintptr_t)p->tls.image) );
  988. tls_offset += p->tls.size;
  989. #else
  990. tls_offset += p->tls.size + p->tls.align - 1;
  991. tls_offset -= (tls_offset + (uintptr_t)p->tls.image)
  992. & (p->tls.align-1);
  993. p->tls.offset = tls_offset;
  994. #endif
  995. p->new_dtv = (void *)(-sizeof(size_t) &
  996. (uintptr_t)(p->name+strlen(p->name)+sizeof(size_t)));
  997. p->new_tls = (void *)(p->new_dtv + n_th*(tls_cnt+1));
  998. if (tls_tail) tls_tail->next = &p->tls;
  999. else libc.tls_head = &p->tls;
  1000. tls_tail = &p->tls;
  1001. }
  1002. tail->next = p;
  1003. p->prev = tail;
  1004. tail = p;
  1005. if (DL_FDPIC) makefuncdescs(p);
  1006. if (ldd_mode) dprintf(1, "\t%s => %s (%p)\n", name, pathname, p->base);
  1007. return p;
  1008. }
  1009. static void load_deps(struct dso *p)
  1010. {
  1011. size_t i, ndeps=0;
  1012. struct dso ***deps = &p->deps, **tmp, *dep;
  1013. for (; p; p=p->next) {
  1014. for (i=0; p->dynv[i]; i+=2) {
  1015. if (p->dynv[i] != DT_NEEDED) continue;
  1016. dep = load_library(p->strings + p->dynv[i+1], p);
  1017. if (!dep) {
  1018. error("Error loading shared library %s: %m (needed by %s)",
  1019. p->strings + p->dynv[i+1], p->name);
  1020. if (runtime) longjmp(*rtld_fail, 1);
  1021. continue;
  1022. }
  1023. if (runtime) {
  1024. tmp = realloc(*deps, sizeof(*tmp)*(ndeps+2));
  1025. if (!tmp) longjmp(*rtld_fail, 1);
  1026. tmp[ndeps++] = dep;
  1027. tmp[ndeps] = 0;
  1028. *deps = tmp;
  1029. }
  1030. }
  1031. }
  1032. }
  1033. static void load_preload(char *s)
  1034. {
  1035. int tmp;
  1036. char *z;
  1037. for (z=s; *z; s=z) {
  1038. for ( ; *s && (isspace(*s) || *s==':'); s++);
  1039. for (z=s; *z && !isspace(*z) && *z!=':'; z++);
  1040. tmp = *z;
  1041. *z = 0;
  1042. load_library(s, 0);
  1043. *z = tmp;
  1044. }
  1045. }
  1046. static void make_global(struct dso *p)
  1047. {
  1048. for (; p; p=p->next) p->global = 1;
  1049. }
  1050. static void do_mips_relocs(struct dso *p, size_t *got)
  1051. {
  1052. size_t i, j, rel[2];
  1053. unsigned char *base = p->base;
  1054. i=0; search_vec(p->dynv, &i, DT_MIPS_LOCAL_GOTNO);
  1055. if (p==&ldso) {
  1056. got += i;
  1057. } else {
  1058. while (i--) *got++ += (size_t)base;
  1059. }
  1060. j=0; search_vec(p->dynv, &j, DT_MIPS_GOTSYM);
  1061. i=0; search_vec(p->dynv, &i, DT_MIPS_SYMTABNO);
  1062. Sym *sym = p->syms + j;
  1063. rel[0] = (unsigned char *)got - base;
  1064. for (i-=j; i; i--, sym++, rel[0]+=sizeof(size_t)) {
  1065. rel[1] = R_INFO(sym-p->syms, R_MIPS_JUMP_SLOT);
  1066. do_relocs(p, rel, sizeof rel, 2);
  1067. }
  1068. }
  1069. static void reloc_all(struct dso *p)
  1070. {
  1071. size_t dyn[DYN_CNT];
  1072. for (; p; p=p->next) {
  1073. if (p->relocated) continue;
  1074. decode_vec(p->dynv, dyn, DYN_CNT);
  1075. if (NEED_MIPS_GOT_RELOCS)
  1076. do_mips_relocs(p, laddr(p, dyn[DT_PLTGOT]));
  1077. do_relocs(p, laddr(p, dyn[DT_JMPREL]), dyn[DT_PLTRELSZ],
  1078. 2+(dyn[DT_PLTREL]==DT_RELA));
  1079. do_relocs(p, laddr(p, dyn[DT_REL]), dyn[DT_RELSZ], 2);
  1080. do_relocs(p, laddr(p, dyn[DT_RELA]), dyn[DT_RELASZ], 3);
  1081. if (head != &ldso && p->relro_start != p->relro_end &&
  1082. mprotect(laddr(p, p->relro_start), p->relro_end-p->relro_start, PROT_READ)
  1083. && errno != ENOSYS) {
  1084. error("Error relocating %s: RELRO protection failed: %m",
  1085. p->name);
  1086. if (runtime) longjmp(*rtld_fail, 1);
  1087. }
  1088. p->relocated = 1;
  1089. }
  1090. }
  1091. static void kernel_mapped_dso(struct dso *p)
  1092. {
  1093. size_t min_addr = -1, max_addr = 0, cnt;
  1094. Phdr *ph = p->phdr;
  1095. for (cnt = p->phnum; cnt--; ph = (void *)((char *)ph + p->phentsize)) {
  1096. if (ph->p_type == PT_DYNAMIC) {
  1097. p->dynv = laddr(p, ph->p_vaddr);
  1098. } else if (ph->p_type == PT_GNU_RELRO) {
  1099. p->relro_start = ph->p_vaddr & -PAGE_SIZE;
  1100. p->relro_end = (ph->p_vaddr + ph->p_memsz) & -PAGE_SIZE;
  1101. }
  1102. if (ph->p_type != PT_LOAD) continue;
  1103. if (ph->p_vaddr < min_addr)
  1104. min_addr = ph->p_vaddr;
  1105. if (ph->p_vaddr+ph->p_memsz > max_addr)
  1106. max_addr = ph->p_vaddr+ph->p_memsz;
  1107. }
  1108. min_addr &= -PAGE_SIZE;
  1109. max_addr = (max_addr + PAGE_SIZE-1) & -PAGE_SIZE;
  1110. p->map = p->base + min_addr;
  1111. p->map_len = max_addr - min_addr;
  1112. p->kernel_mapped = 1;
  1113. }
  1114. void __libc_exit_fini()
  1115. {
  1116. struct dso *p;
  1117. size_t dyn[DYN_CNT];
  1118. for (p=fini_head; p; p=p->fini_next) {
  1119. if (!p->constructed) continue;
  1120. decode_vec(p->dynv, dyn, DYN_CNT);
  1121. if (dyn[0] & (1<<DT_FINI_ARRAY)) {
  1122. size_t n = dyn[DT_FINI_ARRAYSZ]/sizeof(size_t);
  1123. size_t *fn = (size_t *)laddr(p, dyn[DT_FINI_ARRAY])+n;
  1124. while (n--) ((void (*)(void))*--fn)();
  1125. }
  1126. #ifndef NO_LEGACY_INITFINI
  1127. if ((dyn[0] & (1<<DT_FINI)) && dyn[DT_FINI])
  1128. fpaddr(p, dyn[DT_FINI])();
  1129. #endif
  1130. }
  1131. }
  1132. static void do_init_fini(struct dso *p)
  1133. {
  1134. size_t dyn[DYN_CNT];
  1135. int need_locking = libc.threads_minus_1;
  1136. /* Allow recursive calls that arise when a library calls
  1137. * dlopen from one of its constructors, but block any
  1138. * other threads until all ctors have finished. */
  1139. if (need_locking) pthread_mutex_lock(&init_fini_lock);
  1140. for (; p; p=p->prev) {
  1141. if (p->constructed) continue;
  1142. p->constructed = 1;
  1143. decode_vec(p->dynv, dyn, DYN_CNT);
  1144. if (dyn[0] & ((1<<DT_FINI) | (1<<DT_FINI_ARRAY))) {
  1145. p->fini_next = fini_head;
  1146. fini_head = p;
  1147. }
  1148. #ifndef NO_LEGACY_INITFINI
  1149. if ((dyn[0] & (1<<DT_INIT)) && dyn[DT_INIT])
  1150. fpaddr(p, dyn[DT_INIT])();
  1151. #endif
  1152. if (dyn[0] & (1<<DT_INIT_ARRAY)) {
  1153. size_t n = dyn[DT_INIT_ARRAYSZ]/sizeof(size_t);
  1154. size_t *fn = laddr(p, dyn[DT_INIT_ARRAY]);
  1155. while (n--) ((void (*)(void))*fn++)();
  1156. }
  1157. if (!need_locking && libc.threads_minus_1) {
  1158. need_locking = 1;
  1159. pthread_mutex_lock(&init_fini_lock);
  1160. }
  1161. }
  1162. if (need_locking) pthread_mutex_unlock(&init_fini_lock);
  1163. }
  1164. void __libc_start_init(void)
  1165. {
  1166. do_init_fini(tail);
  1167. }
  1168. static void dl_debug_state(void)
  1169. {
  1170. }
  1171. weak_alias(dl_debug_state, _dl_debug_state);
  1172. void __init_tls(size_t *auxv)
  1173. {
  1174. }
  1175. __attribute__((__visibility__("hidden")))
  1176. void *__tls_get_new(tls_mod_off_t *v)
  1177. {
  1178. pthread_t self = __pthread_self();
  1179. /* Block signals to make accessing new TLS async-signal-safe */
  1180. sigset_t set;
  1181. __block_all_sigs(&set);
  1182. if (v[0]<=(size_t)self->dtv[0]) {
  1183. __restore_sigs(&set);
  1184. return (char *)self->dtv[v[0]]+v[1]+DTP_OFFSET;
  1185. }
  1186. /* This is safe without any locks held because, if the caller
  1187. * is able to request the Nth entry of the DTV, the DSO list
  1188. * must be valid at least that far out and it was synchronized
  1189. * at program startup or by an already-completed call to dlopen. */
  1190. struct dso *p;
  1191. for (p=head; p->tls_id != v[0]; p=p->next);
  1192. /* Get new DTV space from new DSO if needed */
  1193. if (v[0] > (size_t)self->dtv[0]) {
  1194. void **newdtv = p->new_dtv +
  1195. (v[0]+1)*a_fetch_add(&p->new_dtv_idx,1);
  1196. memcpy(newdtv, self->dtv,
  1197. ((size_t)self->dtv[0]+1) * sizeof(void *));
  1198. newdtv[0] = (void *)v[0];
  1199. self->dtv = self->dtv_copy = newdtv;
  1200. }
  1201. /* Get new TLS memory from all new DSOs up to the requested one */
  1202. unsigned char *mem;
  1203. for (p=head; ; p=p->next) {
  1204. if (!p->tls_id || self->dtv[p->tls_id]) continue;
  1205. mem = p->new_tls + (p->tls.size + p->tls.align)
  1206. * a_fetch_add(&p->new_tls_idx,1);
  1207. mem += ((uintptr_t)p->tls.image - (uintptr_t)mem)
  1208. & (p->tls.align-1);
  1209. self->dtv[p->tls_id] = mem;
  1210. memcpy(mem, p->tls.image, p->tls.len);
  1211. if (p->tls_id == v[0]) break;
  1212. }
  1213. __restore_sigs(&set);
  1214. return mem + v[1] + DTP_OFFSET;
  1215. }
  1216. static void update_tls_size()
  1217. {
  1218. libc.tls_cnt = tls_cnt;
  1219. libc.tls_align = tls_align;
  1220. libc.tls_size = ALIGN(
  1221. (1+tls_cnt) * sizeof(void *) +
  1222. tls_offset +
  1223. sizeof(struct pthread) +
  1224. tls_align * 2,
  1225. tls_align);
  1226. }
  1227. /* Stage 1 of the dynamic linker is defined in dlstart.c. It calls the
  1228. * following stage 2 and stage 3 functions via primitive symbolic lookup
  1229. * since it does not have access to their addresses to begin with. */
  1230. /* Stage 2 of the dynamic linker is called after relative relocations
  1231. * have been processed. It can make function calls to static functions
  1232. * and access string literals and static data, but cannot use extern
  1233. * symbols. Its job is to perform symbolic relocations on the dynamic
  1234. * linker itself, but some of the relocations performed may need to be
  1235. * replaced later due to copy relocations in the main program. */
  1236. __attribute__((__visibility__("hidden")))
  1237. void __dls2(unsigned char *base, size_t *sp)
  1238. {
  1239. if (DL_FDPIC) {
  1240. void *p1 = (void *)sp[-2];
  1241. void *p2 = (void *)sp[-1];
  1242. if (!p1) {
  1243. size_t *auxv, aux[AUX_CNT];
  1244. for (auxv=sp+1+*sp+1; *auxv; auxv++); auxv++;
  1245. decode_vec(auxv, aux, AUX_CNT);
  1246. if (aux[AT_BASE]) ldso.base = (void *)aux[AT_BASE];
  1247. else ldso.base = (void *)(aux[AT_PHDR] & -4096);
  1248. }
  1249. app_loadmap = p2 ? p1 : 0;
  1250. ldso.loadmap = p2 ? p2 : p1;
  1251. ldso.base = laddr(&ldso, 0);
  1252. } else {
  1253. ldso.base = base;
  1254. }
  1255. Ehdr *ehdr = (void *)ldso.base;
  1256. ldso.name = ldso.shortname = "libc.so";
  1257. ldso.global = 1;
  1258. ldso.phnum = ehdr->e_phnum;
  1259. ldso.phdr = laddr(&ldso, ehdr->e_phoff);
  1260. ldso.phentsize = ehdr->e_phentsize;
  1261. kernel_mapped_dso(&ldso);
  1262. decode_dyn(&ldso);
  1263. if (DL_FDPIC) makefuncdescs(&ldso);
  1264. /* Prepare storage for to save clobbered REL addends so they
  1265. * can be reused in stage 3. There should be very few. If
  1266. * something goes wrong and there are a huge number, abort
  1267. * instead of risking stack overflow. */
  1268. size_t dyn[DYN_CNT];
  1269. decode_vec(ldso.dynv, dyn, DYN_CNT);
  1270. size_t *rel = laddr(&ldso, dyn[DT_REL]);
  1271. size_t rel_size = dyn[DT_RELSZ];
  1272. size_t symbolic_rel_cnt = 0;
  1273. apply_addends_to = rel;
  1274. for (; rel_size; rel+=2, rel_size-=2*sizeof(size_t))
  1275. if (!IS_RELATIVE(rel[1], ldso.syms)) symbolic_rel_cnt++;
  1276. if (symbolic_rel_cnt >= ADDEND_LIMIT) a_crash();
  1277. size_t addends[symbolic_rel_cnt+1];
  1278. saved_addends = addends;
  1279. head = &ldso;
  1280. reloc_all(&ldso);
  1281. ldso.relocated = 0;
  1282. /* Call dynamic linker stage-3, __dls3, looking it up
  1283. * symbolically as a barrier against moving the address
  1284. * load across the above relocation processing. */
  1285. struct symdef dls3_def = find_sym(&ldso, "__dls3", 0);
  1286. if (DL_FDPIC) ((stage3_func)&ldso.funcdescs[dls3_def.sym-ldso.syms])(sp);
  1287. else ((stage3_func)laddr(&ldso, dls3_def.sym->st_value))(sp);
  1288. }
  1289. /* Stage 3 of the dynamic linker is called with the dynamic linker/libc
  1290. * fully functional. Its job is to load (if not already loaded) and
  1291. * process dependencies and relocations for the main application and
  1292. * transfer control to its entry point. */
  1293. _Noreturn void __dls3(size_t *sp)
  1294. {
  1295. static struct dso app, vdso;
  1296. size_t aux[AUX_CNT], *auxv;
  1297. size_t i;
  1298. char *env_preload=0;
  1299. size_t vdso_base;
  1300. int argc = *sp;
  1301. char **argv = (void *)(sp+1);
  1302. char **argv_orig = argv;
  1303. char **envp = argv+argc+1;
  1304. /* Find aux vector just past environ[] and use it to initialize
  1305. * global data that may be needed before we can make syscalls. */
  1306. __environ = envp;
  1307. for (i=argc+1; argv[i]; i++);
  1308. libc.auxv = auxv = (void *)(argv+i+1);
  1309. decode_vec(auxv, aux, AUX_CNT);
  1310. __hwcap = aux[AT_HWCAP];
  1311. libc.page_size = aux[AT_PAGESZ];
  1312. libc.secure = ((aux[0]&0x7800)!=0x7800 || aux[AT_UID]!=aux[AT_EUID]
  1313. || aux[AT_GID]!=aux[AT_EGID] || aux[AT_SECURE]);
  1314. /* Setup early thread pointer in builtin_tls for ldso/libc itself to
  1315. * use during dynamic linking. If possible it will also serve as the
  1316. * thread pointer at runtime. */
  1317. libc.tls_size = sizeof builtin_tls;
  1318. libc.tls_align = tls_align;
  1319. if (__init_tp(__copy_tls((void *)builtin_tls)) < 0) {
  1320. a_crash();
  1321. }
  1322. /* Only trust user/env if kernel says we're not suid/sgid */
  1323. if (!libc.secure) {
  1324. env_path = getenv("LD_LIBRARY_PATH");
  1325. env_preload = getenv("LD_PRELOAD");
  1326. }
  1327. /* If the main program was already loaded by the kernel,
  1328. * AT_PHDR will point to some location other than the dynamic
  1329. * linker's program headers. */
  1330. if (aux[AT_PHDR] != (size_t)ldso.phdr) {
  1331. size_t interp_off = 0;
  1332. size_t tls_image = 0;
  1333. /* Find load address of the main program, via AT_PHDR vs PT_PHDR. */
  1334. Phdr *phdr = app.phdr = (void *)aux[AT_PHDR];
  1335. app.phnum = aux[AT_PHNUM];
  1336. app.phentsize = aux[AT_PHENT];
  1337. for (i=aux[AT_PHNUM]; i; i--, phdr=(void *)((char *)phdr + aux[AT_PHENT])) {
  1338. if (phdr->p_type == PT_PHDR)
  1339. app.base = (void *)(aux[AT_PHDR] - phdr->p_vaddr);
  1340. else if (phdr->p_type == PT_INTERP)
  1341. interp_off = (size_t)phdr->p_vaddr;
  1342. else if (phdr->p_type == PT_TLS) {
  1343. tls_image = phdr->p_vaddr;
  1344. app.tls.len = phdr->p_filesz;
  1345. app.tls.size = phdr->p_memsz;
  1346. app.tls.align = phdr->p_align;
  1347. }
  1348. }
  1349. if (DL_FDPIC) app.loadmap = app_loadmap;
  1350. if (app.tls.size) app.tls.image = laddr(&app, tls_image);
  1351. if (interp_off) ldso.name = laddr(&app, interp_off);
  1352. if ((aux[0] & (1UL<<AT_EXECFN))
  1353. && strncmp((char *)aux[AT_EXECFN], "/proc/", 6))
  1354. app.name = (char *)aux[AT_EXECFN];
  1355. else
  1356. app.name = argv[0];
  1357. kernel_mapped_dso(&app);
  1358. } else {
  1359. int fd;
  1360. char *ldname = argv[0];
  1361. size_t l = strlen(ldname);
  1362. if (l >= 3 && !strcmp(ldname+l-3, "ldd")) ldd_mode = 1;
  1363. argv++;
  1364. while (argv[0] && argv[0][0]=='-' && argv[0][1]=='-') {
  1365. char *opt = argv[0]+2;
  1366. *argv++ = (void *)-1;
  1367. if (!*opt) {
  1368. break;
  1369. } else if (!memcmp(opt, "list", 5)) {
  1370. ldd_mode = 1;
  1371. } else if (!memcmp(opt, "library-path", 12)) {
  1372. if (opt[12]=='=') env_path = opt+13;
  1373. else if (opt[12]) *argv = 0;
  1374. else if (*argv) env_path = *argv++;
  1375. } else if (!memcmp(opt, "preload", 7)) {
  1376. if (opt[7]=='=') env_preload = opt+8;
  1377. else if (opt[7]) *argv = 0;
  1378. else if (*argv) env_preload = *argv++;
  1379. } else {
  1380. argv[0] = 0;
  1381. }
  1382. }
  1383. argv[-1] = (void *)(argc - (argv-argv_orig));
  1384. if (!argv[0]) {
  1385. dprintf(2, "musl libc (" LDSO_ARCH ")\n"
  1386. "Version %s\n"
  1387. "Dynamic Program Loader\n"
  1388. "Usage: %s [options] [--] pathname%s\n",
  1389. __libc_get_version(), ldname,
  1390. ldd_mode ? "" : " [args]");
  1391. _exit(1);
  1392. }
  1393. fd = open(argv[0], O_RDONLY);
  1394. if (fd < 0) {
  1395. dprintf(2, "%s: cannot load %s: %s\n", ldname, argv[0], strerror(errno));
  1396. _exit(1);
  1397. }
  1398. runtime = 1;
  1399. Ehdr *ehdr = (void *)map_library(fd, &app);
  1400. if (!ehdr) {
  1401. dprintf(2, "%s: %s: Not a valid dynamic program\n", ldname, argv[0]);
  1402. _exit(1);
  1403. }
  1404. runtime = 0;
  1405. close(fd);
  1406. ldso.name = ldname;
  1407. app.name = argv[0];
  1408. aux[AT_ENTRY] = (size_t)laddr(&app, ehdr->e_entry);
  1409. /* Find the name that would have been used for the dynamic
  1410. * linker had ldd not taken its place. */
  1411. if (ldd_mode) {
  1412. for (i=0; i<app.phnum; i++) {
  1413. if (app.phdr[i].p_type == PT_INTERP)
  1414. ldso.name = laddr(&app, app.phdr[i].p_vaddr);
  1415. }
  1416. dprintf(1, "\t%s (%p)\n", ldso.name, ldso.base);
  1417. }
  1418. }
  1419. if (app.tls.size) {
  1420. libc.tls_head = tls_tail = &app.tls;
  1421. app.tls_id = tls_cnt = 1;
  1422. #ifdef TLS_ABOVE_TP
  1423. app.tls.offset = 0;
  1424. tls_offset = app.tls.size
  1425. + ( -((uintptr_t)app.tls.image + app.tls.size)
  1426. & (app.tls.align-1) );
  1427. #else
  1428. tls_offset = app.tls.offset = app.tls.size
  1429. + ( -((uintptr_t)app.tls.image + app.tls.size)
  1430. & (app.tls.align-1) );
  1431. #endif
  1432. tls_align = MAXP2(tls_align, app.tls.align);
  1433. }
  1434. app.global = 1;
  1435. decode_dyn(&app);
  1436. if (DL_FDPIC) {
  1437. makefuncdescs(&app);
  1438. if (!app.loadmap) {
  1439. app.loadmap = (void *)&app_dummy_loadmap;
  1440. app.loadmap->nsegs = 1;
  1441. app.loadmap->segs[0].addr = (size_t)app.map;
  1442. app.loadmap->segs[0].p_vaddr = (size_t)app.map
  1443. - (size_t)app.base;
  1444. app.loadmap->segs[0].p_memsz = app.map_len;
  1445. }
  1446. argv[-3] = (void *)app.loadmap;
  1447. }
  1448. /* Attach to vdso, if provided by the kernel */
  1449. if (search_vec(auxv, &vdso_base, AT_SYSINFO_EHDR) && vdso_base) {
  1450. Ehdr *ehdr = (void *)vdso_base;
  1451. Phdr *phdr = vdso.phdr = (void *)(vdso_base + ehdr->e_phoff);
  1452. vdso.phnum = ehdr->e_phnum;
  1453. vdso.phentsize = ehdr->e_phentsize;
  1454. for (i=ehdr->e_phnum; i; i--, phdr=(void *)((char *)phdr + ehdr->e_phentsize)) {
  1455. if (phdr->p_type == PT_DYNAMIC)
  1456. vdso.dynv = (void *)(vdso_base + phdr->p_offset);
  1457. if (phdr->p_type == PT_LOAD)
  1458. vdso.base = (void *)(vdso_base - phdr->p_vaddr + phdr->p_offset);
  1459. }
  1460. vdso.name = "";
  1461. vdso.shortname = "linux-gate.so.1";
  1462. vdso.global = 1;
  1463. vdso.relocated = 1;
  1464. decode_dyn(&vdso);
  1465. vdso.prev = &ldso;
  1466. ldso.next = &vdso;
  1467. }
  1468. /* Initial dso chain consists only of the app. */
  1469. head = tail = &app;
  1470. /* Donate unused parts of app and library mapping to malloc */
  1471. reclaim_gaps(&app);
  1472. reclaim_gaps(&ldso);
  1473. /* Load preload/needed libraries, add their symbols to the global
  1474. * namespace, and perform all remaining relocations. */
  1475. if (env_preload) load_preload(env_preload);
  1476. load_deps(&app);
  1477. make_global(&app);
  1478. for (i=0; app.dynv[i]; i+=2) {
  1479. if (!DT_DEBUG_INDIRECT && app.dynv[i]==DT_DEBUG)
  1480. app.dynv[i+1] = (size_t)&debug;
  1481. if (DT_DEBUG_INDIRECT && app.dynv[i]==DT_DEBUG_INDIRECT) {
  1482. size_t *ptr = (size_t *) app.dynv[i+1];
  1483. *ptr = (size_t)&debug;
  1484. }
  1485. }
  1486. /* The main program must be relocated LAST since it may contin
  1487. * copy relocations which depend on libraries' relocations. */
  1488. reloc_all(app.next);
  1489. reloc_all(&app);
  1490. update_tls_size();
  1491. if (libc.tls_size > sizeof builtin_tls || tls_align > MIN_TLS_ALIGN) {
  1492. void *initial_tls = calloc(libc.tls_size, 1);
  1493. if (!initial_tls) {
  1494. dprintf(2, "%s: Error getting %zu bytes thread-local storage: %m\n",
  1495. argv[0], libc.tls_size);
  1496. _exit(127);
  1497. }
  1498. if (__init_tp(__copy_tls(initial_tls)) < 0) {
  1499. a_crash();
  1500. }
  1501. } else {
  1502. size_t tmp_tls_size = libc.tls_size;
  1503. pthread_t self = __pthread_self();
  1504. /* Temporarily set the tls size to the full size of
  1505. * builtin_tls so that __copy_tls will use the same layout
  1506. * as it did for before. Then check, just to be safe. */
  1507. libc.tls_size = sizeof builtin_tls;
  1508. if (__copy_tls((void*)builtin_tls) != self) a_crash();
  1509. libc.tls_size = tmp_tls_size;
  1510. }
  1511. static_tls_cnt = tls_cnt;
  1512. if (ldso_fail) _exit(127);
  1513. if (ldd_mode) _exit(0);
  1514. /* Switch to runtime mode: any further failures in the dynamic
  1515. * linker are a reportable failure rather than a fatal startup
  1516. * error. */
  1517. runtime = 1;
  1518. debug.ver = 1;
  1519. debug.bp = dl_debug_state;
  1520. debug.head = head;
  1521. debug.base = ldso.base;
  1522. debug.state = 0;
  1523. _dl_debug_state();
  1524. errno = 0;
  1525. CRTJMP((void *)aux[AT_ENTRY], argv-1);
  1526. for(;;);
  1527. }
  1528. void *dlopen(const char *file, int mode)
  1529. {
  1530. struct dso *volatile p, *orig_tail, *next;
  1531. struct tls_module *orig_tls_tail;
  1532. size_t orig_tls_cnt, orig_tls_offset, orig_tls_align;
  1533. size_t i;
  1534. int cs;
  1535. jmp_buf jb;
  1536. if (!file) return head;
  1537. pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
  1538. pthread_rwlock_wrlock(&lock);
  1539. __inhibit_ptc();
  1540. p = 0;
  1541. orig_tls_tail = tls_tail;
  1542. orig_tls_cnt = tls_cnt;
  1543. orig_tls_offset = tls_offset;
  1544. orig_tls_align = tls_align;
  1545. orig_tail = tail;
  1546. noload = mode & RTLD_NOLOAD;
  1547. rtld_fail = &jb;
  1548. if (setjmp(*rtld_fail)) {
  1549. /* Clean up anything new that was (partially) loaded */
  1550. if (p && p->deps) for (i=0; p->deps[i]; i++)
  1551. if (p->deps[i]->global < 0)
  1552. p->deps[i]->global = 0;
  1553. for (p=orig_tail->next; p; p=next) {
  1554. next = p->next;
  1555. while (p->td_index) {
  1556. void *tmp = p->td_index->next;
  1557. free(p->td_index);
  1558. p->td_index = tmp;
  1559. }
  1560. free(p->funcdescs);
  1561. if (p->rpath != p->rpath_orig)
  1562. free(p->rpath);
  1563. free(p->deps);
  1564. unmap_library(p);
  1565. free(p);
  1566. }
  1567. if (!orig_tls_tail) libc.tls_head = 0;
  1568. tls_tail = orig_tls_tail;
  1569. if (tls_tail) tls_tail->next = 0;
  1570. tls_cnt = orig_tls_cnt;
  1571. tls_offset = orig_tls_offset;
  1572. tls_align = orig_tls_align;
  1573. tail = orig_tail;
  1574. tail->next = 0;
  1575. p = 0;
  1576. goto end;
  1577. } else p = load_library(file, head);
  1578. if (!p) {
  1579. error(noload ?
  1580. "Library %s is not already loaded" :
  1581. "Error loading shared library %s: %m",
  1582. file);
  1583. goto end;
  1584. }
  1585. /* First load handling */
  1586. if (!p->deps) {
  1587. load_deps(p);
  1588. if (p->deps) for (i=0; p->deps[i]; i++)
  1589. if (!p->deps[i]->global)
  1590. p->deps[i]->global = -1;
  1591. if (!p->global) p->global = -1;
  1592. reloc_all(p);
  1593. if (p->deps) for (i=0; p->deps[i]; i++)
  1594. if (p->deps[i]->global < 0)
  1595. p->deps[i]->global = 0;
  1596. if (p->global < 0) p->global = 0;
  1597. }
  1598. if (mode & RTLD_GLOBAL) {
  1599. if (p->deps) for (i=0; p->deps[i]; i++)
  1600. p->deps[i]->global = 1;
  1601. p->global = 1;
  1602. }
  1603. update_tls_size();
  1604. _dl_debug_state();
  1605. orig_tail = tail;
  1606. end:
  1607. __release_ptc();
  1608. if (p) gencnt++;
  1609. pthread_rwlock_unlock(&lock);
  1610. if (p) do_init_fini(orig_tail);
  1611. pthread_setcancelstate(cs, 0);
  1612. return p;
  1613. }
  1614. __attribute__((__visibility__("hidden")))
  1615. int __dl_invalid_handle(void *h)
  1616. {
  1617. struct dso *p;
  1618. for (p=head; p; p=p->next) if (h==p) return 0;
  1619. error("Invalid library handle %p", (void *)h);
  1620. return 1;
  1621. }
  1622. static void *addr2dso(size_t a)
  1623. {
  1624. struct dso *p;
  1625. size_t i;
  1626. if (DL_FDPIC) for (p=head; p; p=p->next) {
  1627. i = count_syms(p);
  1628. if (a-(size_t)p->funcdescs < i*sizeof(*p->funcdescs))
  1629. return p;
  1630. }
  1631. for (p=head; p; p=p->next) {
  1632. if (DL_FDPIC && p->loadmap) {
  1633. for (i=0; i<p->loadmap->nsegs; i++) {
  1634. if (a-p->loadmap->segs[i].p_vaddr
  1635. < p->loadmap->segs[i].p_memsz)
  1636. return p;
  1637. }
  1638. } else {
  1639. if (a-(size_t)p->map < p->map_len)
  1640. return p;
  1641. }
  1642. }
  1643. return 0;
  1644. }
  1645. void *__tls_get_addr(tls_mod_off_t *);
  1646. static void *do_dlsym(struct dso *p, const char *s, void *ra)
  1647. {
  1648. size_t i;
  1649. uint32_t h = 0, gh = 0, *ght;
  1650. Sym *sym;
  1651. if (p == head || p == RTLD_DEFAULT || p == RTLD_NEXT) {
  1652. if (p == RTLD_DEFAULT) {
  1653. p = head;
  1654. } else if (p == RTLD_NEXT) {
  1655. p = addr2dso((size_t)ra);
  1656. if (!p) p=head;
  1657. p = p->next;
  1658. }
  1659. struct symdef def = find_sym(p, s, 0);
  1660. if (!def.sym) goto failed;
  1661. if ((def.sym->st_info&0xf) == STT_TLS)
  1662. return __tls_get_addr((tls_mod_off_t []){def.dso->tls_id, def.sym->st_value});
  1663. if (DL_FDPIC && (def.sym->st_info&0xf) == STT_FUNC)
  1664. return def.dso->funcdescs + (def.sym - def.dso->syms);
  1665. return laddr(def.dso, def.sym->st_value);
  1666. }
  1667. if (__dl_invalid_handle(p))
  1668. return 0;
  1669. if ((ght = p->ghashtab)) {
  1670. gh = gnu_hash(s);
  1671. sym = gnu_lookup(gh, ght, p, s);
  1672. } else {
  1673. h = sysv_hash(s);
  1674. sym = sysv_lookup(s, h, p);
  1675. }
  1676. if (sym && (sym->st_info&0xf) == STT_TLS)
  1677. return __tls_get_addr((tls_mod_off_t []){p->tls_id, sym->st_value});
  1678. if (DL_FDPIC && sym && sym->st_shndx && (sym->st_info&0xf) == STT_FUNC)
  1679. return p->funcdescs + (sym - p->syms);
  1680. if (sym && sym->st_value && (1<<(sym->st_info&0xf) & OK_TYPES))
  1681. return laddr(p, sym->st_value);
  1682. if (p->deps) for (i=0; p->deps[i]; i++) {
  1683. if ((ght = p->deps[i]->ghashtab)) {
  1684. if (!gh) gh = gnu_hash(s);
  1685. sym = gnu_lookup(gh, ght, p->deps[i], s);
  1686. } else {
  1687. if (!h) h = sysv_hash(s);
  1688. sym = sysv_lookup(s, h, p->deps[i]);
  1689. }
  1690. if (sym && (sym->st_info&0xf) == STT_TLS)
  1691. return __tls_get_addr((tls_mod_off_t []){p->deps[i]->tls_id, sym->st_value});
  1692. if (DL_FDPIC && sym && sym->st_shndx && (sym->st_info&0xf) == STT_FUNC)
  1693. return p->deps[i]->funcdescs + (sym - p->deps[i]->syms);
  1694. if (sym && sym->st_value && (1<<(sym->st_info&0xf) & OK_TYPES))
  1695. return laddr(p->deps[i], sym->st_value);
  1696. }
  1697. failed:
  1698. error("Symbol not found: %s", s);
  1699. return 0;
  1700. }
  1701. int dladdr(const void *addr, Dl_info *info)
  1702. {
  1703. struct dso *p;
  1704. Sym *sym, *bestsym;
  1705. uint32_t nsym;
  1706. char *strings;
  1707. void *best = 0;
  1708. pthread_rwlock_rdlock(&lock);
  1709. p = addr2dso((size_t)addr);
  1710. pthread_rwlock_unlock(&lock);
  1711. if (!p) return 0;
  1712. sym = p->syms;
  1713. strings = p->strings;
  1714. nsym = count_syms(p);
  1715. if (DL_FDPIC) {
  1716. size_t idx = ((size_t)addr-(size_t)p->funcdescs)
  1717. / sizeof(*p->funcdescs);
  1718. if (idx < nsym && (sym[idx].st_info&0xf) == STT_FUNC) {
  1719. best = p->funcdescs + idx;
  1720. bestsym = sym + idx;
  1721. }
  1722. }
  1723. if (!best) for (; nsym; nsym--, sym++) {
  1724. if (sym->st_value
  1725. && (1<<(sym->st_info&0xf) & OK_TYPES)
  1726. && (1<<(sym->st_info>>4) & OK_BINDS)) {
  1727. void *symaddr = laddr(p, sym->st_value);
  1728. if (symaddr > addr || symaddr < best)
  1729. continue;
  1730. best = symaddr;
  1731. bestsym = sym;
  1732. if (addr == symaddr)
  1733. break;
  1734. }
  1735. }
  1736. if (!best) return 0;
  1737. if (DL_FDPIC && (bestsym->st_info&0xf) == STT_FUNC)
  1738. best = p->funcdescs + (bestsym - p->syms);
  1739. info->dli_fname = p->name;
  1740. info->dli_fbase = p->base;
  1741. info->dli_sname = strings + bestsym->st_name;
  1742. info->dli_saddr = best;
  1743. return 1;
  1744. }
  1745. __attribute__((__visibility__("hidden")))
  1746. void *__dlsym(void *restrict p, const char *restrict s, void *restrict ra)
  1747. {
  1748. void *res;
  1749. pthread_rwlock_rdlock(&lock);
  1750. res = do_dlsym(p, s, ra);
  1751. pthread_rwlock_unlock(&lock);
  1752. return res;
  1753. }
  1754. int dl_iterate_phdr(int(*callback)(struct dl_phdr_info *info, size_t size, void *data), void *data)
  1755. {
  1756. struct dso *current;
  1757. struct dl_phdr_info info;
  1758. int ret = 0;
  1759. for(current = head; current;) {
  1760. info.dlpi_addr = (uintptr_t)current->base;
  1761. info.dlpi_name = current->name;
  1762. info.dlpi_phdr = current->phdr;
  1763. info.dlpi_phnum = current->phnum;
  1764. info.dlpi_adds = gencnt;
  1765. info.dlpi_subs = 0;
  1766. info.dlpi_tls_modid = current->tls_id;
  1767. info.dlpi_tls_data = current->tls.image;
  1768. ret = (callback)(&info, sizeof (info), data);
  1769. if (ret != 0) break;
  1770. pthread_rwlock_rdlock(&lock);
  1771. current = current->next;
  1772. pthread_rwlock_unlock(&lock);
  1773. }
  1774. return ret;
  1775. }
  1776. __attribute__((__visibility__("hidden")))
  1777. void __dl_vseterr(const char *, va_list);
  1778. static void error(const char *fmt, ...)
  1779. {
  1780. va_list ap;
  1781. va_start(ap, fmt);
  1782. if (!runtime) {
  1783. vdprintf(2, fmt, ap);
  1784. dprintf(2, "\n");
  1785. ldso_fail = 1;
  1786. va_end(ap);
  1787. return;
  1788. }
  1789. __dl_vseterr(fmt, ap);
  1790. va_end(ap);
  1791. }