dynlink.c 57 KB

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