1
0

dynlink.c 56 KB

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