dynlink.c 62 KB

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