dynlink.c 56 KB

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