dynlink.c 66 KB

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