1
0

dynlink.c 56 KB

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