dynlink.c 64 KB

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