dynlink.c 53 KB

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