dynlink.c 56 KB

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