]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - libexec/rtld-elf/map_object.c
MFC r365360, r365370:
[FreeBSD/FreeBSD.git] / libexec / rtld-elf / map_object.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright 1996-1998 John D. Polstra.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  *
27  * $FreeBSD$
28  */
29
30 #include <sys/param.h>
31 #include <sys/mman.h>
32 #include <sys/stat.h>
33
34 #include <errno.h>
35 #include <stddef.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <unistd.h>
39
40 #include "debug.h"
41 #include "rtld.h"
42
43 static Elf_Ehdr *get_elf_header(int, const char *, const struct stat *,
44     Elf_Phdr **phdr);
45 static int convert_flags(int); /* Elf flags -> mmap flags */
46
47 int __getosreldate(void);
48
49 static bool
50 phdr_in_zero_page(const Elf_Ehdr *hdr)
51 {
52         return (hdr->e_phoff + hdr->e_phnum * sizeof(Elf_Phdr) <=
53             (size_t)PAGE_SIZE);
54 }
55
56 /*
57  * Map a shared object into memory.  The "fd" argument is a file descriptor,
58  * which must be open on the object and positioned at its beginning.
59  * The "path" argument is a pathname that is used only for error messages.
60  *
61  * The return value is a pointer to a newly-allocated Obj_Entry structure
62  * for the shared object.  Returns NULL on failure.
63  */
64 Obj_Entry *
65 map_object(int fd, const char *path, const struct stat *sb)
66 {
67     Obj_Entry *obj;
68     Elf_Ehdr *hdr;
69     int i;
70     Elf_Phdr *phdr;
71     Elf_Phdr *phlimit;
72     Elf_Phdr **segs;
73     int nsegs;
74     Elf_Phdr *phdyn;
75     Elf_Phdr *phinterp;
76     Elf_Phdr *phtls;
77     caddr_t mapbase;
78     size_t mapsize;
79     Elf_Addr base_vaddr;
80     Elf_Addr base_vlimit;
81     caddr_t base_addr;
82     int base_flags;
83     Elf_Off data_offset;
84     Elf_Addr data_vaddr;
85     Elf_Addr data_vlimit;
86     caddr_t data_addr;
87     int data_prot;
88     int data_flags;
89     Elf_Addr clear_vaddr;
90     caddr_t clear_addr;
91     caddr_t clear_page;
92     Elf_Addr phdr_vaddr;
93     size_t nclear, phsize;
94     Elf_Addr bss_vaddr;
95     Elf_Addr bss_vlimit;
96     caddr_t bss_addr;
97     Elf_Word stack_flags;
98     Elf_Addr relro_page;
99     size_t relro_size;
100     Elf_Addr note_start;
101     Elf_Addr note_end;
102     char *note_map;
103     size_t note_map_len;
104
105     hdr = get_elf_header(fd, path, sb, &phdr);
106     if (hdr == NULL)
107         return (NULL);
108
109     /*
110      * Scan the program header entries, and save key information.
111      * We expect that the loadable segments are ordered by load address.
112      */
113     phsize  = hdr->e_phnum * sizeof(phdr[0]);
114     phlimit = phdr + hdr->e_phnum;
115     nsegs = -1;
116     phdyn = phinterp = phtls = NULL;
117     phdr_vaddr = 0;
118     relro_page = 0;
119     relro_size = 0;
120     note_start = 0;
121     note_end = 0;
122     note_map = NULL;
123     note_map_len = 0;
124     segs = alloca(sizeof(segs[0]) * hdr->e_phnum);
125     stack_flags = RTLD_DEFAULT_STACK_PF_EXEC | PF_R | PF_W;
126     while (phdr < phlimit) {
127         switch (phdr->p_type) {
128
129         case PT_INTERP:
130             phinterp = phdr;
131             break;
132
133         case PT_LOAD:
134             segs[++nsegs] = phdr;
135             if ((segs[nsegs]->p_align & (PAGE_SIZE - 1)) != 0) {
136                 _rtld_error("%s: PT_LOAD segment %d not page-aligned",
137                     path, nsegs);
138                 goto error;
139             }
140             break;
141
142         case PT_PHDR:
143             phdr_vaddr = phdr->p_vaddr;
144             phsize = phdr->p_memsz;
145             break;
146
147         case PT_DYNAMIC:
148             phdyn = phdr;
149             break;
150
151         case PT_TLS:
152             phtls = phdr;
153             break;
154
155         case PT_GNU_STACK:
156             stack_flags = phdr->p_flags;
157             break;
158
159         case PT_GNU_RELRO:
160             relro_page = phdr->p_vaddr;
161             relro_size = phdr->p_memsz;
162             break;
163
164         case PT_NOTE:
165             if (phdr->p_offset > PAGE_SIZE ||
166               phdr->p_offset + phdr->p_filesz > PAGE_SIZE) {
167                 note_map_len = round_page(phdr->p_offset +
168                   phdr->p_filesz) - trunc_page(phdr->p_offset);
169                 note_map = mmap(NULL, note_map_len, PROT_READ,
170                   MAP_PRIVATE, fd, trunc_page(phdr->p_offset));
171                 if (note_map == MAP_FAILED) {
172                     _rtld_error("%s: error mapping PT_NOTE (%d)", path, errno);
173                     goto error;
174                 }
175                 note_start = (Elf_Addr)(note_map + phdr->p_offset -
176                   trunc_page(phdr->p_offset));
177             } else {
178                 note_start = (Elf_Addr)(char *)hdr + phdr->p_offset;
179             }
180             note_end = note_start + phdr->p_filesz;
181             break;
182         }
183
184         ++phdr;
185     }
186     if (phdyn == NULL) {
187         _rtld_error("%s: object is not dynamically-linked", path);
188         goto error;
189     }
190
191     if (nsegs < 0) {
192         _rtld_error("%s: too few PT_LOAD segments", path);
193         goto error;
194     }
195
196     /*
197      * Map the entire address space of the object, to stake out our
198      * contiguous region, and to establish the base address for relocation.
199      */
200     base_vaddr = trunc_page(segs[0]->p_vaddr);
201     base_vlimit = round_page(segs[nsegs]->p_vaddr + segs[nsegs]->p_memsz);
202     mapsize = base_vlimit - base_vaddr;
203     base_addr = (caddr_t) base_vaddr;
204     base_flags = __getosreldate() >= P_OSREL_MAP_GUARD ? MAP_GUARD :
205         MAP_PRIVATE | MAP_ANON | MAP_NOCORE;
206     if (npagesizes > 1 && round_page(segs[0]->p_filesz) >= pagesizes[1])
207         base_flags |= MAP_ALIGNED_SUPER;
208     if (base_vaddr != 0)
209         base_flags |= MAP_FIXED | MAP_EXCL;
210
211     mapbase = mmap(base_addr, mapsize, PROT_NONE, base_flags, -1, 0);
212     if (mapbase == MAP_FAILED) {
213         _rtld_error("%s: mmap of entire address space failed: %s",
214           path, rtld_strerror(errno));
215         goto error;
216     }
217     if (base_addr != NULL && mapbase != base_addr) {
218         _rtld_error("%s: mmap returned wrong address: wanted %p, got %p",
219           path, base_addr, mapbase);
220         goto error1;
221     }
222
223     for (i = 0; i <= nsegs; i++) {
224         /* Overlay the segment onto the proper region. */
225         data_offset = trunc_page(segs[i]->p_offset);
226         data_vaddr = trunc_page(segs[i]->p_vaddr);
227         data_vlimit = round_page(segs[i]->p_vaddr + segs[i]->p_filesz);
228         data_addr = mapbase + (data_vaddr - base_vaddr);
229         data_prot = convert_prot(segs[i]->p_flags);
230         data_flags = convert_flags(segs[i]->p_flags) | MAP_FIXED;
231         if (mmap(data_addr, data_vlimit - data_vaddr, data_prot,
232           data_flags | MAP_PREFAULT_READ, fd, data_offset) == (caddr_t) -1) {
233             _rtld_error("%s: mmap of data failed: %s", path,
234                 rtld_strerror(errno));
235             goto error1;
236         }
237
238         /* Do BSS setup */
239         if (segs[i]->p_filesz != segs[i]->p_memsz) {
240
241             /* Clear any BSS in the last page of the segment. */
242             clear_vaddr = segs[i]->p_vaddr + segs[i]->p_filesz;
243             clear_addr = mapbase + (clear_vaddr - base_vaddr);
244             clear_page = mapbase + (trunc_page(clear_vaddr) - base_vaddr);
245
246             if ((nclear = data_vlimit - clear_vaddr) > 0) {
247                 /* Make sure the end of the segment is writable */
248                 if ((data_prot & PROT_WRITE) == 0 && -1 ==
249                      mprotect(clear_page, PAGE_SIZE, data_prot|PROT_WRITE)) {
250                         _rtld_error("%s: mprotect failed: %s", path,
251                             rtld_strerror(errno));
252                         goto error1;
253                 }
254
255                 memset(clear_addr, 0, nclear);
256
257                 /* Reset the data protection back */
258                 if ((data_prot & PROT_WRITE) == 0)
259                     mprotect(clear_page, PAGE_SIZE, data_prot);
260             }
261
262             /* Overlay the BSS segment onto the proper region. */
263             bss_vaddr = data_vlimit;
264             bss_vlimit = round_page(segs[i]->p_vaddr + segs[i]->p_memsz);
265             bss_addr = mapbase +  (bss_vaddr - base_vaddr);
266             if (bss_vlimit > bss_vaddr) {       /* There is something to do */
267                 if (mmap(bss_addr, bss_vlimit - bss_vaddr, data_prot,
268                     data_flags | MAP_ANON, -1, 0) == MAP_FAILED) {
269                     _rtld_error("%s: mmap of bss failed: %s", path,
270                         rtld_strerror(errno));
271                     goto error1;
272                 }
273             }
274         }
275
276         if (phdr_vaddr == 0 && data_offset <= hdr->e_phoff &&
277           (data_vlimit - data_vaddr + data_offset) >=
278           (hdr->e_phoff + hdr->e_phnum * sizeof (Elf_Phdr))) {
279             phdr_vaddr = data_vaddr + hdr->e_phoff - data_offset;
280         }
281     }
282
283     obj = obj_new();
284     if (sb != NULL) {
285         obj->dev = sb->st_dev;
286         obj->ino = sb->st_ino;
287     }
288     obj->mapbase = mapbase;
289     obj->mapsize = mapsize;
290     obj->textsize = round_page(segs[0]->p_vaddr + segs[0]->p_memsz) -
291       base_vaddr;
292     obj->vaddrbase = base_vaddr;
293     obj->relocbase = mapbase - base_vaddr;
294     obj->dynamic = (const Elf_Dyn *)(obj->relocbase + phdyn->p_vaddr);
295     if (hdr->e_entry != 0)
296         obj->entry = (caddr_t)(obj->relocbase + hdr->e_entry);
297     if (phdr_vaddr != 0) {
298         obj->phdr = (const Elf_Phdr *)(obj->relocbase + phdr_vaddr);
299     } else {
300         obj->phdr = malloc(phsize);
301         if (obj->phdr == NULL) {
302             obj_free(obj);
303             _rtld_error("%s: cannot allocate program header", path);
304             goto error1;
305         }
306         memcpy(__DECONST(char *, obj->phdr), (char *)hdr + hdr->e_phoff, phsize);
307         obj->phdr_alloc = true;
308     }
309     obj->phsize = phsize;
310     if (phinterp != NULL)
311         obj->interp = (const char *)(obj->relocbase + phinterp->p_vaddr);
312     if (phtls != NULL) {
313         tls_dtv_generation++;
314         obj->tlsindex = ++tls_max_index;
315         obj->tlssize = phtls->p_memsz;
316         obj->tlsalign = phtls->p_align;
317         obj->tlspoffset = phtls->p_offset;
318         obj->tlsinitsize = phtls->p_filesz;
319         obj->tlsinit = mapbase + phtls->p_vaddr;
320     }
321     obj->stack_flags = stack_flags;
322     obj->relro_page = obj->relocbase + trunc_page(relro_page);
323     obj->relro_size = round_page(relro_size);
324     if (note_start < note_end)
325         digest_notes(obj, note_start, note_end);
326     if (note_map != NULL)
327         munmap(note_map, note_map_len);
328     munmap(hdr, PAGE_SIZE);
329     return (obj);
330
331 error1:
332     munmap(mapbase, mapsize);
333 error:
334     if (note_map != NULL && note_map != MAP_FAILED)
335         munmap(note_map, note_map_len);
336     if (!phdr_in_zero_page(hdr))
337         munmap(phdr, hdr->e_phnum * sizeof(phdr[0]));
338     munmap(hdr, PAGE_SIZE);
339     return (NULL);
340 }
341
342 static Elf_Ehdr *
343 get_elf_header(int fd, const char *path, const struct stat *sbp,
344     Elf_Phdr **phdr_p)
345 {
346         Elf_Ehdr *hdr;
347         Elf_Phdr *phdr;
348
349         /* Make sure file has enough data for the ELF header */
350         if (sbp != NULL && sbp->st_size < (off_t)sizeof(Elf_Ehdr)) {
351                 _rtld_error("%s: invalid file format", path);
352                 return (NULL);
353         }
354
355         hdr = mmap(NULL, PAGE_SIZE, PROT_READ, MAP_PRIVATE | MAP_PREFAULT_READ,
356             fd, 0);
357         if (hdr == MAP_FAILED) {
358                 _rtld_error("%s: read error: %s", path, rtld_strerror(errno));
359                 return (NULL);
360         }
361
362         /* Make sure the file is valid */
363         if (!IS_ELF(*hdr)) {
364                 _rtld_error("%s: invalid file format", path);
365                 goto error;
366         }
367         if (hdr->e_ident[EI_CLASS] != ELF_TARG_CLASS ||
368             hdr->e_ident[EI_DATA] != ELF_TARG_DATA) {
369                 _rtld_error("%s: unsupported file layout", path);
370                 goto error;
371         }
372         if (hdr->e_ident[EI_VERSION] != EV_CURRENT ||
373             hdr->e_version != EV_CURRENT) {
374                 _rtld_error("%s: unsupported file version", path);
375                 goto error;
376         }
377         if (hdr->e_type != ET_EXEC && hdr->e_type != ET_DYN) {
378                 _rtld_error("%s: unsupported file type", path);
379                 goto error;
380         }
381         if (hdr->e_machine != ELF_TARG_MACH) {
382                 _rtld_error("%s: unsupported machine", path);
383                 goto error;
384         }
385
386         /*
387          * We rely on the program header being in the first page.  This is
388          * not strictly required by the ABI specification, but it seems to
389          * always true in practice.  And, it simplifies things considerably.
390          */
391         if (hdr->e_phentsize != sizeof(Elf_Phdr)) {
392                 _rtld_error(
393             "%s: invalid shared object: e_phentsize != sizeof(Elf_Phdr)", path);
394                 goto error;
395         }
396         if (phdr_in_zero_page(hdr)) {
397                 phdr = (Elf_Phdr *)((char *)hdr + hdr->e_phoff);
398         } else {
399                 phdr = mmap(NULL, hdr->e_phnum * sizeof(phdr[0]),
400                     PROT_READ, MAP_PRIVATE | MAP_PREFAULT_READ, fd,
401                     hdr->e_phoff);
402                 if (phdr == MAP_FAILED) {
403                         _rtld_error("%s: error mapping phdr: %s", path,
404                             rtld_strerror(errno));
405                         goto error;
406                 }
407         }
408         *phdr_p = phdr;
409         return (hdr);
410
411 error:
412         munmap(hdr, PAGE_SIZE);
413         return (NULL);
414 }
415
416 void
417 obj_free(Obj_Entry *obj)
418 {
419     Objlist_Entry *elm;
420
421     if (obj->tls_done)
422         free_tls_offset(obj);
423     while (obj->needed != NULL) {
424         Needed_Entry *needed = obj->needed;
425         obj->needed = needed->next;
426         free(needed);
427     }
428     while (!STAILQ_EMPTY(&obj->names)) {
429         Name_Entry *entry = STAILQ_FIRST(&obj->names);
430         STAILQ_REMOVE_HEAD(&obj->names, link);
431         free(entry);
432     }
433     while (!STAILQ_EMPTY(&obj->dldags)) {
434         elm = STAILQ_FIRST(&obj->dldags);
435         STAILQ_REMOVE_HEAD(&obj->dldags, link);
436         free(elm);
437     }
438     while (!STAILQ_EMPTY(&obj->dagmembers)) {
439         elm = STAILQ_FIRST(&obj->dagmembers);
440         STAILQ_REMOVE_HEAD(&obj->dagmembers, link);
441         free(elm);
442     }
443     if (obj->vertab)
444         free(obj->vertab);
445     if (obj->origin_path)
446         free(obj->origin_path);
447     if (obj->z_origin)
448         free(__DECONST(void*, obj->rpath));
449     if (obj->priv)
450         free(obj->priv);
451     if (obj->path)
452         free(obj->path);
453     if (obj->phdr_alloc)
454         free(__DECONST(void *, obj->phdr));
455     free(obj);
456 }
457
458 Obj_Entry *
459 obj_new(void)
460 {
461     Obj_Entry *obj;
462
463     obj = CNEW(Obj_Entry);
464     STAILQ_INIT(&obj->dldags);
465     STAILQ_INIT(&obj->dagmembers);
466     STAILQ_INIT(&obj->names);
467     return obj;
468 }
469
470 /*
471  * Given a set of ELF protection flags, return the corresponding protection
472  * flags for MMAP.
473  */
474 int
475 convert_prot(int elfflags)
476 {
477     int prot = 0;
478     if (elfflags & PF_R)
479         prot |= PROT_READ;
480     if (elfflags & PF_W)
481         prot |= PROT_WRITE;
482     if (elfflags & PF_X)
483         prot |= PROT_EXEC;
484     return prot;
485 }
486
487 static int
488 convert_flags(int elfflags)
489 {
490     int flags = MAP_PRIVATE; /* All mappings are private */
491
492     /*
493      * Readonly mappings are marked "MAP_NOCORE", because they can be
494      * reconstructed by a debugger.
495      */
496     if (!(elfflags & PF_W))
497         flags |= MAP_NOCORE;
498     return flags;
499 }