dynlink.c 62 KB

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