dynlink.c 55 KB

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