dynlink.c 63 KB

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