dynlink.c 63 KB

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