1
0

dynlink.c 66 KB

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