dynlink.c 66 KB

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