dynlink.c 62 KB

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