dynlink.c 61 KB

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