]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - libexec/rtld-elf/map_object.c
rtld: Parse own phdr and notes.
[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 static int convert_flags(int); /* Elf flags -> mmap flags */
45
46 int __getosreldate(void);
47
48 /*
49  * Map a shared object into memory.  The "fd" argument is a file descriptor,
50  * which must be open on the object and positioned at its beginning.
51  * The "path" argument is a pathname that is used only for error messages.
52  *
53  * The return value is a pointer to a newly-allocated Obj_Entry structure
54  * for the shared object.  Returns NULL on failure.
55  */
56 Obj_Entry *
57 map_object(int fd, const char *path, const struct stat *sb)
58 {
59     Obj_Entry *obj;
60     Elf_Ehdr *hdr;
61     int i;
62     Elf_Phdr *phdr;
63     Elf_Phdr *phlimit;
64     Elf_Phdr **segs;
65     int nsegs;
66     Elf_Phdr *phdyn;
67     Elf_Phdr *phinterp;
68     Elf_Phdr *phtls;
69     caddr_t mapbase;
70     size_t mapsize;
71     Elf_Addr base_vaddr;
72     Elf_Addr base_vlimit;
73     caddr_t base_addr;
74     int base_flags;
75     Elf_Off data_offset;
76     Elf_Addr data_vaddr;
77     Elf_Addr data_vlimit;
78     caddr_t data_addr;
79     int data_prot;
80     int data_flags;
81     Elf_Addr clear_vaddr;
82     caddr_t clear_addr;
83     caddr_t clear_page;
84     Elf_Addr phdr_vaddr;
85     size_t nclear, phsize;
86     Elf_Addr bss_vaddr;
87     Elf_Addr bss_vlimit;
88     caddr_t bss_addr;
89     Elf_Word stack_flags;
90     Elf_Addr relro_page;
91     size_t relro_size;
92     Elf_Addr note_start;
93     Elf_Addr note_end;
94     char *note_map;
95     size_t note_map_len;
96     Elf_Addr text_end;
97
98     hdr = get_elf_header(fd, path, sb);
99     if (hdr == NULL)
100         return (NULL);
101
102     /*
103      * Scan the program header entries, and save key information.
104      *
105      * We expect that the loadable segments are ordered by load address.
106      */
107     phdr = (Elf_Phdr *)((char *)hdr + hdr->e_phoff);
108     phsize  = hdr->e_phnum * sizeof (phdr[0]);
109     phlimit = phdr + hdr->e_phnum;
110     nsegs = -1;
111     phdyn = phinterp = phtls = NULL;
112     phdr_vaddr = 0;
113     relro_page = 0;
114     relro_size = 0;
115     note_start = 0;
116     note_end = 0;
117     note_map = NULL;
118     note_map_len = 0;
119     segs = alloca(sizeof(segs[0]) * hdr->e_phnum);
120     stack_flags = RTLD_DEFAULT_STACK_PF_EXEC | PF_R | PF_W;
121     text_end = 0;
122     while (phdr < phlimit) {
123         switch (phdr->p_type) {
124
125         case PT_INTERP:
126             phinterp = phdr;
127             break;
128
129         case PT_LOAD:
130             segs[++nsegs] = phdr;
131             if ((segs[nsegs]->p_align & (PAGE_SIZE - 1)) != 0) {
132                 _rtld_error("%s: PT_LOAD segment %d not page-aligned",
133                     path, nsegs);
134                 goto error;
135             }
136             if ((segs[nsegs]->p_flags & PF_X) == PF_X) {
137                 text_end = MAX(text_end,
138                     round_page(segs[nsegs]->p_vaddr + segs[nsegs]->p_memsz));
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 (data_vlimit != data_vaddr &&
232             mmap(data_addr, data_vlimit - data_vaddr, data_prot, 
233             data_flags | MAP_PREFAULT_READ, fd, data_offset) == MAP_FAILED) {
234                 _rtld_error("%s: mmap of data failed: %s", path,
235                     rtld_strerror(errno));
236                 goto error1;
237         }
238
239         /* Do BSS setup */
240         if (segs[i]->p_filesz != segs[i]->p_memsz) {
241
242             /* Clear any BSS in the last page of the segment. */
243             clear_vaddr = segs[i]->p_vaddr + segs[i]->p_filesz;
244             clear_addr = mapbase + (clear_vaddr - base_vaddr);
245             clear_page = mapbase + (trunc_page(clear_vaddr) - base_vaddr);
246
247             if ((nclear = data_vlimit - clear_vaddr) > 0) {
248                 /* Make sure the end of the segment is writable */
249                 if ((data_prot & PROT_WRITE) == 0 && -1 ==
250                      mprotect(clear_page, PAGE_SIZE, data_prot|PROT_WRITE)) {
251                         _rtld_error("%s: mprotect failed: %s", path,
252                             rtld_strerror(errno));
253                         goto error1;
254                 }
255
256                 memset(clear_addr, 0, nclear);
257
258                 /* Reset the data protection back */
259                 if ((data_prot & PROT_WRITE) == 0)
260                     mprotect(clear_page, PAGE_SIZE, data_prot);
261             }
262
263             /* Overlay the BSS segment onto the proper region. */
264             bss_vaddr = data_vlimit;
265             bss_vlimit = round_page(segs[i]->p_vaddr + segs[i]->p_memsz);
266             bss_addr = mapbase +  (bss_vaddr - base_vaddr);
267             if (bss_vlimit > bss_vaddr) {       /* There is something to do */
268                 if (mmap(bss_addr, bss_vlimit - bss_vaddr, data_prot,
269                     data_flags | MAP_ANON, -1, 0) == MAP_FAILED) {
270                     _rtld_error("%s: mmap of bss failed: %s", path,
271                         rtld_strerror(errno));
272                     goto error1;
273                 }
274             }
275         }
276
277         if (phdr_vaddr == 0 && data_offset <= hdr->e_phoff &&
278           (data_vlimit - data_vaddr + data_offset) >=
279           (hdr->e_phoff + hdr->e_phnum * sizeof (Elf_Phdr))) {
280             phdr_vaddr = data_vaddr + hdr->e_phoff - data_offset;
281         }
282     }
283
284     obj = obj_new();
285     if (sb != NULL) {
286         obj->dev = sb->st_dev;
287         obj->ino = sb->st_ino;
288     }
289     obj->mapbase = mapbase;
290     obj->mapsize = mapsize;
291     obj->vaddrbase = base_vaddr;
292     obj->relocbase = mapbase - base_vaddr;
293     obj->dynamic = (const Elf_Dyn *)(obj->relocbase + phdyn->p_vaddr);
294     if (hdr->e_entry != 0)
295         obj->entry = (caddr_t)(obj->relocbase + hdr->e_entry);
296     if (phdr_vaddr != 0) {
297         obj->phdr = (const Elf_Phdr *)(obj->relocbase + phdr_vaddr);
298     } else {
299         obj->phdr = malloc(phsize);
300         if (obj->phdr == NULL) {
301             obj_free(obj);
302             _rtld_error("%s: cannot allocate program header", path);
303             goto error1;
304         }
305         memcpy(__DECONST(char *, obj->phdr), (char *)hdr + hdr->e_phoff, phsize);
306         obj->phdr_alloc = true;
307     }
308     obj->phsize = phsize;
309     if (phinterp != NULL)
310         obj->interp = (const char *)(obj->relocbase + phinterp->p_vaddr);
311     if (phtls != NULL) {
312         tls_dtv_generation++;
313         obj->tlsindex = ++tls_max_index;
314         obj->tlssize = phtls->p_memsz;
315         obj->tlsalign = phtls->p_align;
316         obj->tlspoffset = phtls->p_offset;
317         obj->tlsinitsize = phtls->p_filesz;
318         obj->tlsinit = mapbase + phtls->p_vaddr;
319     }
320     obj->stack_flags = stack_flags;
321     obj->relro_page = obj->relocbase + trunc_page(relro_page);
322     obj->relro_size = round_page(relro_size);
323     if (note_start < note_end)
324         digest_notes(obj, note_start, note_end);
325     if (note_map != NULL)
326         munmap(note_map, note_map_len);
327     munmap(hdr, PAGE_SIZE);
328     return (obj);
329
330 error1:
331     munmap(mapbase, mapsize);
332 error:
333     if (note_map != NULL && note_map != MAP_FAILED)
334         munmap(note_map, note_map_len);
335     munmap(hdr, PAGE_SIZE);
336     return (NULL);
337 }
338
339 static Elf_Ehdr *
340 get_elf_header(int fd, const char *path, const struct stat *sbp)
341 {
342         Elf_Ehdr *hdr;
343
344         /* Make sure file has enough data for the ELF header */
345         if (sbp != NULL && sbp->st_size < (off_t)sizeof(Elf_Ehdr)) {
346                 _rtld_error("%s: invalid file format", path);
347                 return (NULL);
348         }
349
350         hdr = mmap(NULL, PAGE_SIZE, PROT_READ, MAP_PRIVATE | MAP_PREFAULT_READ,
351             fd, 0);
352         if (hdr == MAP_FAILED) {
353                 _rtld_error("%s: read error: %s", path, rtld_strerror(errno));
354                 return (NULL);
355         }
356
357         /* Make sure the file is valid */
358         if (!IS_ELF(*hdr)) {
359                 _rtld_error("%s: invalid file format", path);
360                 goto error;
361         }
362         if (hdr->e_ident[EI_CLASS] != ELF_TARG_CLASS ||
363             hdr->e_ident[EI_DATA] != ELF_TARG_DATA) {
364                 _rtld_error("%s: unsupported file layout", path);
365                 goto error;
366         }
367         if (hdr->e_ident[EI_VERSION] != EV_CURRENT ||
368             hdr->e_version != EV_CURRENT) {
369                 _rtld_error("%s: unsupported file version", path);
370                 goto error;
371         }
372         if (hdr->e_type != ET_EXEC && hdr->e_type != ET_DYN) {
373                 _rtld_error("%s: unsupported file type", path);
374                 goto error;
375         }
376         if (hdr->e_machine != ELF_TARG_MACH) {
377                 _rtld_error("%s: unsupported machine", path);
378                 goto error;
379         }
380
381         /*
382          * We rely on the program header being in the first page.  This is
383          * not strictly required by the ABI specification, but it seems to
384          * always true in practice.  And, it simplifies things considerably.
385          */
386         if (hdr->e_phentsize != sizeof(Elf_Phdr)) {
387                 _rtld_error(
388             "%s: invalid shared object: e_phentsize != sizeof(Elf_Phdr)", path);
389                 goto error;
390         }
391         if (hdr->e_phoff + hdr->e_phnum * sizeof(Elf_Phdr) >
392             (size_t)PAGE_SIZE) {
393                 _rtld_error("%s: program header too large", path);
394                 goto error;
395         }
396         return (hdr);
397
398 error:
399         munmap(hdr, PAGE_SIZE);
400         return (NULL);
401 }
402
403 void
404 obj_free(Obj_Entry *obj)
405 {
406     Objlist_Entry *elm;
407
408     if (obj->tls_done)
409         free_tls_offset(obj);
410     while (obj->needed != NULL) {
411         Needed_Entry *needed = obj->needed;
412         obj->needed = needed->next;
413         free(needed);
414     }
415     while (!STAILQ_EMPTY(&obj->names)) {
416         Name_Entry *entry = STAILQ_FIRST(&obj->names);
417         STAILQ_REMOVE_HEAD(&obj->names, link);
418         free(entry);
419     }
420     while (!STAILQ_EMPTY(&obj->dldags)) {
421         elm = STAILQ_FIRST(&obj->dldags);
422         STAILQ_REMOVE_HEAD(&obj->dldags, link);
423         free(elm);
424     }
425     while (!STAILQ_EMPTY(&obj->dagmembers)) {
426         elm = STAILQ_FIRST(&obj->dagmembers);
427         STAILQ_REMOVE_HEAD(&obj->dagmembers, link);
428         free(elm);
429     }
430     if (obj->vertab)
431         free(obj->vertab);
432     if (obj->origin_path)
433         free(obj->origin_path);
434     if (obj->z_origin)
435         free(__DECONST(void*, obj->rpath));
436     if (obj->priv)
437         free(obj->priv);
438     if (obj->path)
439         free(obj->path);
440     if (obj->phdr_alloc)
441         free(__DECONST(void *, obj->phdr));
442     free(obj);
443 }
444
445 Obj_Entry *
446 obj_new(void)
447 {
448     Obj_Entry *obj;
449
450     obj = CNEW(Obj_Entry);
451     STAILQ_INIT(&obj->dldags);
452     STAILQ_INIT(&obj->dagmembers);
453     STAILQ_INIT(&obj->names);
454     return obj;
455 }
456
457 /*
458  * Given a set of ELF protection flags, return the corresponding protection
459  * flags for MMAP.
460  */
461 int
462 convert_prot(int elfflags)
463 {
464     int prot = 0;
465     if (elfflags & PF_R)
466         prot |= PROT_READ;
467     if (elfflags & PF_W)
468         prot |= PROT_WRITE;
469     if (elfflags & PF_X)
470         prot |= PROT_EXEC;
471     return prot;
472 }
473
474 static int
475 convert_flags(int elfflags)
476 {
477     int flags = MAP_PRIVATE; /* All mappings are private */
478
479     /*
480      * Readonly mappings are marked "MAP_NOCORE", because they can be
481      * reconstructed by a debugger.
482      */
483     if (!(elfflags & PF_W))
484         flags |= MAP_NOCORE;
485     return flags;
486 }