dynlink.c 61 KB

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