dynlink.c 63 KB

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