dynlink.c 55 KB

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