dynlink.c 54 KB

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