dynlink.c 54 KB

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