dynlink.c 64 KB

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