dynlink.c 66 KB

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