1
0

dynlink.c 64 KB

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