dynlink.c 62 KB

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