dynlink.c 56 KB

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