1
0

dynlink.c 59 KB

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