1
0

dynlink.c 66 KB

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