dynlink.c 64 KB

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