dynlink.c 52 KB

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