dynlink.c 64 KB

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