1
0

dynlink.c 62 KB

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