dynlink.c 54 KB

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