dynlink.c 58 KB

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