dynlink.c 57 KB

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