dynlink.c 51 KB

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