dynlink.c 63 KB

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