dynlink.c 66 KB

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