dynlink.c 62 KB

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