The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/kern/imgact_elf.c

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

    1 /*-
    2  * Copyright (c) 2017 Dell EMC
    3  * Copyright (c) 2000 David O'Brien
    4  * Copyright (c) 1995-1996 Søren Schmidt
    5  * Copyright (c) 1996 Peter Wemm
    6  * All rights reserved.
    7  *
    8  * Redistribution and use in source and binary forms, with or without
    9  * modification, are permitted provided that the following conditions
   10  * are met:
   11  * 1. Redistributions of source code must retain the above copyright
   12  *    notice, this list of conditions and the following disclaimer
   13  *    in this position and unchanged.
   14  * 2. Redistributions in binary form must reproduce the above copyright
   15  *    notice, this list of conditions and the following disclaimer in the
   16  *    documentation and/or other materials provided with the distribution.
   17  * 3. The name of the author may not be used to endorse or promote products
   18  *    derived from this software without specific prior written permission
   19  *
   20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
   21  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   22  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
   23  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
   24  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
   25  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
   26  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
   27  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   28  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
   29  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   30  */
   31 
   32 #include <sys/cdefs.h>
   33 __FBSDID("$FreeBSD$");
   34 
   35 #include "opt_capsicum.h"
   36 #include "opt_compat.h"
   37 #include "opt_gzio.h"
   38 
   39 #include <sys/param.h>
   40 #include <sys/capsicum.h>
   41 #include <sys/exec.h>
   42 #include <sys/fcntl.h>
   43 #include <sys/gzio.h>
   44 #include <sys/imgact.h>
   45 #include <sys/imgact_elf.h>
   46 #include <sys/jail.h>
   47 #include <sys/kernel.h>
   48 #include <sys/lock.h>
   49 #include <sys/malloc.h>
   50 #include <sys/mount.h>
   51 #include <sys/mman.h>
   52 #include <sys/namei.h>
   53 #include <sys/pioctl.h>
   54 #include <sys/proc.h>
   55 #include <sys/procfs.h>
   56 #include <sys/ptrace.h>
   57 #include <sys/racct.h>
   58 #include <sys/resourcevar.h>
   59 #include <sys/rwlock.h>
   60 #include <sys/sbuf.h>
   61 #include <sys/sf_buf.h>
   62 #include <sys/smp.h>
   63 #include <sys/systm.h>
   64 #include <sys/signalvar.h>
   65 #include <sys/stat.h>
   66 #include <sys/sx.h>
   67 #include <sys/syscall.h>
   68 #include <sys/sysctl.h>
   69 #include <sys/sysent.h>
   70 #include <sys/vnode.h>
   71 #include <sys/syslog.h>
   72 #include <sys/eventhandler.h>
   73 #include <sys/user.h>
   74 
   75 #include <vm/vm.h>
   76 #include <vm/vm_kern.h>
   77 #include <vm/vm_param.h>
   78 #include <vm/pmap.h>
   79 #include <vm/vm_map.h>
   80 #include <vm/vm_object.h>
   81 #include <vm/vm_extern.h>
   82 
   83 #include <machine/elf.h>
   84 #include <machine/md_var.h>
   85 
   86 #define ELF_NOTE_ROUNDSIZE      4
   87 #define OLD_EI_BRAND    8
   88 
   89 static int __elfN(check_header)(const Elf_Ehdr *hdr);
   90 static Elf_Brandinfo *__elfN(get_brandinfo)(struct image_params *imgp,
   91     const char *interp, int interp_name_len, int32_t *osrel);
   92 static int __elfN(load_file)(struct proc *p, const char *file, u_long *addr,
   93     u_long *entry, size_t pagesize);
   94 static int __elfN(load_section)(struct image_params *imgp, vm_ooffset_t offset,
   95     caddr_t vmaddr, size_t memsz, size_t filsz, vm_prot_t prot,
   96     size_t pagesize);
   97 static int __CONCAT(exec_, __elfN(imgact))(struct image_params *imgp);
   98 static bool __elfN(freebsd_trans_osrel)(const Elf_Note *note,
   99     int32_t *osrel);
  100 static bool kfreebsd_trans_osrel(const Elf_Note *note, int32_t *osrel);
  101 static boolean_t __elfN(check_note)(struct image_params *imgp,
  102     Elf_Brandnote *checknote, int32_t *osrel);
  103 static vm_prot_t __elfN(trans_prot)(Elf_Word);
  104 static Elf_Word __elfN(untrans_prot)(vm_prot_t);
  105 
  106 SYSCTL_NODE(_kern, OID_AUTO, __CONCAT(elf, __ELF_WORD_SIZE), CTLFLAG_RW, 0,
  107     "");
  108 
  109 #define CORE_BUF_SIZE   (16 * 1024)
  110 
  111 int __elfN(fallback_brand) = -1;
  112 SYSCTL_INT(__CONCAT(_kern_elf, __ELF_WORD_SIZE), OID_AUTO,
  113     fallback_brand, CTLFLAG_RWTUN, &__elfN(fallback_brand), 0,
  114     __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE)) " brand of last resort");
  115 
  116 static int elf_legacy_coredump = 0;
  117 SYSCTL_INT(_debug, OID_AUTO, __elfN(legacy_coredump), CTLFLAG_RW, 
  118     &elf_legacy_coredump, 0,
  119     "include all and only RW pages in core dumps");
  120 
  121 int __elfN(nxstack) =
  122 #if defined(__amd64__) || defined(__powerpc64__) /* both 64 and 32 bit */ || \
  123     (defined(__arm__) && __ARM_ARCH >= 7) || defined(__aarch64__)
  124         1;
  125 #else
  126         0;
  127 #endif
  128 SYSCTL_INT(__CONCAT(_kern_elf, __ELF_WORD_SIZE), OID_AUTO,
  129     nxstack, CTLFLAG_RW, &__elfN(nxstack), 0,
  130     __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE)) ": enable non-executable stack");
  131 
  132 #if __ELF_WORD_SIZE == 32
  133 #if defined(__amd64__)
  134 int i386_read_exec = 0;
  135 SYSCTL_INT(_kern_elf32, OID_AUTO, read_exec, CTLFLAG_RW, &i386_read_exec, 0,
  136     "enable execution from readable segments");
  137 #endif
  138 #endif
  139 
  140 static Elf_Brandinfo *elf_brand_list[MAX_BRANDS];
  141 
  142 #define trunc_page_ps(va, ps)   rounddown2(va, ps)
  143 #define round_page_ps(va, ps)   roundup2(va, ps)
  144 #define aligned(a, t)   (trunc_page_ps((u_long)(a), sizeof(t)) == (u_long)(a))
  145 
  146 static const char FREEBSD_ABI_VENDOR[] = "FreeBSD";
  147 
  148 Elf_Brandnote __elfN(freebsd_brandnote) = {
  149         .hdr.n_namesz   = sizeof(FREEBSD_ABI_VENDOR),
  150         .hdr.n_descsz   = sizeof(int32_t),
  151         .hdr.n_type     = NT_FREEBSD_ABI_TAG,
  152         .vendor         = FREEBSD_ABI_VENDOR,
  153         .flags          = BN_TRANSLATE_OSREL,
  154         .trans_osrel    = __elfN(freebsd_trans_osrel)
  155 };
  156 
  157 static bool
  158 __elfN(freebsd_trans_osrel)(const Elf_Note *note, int32_t *osrel)
  159 {
  160         uintptr_t p;
  161 
  162         p = (uintptr_t)(note + 1);
  163         p += roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE);
  164         *osrel = *(const int32_t *)(p);
  165 
  166         return (true);
  167 }
  168 
  169 static const char GNU_ABI_VENDOR[] = "GNU";
  170 static int GNU_KFREEBSD_ABI_DESC = 3;
  171 
  172 Elf_Brandnote __elfN(kfreebsd_brandnote) = {
  173         .hdr.n_namesz   = sizeof(GNU_ABI_VENDOR),
  174         .hdr.n_descsz   = 16,   /* XXX at least 16 */
  175         .hdr.n_type     = 1,
  176         .vendor         = GNU_ABI_VENDOR,
  177         .flags          = BN_TRANSLATE_OSREL,
  178         .trans_osrel    = kfreebsd_trans_osrel
  179 };
  180 
  181 static bool
  182 kfreebsd_trans_osrel(const Elf_Note *note, int32_t *osrel)
  183 {
  184         const Elf32_Word *desc;
  185         uintptr_t p;
  186 
  187         p = (uintptr_t)(note + 1);
  188         p += roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE);
  189 
  190         desc = (const Elf32_Word *)p;
  191         if (desc[0] != GNU_KFREEBSD_ABI_DESC)
  192                 return (false);
  193 
  194         /*
  195          * Debian GNU/kFreeBSD embed the earliest compatible kernel version
  196          * (__FreeBSD_version: <major><two digit minor>Rxx) in the LSB way.
  197          */
  198         *osrel = desc[1] * 100000 + desc[2] * 1000 + desc[3];
  199 
  200         return (true);
  201 }
  202 
  203 int
  204 __elfN(insert_brand_entry)(Elf_Brandinfo *entry)
  205 {
  206         int i;
  207 
  208         for (i = 0; i < MAX_BRANDS; i++) {
  209                 if (elf_brand_list[i] == NULL) {
  210                         elf_brand_list[i] = entry;
  211                         break;
  212                 }
  213         }
  214         if (i == MAX_BRANDS) {
  215                 printf("WARNING: %s: could not insert brandinfo entry: %p\n",
  216                         __func__, entry);
  217                 return (-1);
  218         }
  219         return (0);
  220 }
  221 
  222 int
  223 __elfN(remove_brand_entry)(Elf_Brandinfo *entry)
  224 {
  225         int i;
  226 
  227         for (i = 0; i < MAX_BRANDS; i++) {
  228                 if (elf_brand_list[i] == entry) {
  229                         elf_brand_list[i] = NULL;
  230                         break;
  231                 }
  232         }
  233         if (i == MAX_BRANDS)
  234                 return (-1);
  235         return (0);
  236 }
  237 
  238 int
  239 __elfN(brand_inuse)(Elf_Brandinfo *entry)
  240 {
  241         struct proc *p;
  242         int rval = FALSE;
  243 
  244         sx_slock(&allproc_lock);
  245         FOREACH_PROC_IN_SYSTEM(p) {
  246                 if (p->p_sysent == entry->sysvec) {
  247                         rval = TRUE;
  248                         break;
  249                 }
  250         }
  251         sx_sunlock(&allproc_lock);
  252 
  253         return (rval);
  254 }
  255 
  256 static Elf_Brandinfo *
  257 __elfN(get_brandinfo)(struct image_params *imgp, const char *interp,
  258     int interp_name_len, int32_t *osrel)
  259 {
  260         const Elf_Ehdr *hdr = (const Elf_Ehdr *)imgp->image_header;
  261         Elf_Brandinfo *bi, *bi_m;
  262         boolean_t ret;
  263         int i;
  264 
  265         /*
  266          * We support four types of branding -- (1) the ELF EI_OSABI field
  267          * that SCO added to the ELF spec, (2) FreeBSD 3.x's traditional string
  268          * branding w/in the ELF header, (3) path of the `interp_path'
  269          * field, and (4) the ".note.ABI-tag" ELF section.
  270          */
  271 
  272         /* Look for an ".note.ABI-tag" ELF section */
  273         bi_m = NULL;
  274         for (i = 0; i < MAX_BRANDS; i++) {
  275                 bi = elf_brand_list[i];
  276                 if (bi == NULL)
  277                         continue;
  278                 if (interp != NULL && (bi->flags & BI_BRAND_ONLY_STATIC) != 0)
  279                         continue;
  280                 if (hdr->e_machine == bi->machine && (bi->flags &
  281                     (BI_BRAND_NOTE|BI_BRAND_NOTE_MANDATORY)) != 0) {
  282                         ret = __elfN(check_note)(imgp, bi->brand_note, osrel);
  283                         /* Give brand a chance to veto check_note's guess */
  284                         if (ret && bi->header_supported)
  285                                 ret = bi->header_supported(imgp);
  286                         /*
  287                          * If note checker claimed the binary, but the
  288                          * interpreter path in the image does not
  289                          * match default one for the brand, try to
  290                          * search for other brands with the same
  291                          * interpreter.  Either there is better brand
  292                          * with the right interpreter, or, failing
  293                          * this, we return first brand which accepted
  294                          * our note and, optionally, header.
  295                          */
  296                         if (ret && bi_m == NULL && interp != NULL &&
  297                             (bi->interp_path == NULL ||
  298                             (strlen(bi->interp_path) + 1 != interp_name_len ||
  299                             strncmp(interp, bi->interp_path, interp_name_len)
  300                             != 0))) {
  301                                 bi_m = bi;
  302                                 ret = 0;
  303                         }
  304                         if (ret)
  305                                 return (bi);
  306                 }
  307         }
  308         if (bi_m != NULL)
  309                 return (bi_m);
  310 
  311         /* If the executable has a brand, search for it in the brand list. */
  312         for (i = 0; i < MAX_BRANDS; i++) {
  313                 bi = elf_brand_list[i];
  314                 if (bi == NULL || (bi->flags & BI_BRAND_NOTE_MANDATORY) != 0 ||
  315                     (interp != NULL && (bi->flags & BI_BRAND_ONLY_STATIC) != 0))
  316                         continue;
  317                 if (hdr->e_machine == bi->machine &&
  318                     (hdr->e_ident[EI_OSABI] == bi->brand ||
  319                     (bi->compat_3_brand != NULL &&
  320                     strcmp((const char *)&hdr->e_ident[OLD_EI_BRAND],
  321                     bi->compat_3_brand) == 0))) {
  322                         /* Looks good, but give brand a chance to veto */
  323                         if (bi->header_supported == NULL ||
  324                             bi->header_supported(imgp)) {
  325                                 /*
  326                                  * Again, prefer strictly matching
  327                                  * interpreter path.
  328                                  */
  329                                 if (interp_name_len == 0 &&
  330                                     bi->interp_path == NULL)
  331                                         return (bi);
  332                                 if (bi->interp_path != NULL &&
  333                                     strlen(bi->interp_path) + 1 ==
  334                                     interp_name_len && strncmp(interp,
  335                                     bi->interp_path, interp_name_len) == 0)
  336                                         return (bi);
  337                                 if (bi_m == NULL)
  338                                         bi_m = bi;
  339                         }
  340                 }
  341         }
  342         if (bi_m != NULL)
  343                 return (bi_m);
  344 
  345         /* No known brand, see if the header is recognized by any brand */
  346         for (i = 0; i < MAX_BRANDS; i++) {
  347                 bi = elf_brand_list[i];
  348                 if (bi == NULL || bi->flags & BI_BRAND_NOTE_MANDATORY ||
  349                     bi->header_supported == NULL)
  350                         continue;
  351                 if (hdr->e_machine == bi->machine) {
  352                         ret = bi->header_supported(imgp);
  353                         if (ret)
  354                                 return (bi);
  355                 }
  356         }
  357 
  358         /* Lacking a known brand, search for a recognized interpreter. */
  359         if (interp != NULL) {
  360                 for (i = 0; i < MAX_BRANDS; i++) {
  361                         bi = elf_brand_list[i];
  362                         if (bi == NULL || (bi->flags &
  363                             (BI_BRAND_NOTE_MANDATORY | BI_BRAND_ONLY_STATIC))
  364                             != 0)
  365                                 continue;
  366                         if (hdr->e_machine == bi->machine &&
  367                             bi->interp_path != NULL &&
  368                             /* ELF image p_filesz includes terminating zero */
  369                             strlen(bi->interp_path) + 1 == interp_name_len &&
  370                             strncmp(interp, bi->interp_path, interp_name_len)
  371                             == 0 && (bi->header_supported == NULL ||
  372                             bi->header_supported(imgp)))
  373                                 return (bi);
  374                 }
  375         }
  376 
  377         /* Lacking a recognized interpreter, try the default brand */
  378         for (i = 0; i < MAX_BRANDS; i++) {
  379                 bi = elf_brand_list[i];
  380                 if (bi == NULL || (bi->flags & BI_BRAND_NOTE_MANDATORY) != 0 ||
  381                     (interp != NULL && (bi->flags & BI_BRAND_ONLY_STATIC) != 0))
  382                         continue;
  383                 if (hdr->e_machine == bi->machine &&
  384                     __elfN(fallback_brand) == bi->brand &&
  385                     (bi->header_supported == NULL ||
  386                     bi->header_supported(imgp)))
  387                         return (bi);
  388         }
  389         return (NULL);
  390 }
  391 
  392 static bool
  393 __elfN(phdr_in_zero_page)(const Elf_Ehdr *hdr)
  394 {
  395         return (hdr->e_phoff <= PAGE_SIZE &&
  396             (u_int)hdr->e_phentsize * hdr->e_phnum <= PAGE_SIZE - hdr->e_phoff);
  397 }
  398 
  399 static int
  400 __elfN(check_header)(const Elf_Ehdr *hdr)
  401 {
  402         Elf_Brandinfo *bi;
  403         int i;
  404 
  405         if (!IS_ELF(*hdr) ||
  406             hdr->e_ident[EI_CLASS] != ELF_TARG_CLASS ||
  407             hdr->e_ident[EI_DATA] != ELF_TARG_DATA ||
  408             hdr->e_ident[EI_VERSION] != EV_CURRENT ||
  409             hdr->e_phentsize != sizeof(Elf_Phdr) ||
  410             hdr->e_version != ELF_TARG_VER)
  411                 return (ENOEXEC);
  412 
  413         /*
  414          * Make sure we have at least one brand for this machine.
  415          */
  416 
  417         for (i = 0; i < MAX_BRANDS; i++) {
  418                 bi = elf_brand_list[i];
  419                 if (bi != NULL && bi->machine == hdr->e_machine)
  420                         break;
  421         }
  422         if (i == MAX_BRANDS)
  423                 return (ENOEXEC);
  424 
  425         return (0);
  426 }
  427 
  428 static int
  429 __elfN(map_partial)(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
  430     vm_offset_t start, vm_offset_t end, vm_prot_t prot)
  431 {
  432         struct sf_buf *sf;
  433         int error;
  434         vm_offset_t off;
  435 
  436         /*
  437          * Create the page if it doesn't exist yet. Ignore errors.
  438          */
  439         vm_map_fixed(map, NULL, 0, trunc_page(start), round_page(end) -
  440             trunc_page(start), VM_PROT_ALL, VM_PROT_ALL, MAP_CHECK_EXCL);
  441 
  442         /*
  443          * Find the page from the underlying object.
  444          */
  445         if (object != NULL) {
  446                 sf = vm_imgact_map_page(object, offset);
  447                 if (sf == NULL)
  448                         return (KERN_FAILURE);
  449                 off = offset - trunc_page(offset);
  450                 error = copyout((caddr_t)sf_buf_kva(sf) + off, (caddr_t)start,
  451                     end - start);
  452                 vm_imgact_unmap_page(sf);
  453                 if (error != 0)
  454                         return (KERN_FAILURE);
  455         }
  456 
  457         return (KERN_SUCCESS);
  458 }
  459 
  460 static int
  461 __elfN(map_insert)(struct image_params *imgp, vm_map_t map, vm_object_t object,
  462     vm_ooffset_t offset, vm_offset_t start, vm_offset_t end, vm_prot_t prot,
  463     int cow)
  464 {
  465         struct sf_buf *sf;
  466         vm_offset_t off;
  467         vm_size_t sz;
  468         int error, locked, rv;
  469 
  470         if (start != trunc_page(start)) {
  471                 rv = __elfN(map_partial)(map, object, offset, start,
  472                     round_page(start), prot);
  473                 if (rv != KERN_SUCCESS)
  474                         return (rv);
  475                 offset += round_page(start) - start;
  476                 start = round_page(start);
  477         }
  478         if (end != round_page(end)) {
  479                 rv = __elfN(map_partial)(map, object, offset +
  480                     trunc_page(end) - start, trunc_page(end), end, prot);
  481                 if (rv != KERN_SUCCESS)
  482                         return (rv);
  483                 end = trunc_page(end);
  484         }
  485         if (start >= end)
  486                 return (KERN_SUCCESS);
  487         if ((offset & PAGE_MASK) != 0) {
  488                 /*
  489                  * The mapping is not page aligned.  This means that we have
  490                  * to copy the data.
  491                  */
  492                 rv = vm_map_fixed(map, NULL, 0, start, end - start,
  493                     prot | VM_PROT_WRITE, VM_PROT_ALL, MAP_CHECK_EXCL);
  494                 if (rv != KERN_SUCCESS)
  495                         return (rv);
  496                 if (object == NULL)
  497                         return (KERN_SUCCESS);
  498                 for (; start < end; start += sz) {
  499                         sf = vm_imgact_map_page(object, offset);
  500                         if (sf == NULL)
  501                                 return (KERN_FAILURE);
  502                         off = offset - trunc_page(offset);
  503                         sz = end - start;
  504                         if (sz > PAGE_SIZE - off)
  505                                 sz = PAGE_SIZE - off;
  506                         error = copyout((caddr_t)sf_buf_kva(sf) + off,
  507                             (caddr_t)start, sz);
  508                         vm_imgact_unmap_page(sf);
  509                         if (error != 0)
  510                                 return (KERN_FAILURE);
  511                         offset += sz;
  512                 }
  513         } else {
  514                 vm_object_reference(object);
  515                 rv = vm_map_fixed(map, object, offset, start, end - start,
  516                     prot, VM_PROT_ALL, cow | MAP_CHECK_EXCL);
  517                 if (rv != KERN_SUCCESS) {
  518                         locked = VOP_ISLOCKED(imgp->vp);
  519                         VOP_UNLOCK(imgp->vp, 0);
  520                         vm_object_deallocate(object);
  521                         vn_lock(imgp->vp, locked | LK_RETRY);
  522                         return (rv);
  523                 }
  524         }
  525         return (KERN_SUCCESS);
  526 }
  527 
  528 static int
  529 __elfN(load_section)(struct image_params *imgp, vm_ooffset_t offset,
  530     caddr_t vmaddr, size_t memsz, size_t filsz, vm_prot_t prot,
  531     size_t pagesize)
  532 {
  533         struct sf_buf *sf;
  534         size_t map_len;
  535         vm_map_t map;
  536         vm_object_t object;
  537         vm_offset_t off, map_addr;
  538         int error, rv, cow;
  539         size_t copy_len;
  540         vm_ooffset_t file_addr;
  541 
  542         /*
  543          * It's necessary to fail if the filsz + offset taken from the
  544          * header is greater than the actual file pager object's size.
  545          * If we were to allow this, then the vm_map_find() below would
  546          * walk right off the end of the file object and into the ether.
  547          *
  548          * While I'm here, might as well check for something else that
  549          * is invalid: filsz cannot be greater than memsz.
  550          */
  551         if ((filsz != 0 && (off_t)filsz + offset > imgp->attr->va_size) ||
  552             filsz > memsz) {
  553                 uprintf("elf_load_section: truncated ELF file\n");
  554                 return (ENOEXEC);
  555         }
  556 
  557         object = imgp->object;
  558         map = &imgp->proc->p_vmspace->vm_map;
  559         map_addr = trunc_page_ps((vm_offset_t)vmaddr, pagesize);
  560         file_addr = trunc_page_ps(offset, pagesize);
  561 
  562         /*
  563          * We have two choices.  We can either clear the data in the last page
  564          * of an oversized mapping, or we can start the anon mapping a page
  565          * early and copy the initialized data into that first page.  We
  566          * choose the second.
  567          */
  568         if (filsz == 0)
  569                 map_len = 0;
  570         else if (memsz > filsz)
  571                 map_len = trunc_page_ps(offset + filsz, pagesize) - file_addr;
  572         else
  573                 map_len = round_page_ps(offset + filsz, pagesize) - file_addr;
  574 
  575         if (map_len != 0) {
  576                 /* cow flags: don't dump readonly sections in core */
  577                 cow = MAP_COPY_ON_WRITE | MAP_PREFAULT |
  578                     (prot & VM_PROT_WRITE ? 0 : MAP_DISABLE_COREDUMP);
  579 
  580                 rv = __elfN(map_insert)(imgp, map,
  581                                       object,
  582                                       file_addr,        /* file offset */
  583                                       map_addr,         /* virtual start */
  584                                       map_addr + map_len,/* virtual end */
  585                                       prot,
  586                                       cow);
  587                 if (rv != KERN_SUCCESS)
  588                         return (EINVAL);
  589 
  590                 /* we can stop now if we've covered it all */
  591                 if (memsz == filsz)
  592                         return (0);
  593         }
  594 
  595 
  596         /*
  597          * We have to get the remaining bit of the file into the first part
  598          * of the oversized map segment.  This is normally because the .data
  599          * segment in the file is extended to provide bss.  It's a neat idea
  600          * to try and save a page, but it's a pain in the behind to implement.
  601          */
  602         copy_len = filsz == 0 ? 0 : (offset + filsz) - trunc_page_ps(offset +
  603             filsz, pagesize);
  604         map_addr = trunc_page_ps((vm_offset_t)vmaddr + filsz, pagesize);
  605         map_len = round_page_ps((vm_offset_t)vmaddr + memsz, pagesize) -
  606             map_addr;
  607 
  608         /* This had damn well better be true! */
  609         if (map_len != 0) {
  610                 rv = __elfN(map_insert)(imgp, map, NULL, 0, map_addr,
  611                     map_addr + map_len, prot, 0);
  612                 if (rv != KERN_SUCCESS)
  613                         return (EINVAL);
  614         }
  615 
  616         if (copy_len != 0) {
  617                 sf = vm_imgact_map_page(object, offset + filsz);
  618                 if (sf == NULL)
  619                         return (EIO);
  620 
  621                 /* send the page fragment to user space */
  622                 off = trunc_page_ps(offset + filsz, pagesize) -
  623                     trunc_page(offset + filsz);
  624                 error = copyout((caddr_t)sf_buf_kva(sf) + off,
  625                     (caddr_t)map_addr, copy_len);
  626                 vm_imgact_unmap_page(sf);
  627                 if (error != 0)
  628                         return (error);
  629         }
  630 
  631         /*
  632          * Remove write access to the page if it was only granted by map_insert
  633          * to allow copyout.
  634          */
  635         if ((prot & VM_PROT_WRITE) == 0)
  636                 vm_map_protect(map, trunc_page(map_addr), round_page(map_addr +
  637                     map_len), prot, FALSE);
  638 
  639         return (0);
  640 }
  641 
  642 /*
  643  * Load the file "file" into memory.  It may be either a shared object
  644  * or an executable.
  645  *
  646  * The "addr" reference parameter is in/out.  On entry, it specifies
  647  * the address where a shared object should be loaded.  If the file is
  648  * an executable, this value is ignored.  On exit, "addr" specifies
  649  * where the file was actually loaded.
  650  *
  651  * The "entry" reference parameter is out only.  On exit, it specifies
  652  * the entry point for the loaded file.
  653  */
  654 static int
  655 __elfN(load_file)(struct proc *p, const char *file, u_long *addr,
  656         u_long *entry, size_t pagesize)
  657 {
  658         struct {
  659                 struct nameidata nd;
  660                 struct vattr attr;
  661                 struct image_params image_params;
  662         } *tempdata;
  663         const Elf_Ehdr *hdr = NULL;
  664         const Elf_Phdr *phdr = NULL;
  665         struct nameidata *nd;
  666         struct vattr *attr;
  667         struct image_params *imgp;
  668         vm_prot_t prot;
  669         u_long rbase;
  670         u_long base_addr = 0;
  671         int error, i, numsegs;
  672 
  673 #ifdef CAPABILITY_MODE
  674         /*
  675          * XXXJA: This check can go away once we are sufficiently confident
  676          * that the checks in namei() are correct.
  677          */
  678         if (IN_CAPABILITY_MODE(curthread))
  679                 return (ECAPMODE);
  680 #endif
  681 
  682         tempdata = malloc(sizeof(*tempdata), M_TEMP, M_WAITOK);
  683         nd = &tempdata->nd;
  684         attr = &tempdata->attr;
  685         imgp = &tempdata->image_params;
  686 
  687         /*
  688          * Initialize part of the common data
  689          */
  690         imgp->proc = p;
  691         imgp->attr = attr;
  692         imgp->firstpage = NULL;
  693         imgp->image_header = NULL;
  694         imgp->object = NULL;
  695         imgp->execlabel = NULL;
  696 
  697         NDINIT(nd, LOOKUP, ISOPEN | LOCKLEAF | FOLLOW, UIO_SYSSPACE, file,
  698             curthread);
  699         if ((error = namei(nd)) != 0) {
  700                 nd->ni_vp = NULL;
  701                 goto fail;
  702         }
  703         NDFREE(nd, NDF_ONLY_PNBUF);
  704         imgp->vp = nd->ni_vp;
  705 
  706         /*
  707          * Check permissions, modes, uid, etc on the file, and "open" it.
  708          */
  709         error = exec_check_permissions(imgp);
  710         if (error)
  711                 goto fail;
  712 
  713         error = exec_map_first_page(imgp);
  714         if (error)
  715                 goto fail;
  716 
  717         /*
  718          * Also make certain that the interpreter stays the same, so set
  719          * its VV_TEXT flag, too.
  720          */
  721         VOP_SET_TEXT(nd->ni_vp);
  722 
  723         imgp->object = nd->ni_vp->v_object;
  724 
  725         hdr = (const Elf_Ehdr *)imgp->image_header;
  726         if ((error = __elfN(check_header)(hdr)) != 0)
  727                 goto fail;
  728         if (hdr->e_type == ET_DYN)
  729                 rbase = *addr;
  730         else if (hdr->e_type == ET_EXEC)
  731                 rbase = 0;
  732         else {
  733                 error = ENOEXEC;
  734                 goto fail;
  735         }
  736 
  737         /* Only support headers that fit within first page for now      */
  738         if (!__elfN(phdr_in_zero_page)(hdr)) {
  739                 error = ENOEXEC;
  740                 goto fail;
  741         }
  742 
  743         phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
  744         if (!aligned(phdr, Elf_Addr)) {
  745                 error = ENOEXEC;
  746                 goto fail;
  747         }
  748 
  749         for (i = 0, numsegs = 0; i < hdr->e_phnum; i++) {
  750                 if (phdr[i].p_type == PT_LOAD && phdr[i].p_memsz != 0) {
  751                         /* Loadable segment */
  752                         prot = __elfN(trans_prot)(phdr[i].p_flags);
  753                         error = __elfN(load_section)(imgp, phdr[i].p_offset,
  754                             (caddr_t)(uintptr_t)phdr[i].p_vaddr + rbase,
  755                             phdr[i].p_memsz, phdr[i].p_filesz, prot, pagesize);
  756                         if (error != 0)
  757                                 goto fail;
  758                         /*
  759                          * Establish the base address if this is the
  760                          * first segment.
  761                          */
  762                         if (numsegs == 0)
  763                                 base_addr = trunc_page(phdr[i].p_vaddr +
  764                                     rbase);
  765                         numsegs++;
  766                 }
  767         }
  768         *addr = base_addr;
  769         *entry = (unsigned long)hdr->e_entry + rbase;
  770 
  771 fail:
  772         if (imgp->firstpage)
  773                 exec_unmap_first_page(imgp);
  774 
  775         if (nd->ni_vp)
  776                 vput(nd->ni_vp);
  777 
  778         free(tempdata, M_TEMP);
  779 
  780         return (error);
  781 }
  782 
  783 static int
  784 __CONCAT(exec_, __elfN(imgact))(struct image_params *imgp)
  785 {
  786         struct thread *td;
  787         const Elf_Ehdr *hdr;
  788         const Elf_Phdr *phdr;
  789         Elf_Auxargs *elf_auxargs;
  790         struct vmspace *vmspace;
  791         const char *err_str, *newinterp;
  792         char *interp, *interp_buf, *path;
  793         Elf_Brandinfo *brand_info;
  794         struct sysentvec *sv;
  795         vm_prot_t prot;
  796         u_long text_size, data_size, total_size, text_addr, data_addr;
  797         u_long seg_size, seg_addr, addr, baddr, et_dyn_addr, entry, proghdr;
  798         int32_t osrel;
  799         int error, i, n, interp_name_len, have_interp;
  800 
  801         hdr = (const Elf_Ehdr *)imgp->image_header;
  802 
  803         /*
  804          * Do we have a valid ELF header ?
  805          *
  806          * Only allow ET_EXEC & ET_DYN here, reject ET_DYN later
  807          * if particular brand doesn't support it.
  808          */
  809         if (__elfN(check_header)(hdr) != 0 ||
  810             (hdr->e_type != ET_EXEC && hdr->e_type != ET_DYN))
  811                 return (-1);
  812 
  813         /*
  814          * From here on down, we return an errno, not -1, as we've
  815          * detected an ELF file.
  816          */
  817 
  818         if (!__elfN(phdr_in_zero_page)(hdr)) {
  819                 uprintf("Program headers not in the first page\n");
  820                 return (ENOEXEC);
  821         }
  822         phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff); 
  823         if (!aligned(phdr, Elf_Addr)) {
  824                 uprintf("Unaligned program headers\n");
  825                 return (ENOEXEC);
  826         }
  827 
  828         n = error = 0;
  829         baddr = 0;
  830         osrel = 0;
  831         text_size = data_size = total_size = text_addr = data_addr = 0;
  832         entry = proghdr = 0;
  833         interp_name_len = 0;
  834         err_str = newinterp = NULL;
  835         interp = interp_buf = NULL;
  836         td = curthread;
  837 
  838         for (i = 0; i < hdr->e_phnum; i++) {
  839                 switch (phdr[i].p_type) {
  840                 case PT_LOAD:
  841                         if (n == 0)
  842                                 baddr = phdr[i].p_vaddr;
  843                         n++;
  844                         break;
  845                 case PT_INTERP:
  846                         /* Path to interpreter */
  847                         if (phdr[i].p_filesz < 2 ||
  848                             phdr[i].p_filesz > MAXPATHLEN) {
  849                                 uprintf("Invalid PT_INTERP\n");
  850                                 error = ENOEXEC;
  851                                 goto ret;
  852                         }
  853                         if (interp != NULL) {
  854                                 uprintf("Multiple PT_INTERP headers\n");
  855                                 error = ENOEXEC;
  856                                 goto ret;
  857                         }
  858                         interp_name_len = phdr[i].p_filesz;
  859                         if (phdr[i].p_offset > PAGE_SIZE ||
  860                             interp_name_len > PAGE_SIZE - phdr[i].p_offset) {
  861                                 VOP_UNLOCK(imgp->vp, 0);
  862                                 interp_buf = malloc(interp_name_len + 1, M_TEMP,
  863                                     M_WAITOK);
  864                                 vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
  865                                 error = vn_rdwr(UIO_READ, imgp->vp, interp_buf,
  866                                     interp_name_len, phdr[i].p_offset,
  867                                     UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred,
  868                                     NOCRED, NULL, td);
  869                                 if (error != 0) {
  870                                         uprintf("i/o error PT_INTERP %d\n",
  871                                             error);
  872                                         goto ret;
  873                                 }
  874                                 interp_buf[interp_name_len] = '\0';
  875                                 interp = interp_buf;
  876                         } else {
  877                                 interp = __DECONST(char *, imgp->image_header) +
  878                                     phdr[i].p_offset;
  879                                 if (interp[interp_name_len - 1] != '\0') {
  880                                         uprintf("Invalid PT_INTERP\n");
  881                                         error = ENOEXEC;
  882                                         goto ret;
  883                                 }
  884                         }
  885                         break;
  886                 case PT_GNU_STACK:
  887                         if (__elfN(nxstack))
  888                                 imgp->stack_prot =
  889                                     __elfN(trans_prot)(phdr[i].p_flags);
  890                         imgp->stack_sz = phdr[i].p_memsz;
  891                         break;
  892                 }
  893         }
  894 
  895         brand_info = __elfN(get_brandinfo)(imgp, interp, interp_name_len,
  896             &osrel);
  897         if (brand_info == NULL) {
  898                 uprintf("ELF binary type \"%u\" not known.\n",
  899                     hdr->e_ident[EI_OSABI]);
  900                 error = ENOEXEC;
  901                 goto ret;
  902         }
  903         if (hdr->e_type == ET_DYN) {
  904                 if ((brand_info->flags & BI_CAN_EXEC_DYN) == 0) {
  905                         uprintf("Cannot execute shared object\n");
  906                         error = ENOEXEC;
  907                         goto ret;
  908                 }
  909                 /*
  910                  * Honour the base load address from the dso if it is
  911                  * non-zero for some reason.
  912                  */
  913                 if (baddr == 0)
  914                         et_dyn_addr = ET_DYN_LOAD_ADDR;
  915                 else
  916                         et_dyn_addr = 0;
  917         } else
  918                 et_dyn_addr = 0;
  919         sv = brand_info->sysvec;
  920         if (interp != NULL && brand_info->interp_newpath != NULL)
  921                 newinterp = brand_info->interp_newpath;
  922 
  923         /*
  924          * Avoid a possible deadlock if the current address space is destroyed
  925          * and that address space maps the locked vnode.  In the common case,
  926          * the locked vnode's v_usecount is decremented but remains greater
  927          * than zero.  Consequently, the vnode lock is not needed by vrele().
  928          * However, in cases where the vnode lock is external, such as nullfs,
  929          * v_usecount may become zero.
  930          *
  931          * The VV_TEXT flag prevents modifications to the executable while
  932          * the vnode is unlocked.
  933          */
  934         VOP_UNLOCK(imgp->vp, 0);
  935 
  936         error = exec_new_vmspace(imgp, sv);
  937         imgp->proc->p_sysent = sv;
  938 
  939         vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
  940         if (error != 0)
  941                 goto ret;
  942 
  943         for (i = 0; i < hdr->e_phnum; i++) {
  944                 switch (phdr[i].p_type) {
  945                 case PT_LOAD:   /* Loadable segment */
  946                         if (phdr[i].p_memsz == 0)
  947                                 break;
  948                         prot = __elfN(trans_prot)(phdr[i].p_flags);
  949                         error = __elfN(load_section)(imgp, phdr[i].p_offset,
  950                             (caddr_t)(uintptr_t)phdr[i].p_vaddr + et_dyn_addr,
  951                             phdr[i].p_memsz, phdr[i].p_filesz, prot,
  952                             sv->sv_pagesize);
  953                         if (error != 0)
  954                                 goto ret;
  955 
  956                         /*
  957                          * If this segment contains the program headers,
  958                          * remember their virtual address for the AT_PHDR
  959                          * aux entry. Static binaries don't usually include
  960                          * a PT_PHDR entry.
  961                          */
  962                         if (phdr[i].p_offset == 0 &&
  963                             hdr->e_phoff + hdr->e_phnum * hdr->e_phentsize
  964                                 <= phdr[i].p_filesz)
  965                                 proghdr = phdr[i].p_vaddr + hdr->e_phoff +
  966                                     et_dyn_addr;
  967 
  968                         seg_addr = trunc_page(phdr[i].p_vaddr + et_dyn_addr);
  969                         seg_size = round_page(phdr[i].p_memsz +
  970                             phdr[i].p_vaddr + et_dyn_addr - seg_addr);
  971 
  972                         /*
  973                          * Make the largest executable segment the official
  974                          * text segment and all others data.
  975                          *
  976                          * Note that obreak() assumes that data_addr + 
  977                          * data_size == end of data load area, and the ELF
  978                          * file format expects segments to be sorted by
  979                          * address.  If multiple data segments exist, the
  980                          * last one will be used.
  981                          */
  982 
  983                         if (phdr[i].p_flags & PF_X && text_size < seg_size) {
  984                                 text_size = seg_size;
  985                                 text_addr = seg_addr;
  986                         } else {
  987                                 data_size = seg_size;
  988                                 data_addr = seg_addr;
  989                         }
  990                         total_size += seg_size;
  991                         break;
  992                 case PT_PHDR:   /* Program header table info */
  993                         proghdr = phdr[i].p_vaddr + et_dyn_addr;
  994                         break;
  995                 default:
  996                         break;
  997                 }
  998         }
  999         
 1000         if (data_addr == 0 && data_size == 0) {
 1001                 data_addr = text_addr;
 1002                 data_size = text_size;
 1003         }
 1004 
 1005         entry = (u_long)hdr->e_entry + et_dyn_addr;
 1006 
 1007         /*
 1008          * Check limits.  It should be safe to check the
 1009          * limits after loading the segments since we do
 1010          * not actually fault in all the segments pages.
 1011          */
 1012         PROC_LOCK(imgp->proc);
 1013         if (data_size > lim_cur_proc(imgp->proc, RLIMIT_DATA))
 1014                 err_str = "Data segment size exceeds process limit";
 1015         else if (text_size > maxtsiz)
 1016                 err_str = "Text segment size exceeds system limit";
 1017         else if (total_size > lim_cur_proc(imgp->proc, RLIMIT_VMEM))
 1018                 err_str = "Total segment size exceeds process limit";
 1019         else if (racct_set(imgp->proc, RACCT_DATA, data_size) != 0)
 1020                 err_str = "Data segment size exceeds resource limit";
 1021         else if (racct_set(imgp->proc, RACCT_VMEM, total_size) != 0)
 1022                 err_str = "Total segment size exceeds resource limit";
 1023         if (err_str != NULL) {
 1024                 PROC_UNLOCK(imgp->proc);
 1025                 uprintf("%s\n", err_str);
 1026                 error = ENOMEM;
 1027                 goto ret;
 1028         }
 1029 
 1030         vmspace = imgp->proc->p_vmspace;
 1031         vmspace->vm_tsize = text_size >> PAGE_SHIFT;
 1032         vmspace->vm_taddr = (caddr_t)(uintptr_t)text_addr;
 1033         vmspace->vm_dsize = data_size >> PAGE_SHIFT;
 1034         vmspace->vm_daddr = (caddr_t)(uintptr_t)data_addr;
 1035 
 1036         /*
 1037          * We load the dynamic linker where a userland call
 1038          * to mmap(0, ...) would put it.  The rationale behind this
 1039          * calculation is that it leaves room for the heap to grow to
 1040          * its maximum allowed size.
 1041          */
 1042         addr = round_page((vm_offset_t)vmspace->vm_daddr + lim_max(td,
 1043             RLIMIT_DATA));
 1044         PROC_UNLOCK(imgp->proc);
 1045 
 1046         imgp->entry_addr = entry;
 1047 
 1048         if (interp != NULL) {
 1049                 have_interp = FALSE;
 1050                 VOP_UNLOCK(imgp->vp, 0);
 1051                 if (brand_info->emul_path != NULL &&
 1052                     brand_info->emul_path[0] != '\0') {
 1053                         path = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
 1054                         snprintf(path, MAXPATHLEN, "%s%s",
 1055                             brand_info->emul_path, interp);
 1056                         error = __elfN(load_file)(imgp->proc, path, &addr,
 1057                             &imgp->entry_addr, sv->sv_pagesize);
 1058                         free(path, M_TEMP);
 1059                         if (error == 0)
 1060                                 have_interp = TRUE;
 1061                 }
 1062                 if (!have_interp && newinterp != NULL &&
 1063                     (brand_info->interp_path == NULL ||
 1064                     strcmp(interp, brand_info->interp_path) == 0)) {
 1065                         error = __elfN(load_file)(imgp->proc, newinterp, &addr,
 1066                             &imgp->entry_addr, sv->sv_pagesize);
 1067                         if (error == 0)
 1068                                 have_interp = TRUE;
 1069                 }
 1070                 if (!have_interp) {
 1071                         error = __elfN(load_file)(imgp->proc, interp, &addr,
 1072                             &imgp->entry_addr, sv->sv_pagesize);
 1073                 }
 1074                 vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
 1075                 if (error != 0) {
 1076                         uprintf("ELF interpreter %s not found, error %d\n",
 1077                             interp, error);
 1078                         goto ret;
 1079                 }
 1080         } else
 1081                 addr = et_dyn_addr;
 1082 
 1083         /*
 1084          * Construct auxargs table (used by the fixup routine)
 1085          */
 1086         elf_auxargs = malloc(sizeof(Elf_Auxargs), M_TEMP, M_WAITOK);
 1087         elf_auxargs->execfd = -1;
 1088         elf_auxargs->phdr = proghdr;
 1089         elf_auxargs->phent = hdr->e_phentsize;
 1090         elf_auxargs->phnum = hdr->e_phnum;
 1091         elf_auxargs->pagesz = PAGE_SIZE;
 1092         elf_auxargs->base = addr;
 1093         elf_auxargs->flags = 0;
 1094         elf_auxargs->entry = entry;
 1095         elf_auxargs->hdr_eflags = hdr->e_flags;
 1096 
 1097         imgp->auxargs = elf_auxargs;
 1098         imgp->interpreted = 0;
 1099         imgp->reloc_base = addr;
 1100         imgp->proc->p_osrel = osrel;
 1101         imgp->proc->p_elf_machine = hdr->e_machine;
 1102         imgp->proc->p_elf_flags = hdr->e_flags;
 1103 
 1104  ret:
 1105         free(interp_buf, M_TEMP);
 1106         return (error);
 1107 }
 1108 
 1109 #define suword __CONCAT(suword, __ELF_WORD_SIZE)
 1110 
 1111 int
 1112 __elfN(freebsd_fixup)(register_t **stack_base, struct image_params *imgp)
 1113 {
 1114         Elf_Auxargs *args = (Elf_Auxargs *)imgp->auxargs;
 1115         Elf_Addr *base;
 1116         Elf_Addr *pos;
 1117 
 1118         base = (Elf_Addr *)*stack_base;
 1119         pos = base + (imgp->args->argc + imgp->args->envc + 2);
 1120 
 1121         if (args->execfd != -1)
 1122                 AUXARGS_ENTRY(pos, AT_EXECFD, args->execfd);
 1123         AUXARGS_ENTRY(pos, AT_PHDR, args->phdr);
 1124         AUXARGS_ENTRY(pos, AT_PHENT, args->phent);
 1125         AUXARGS_ENTRY(pos, AT_PHNUM, args->phnum);
 1126         AUXARGS_ENTRY(pos, AT_PAGESZ, args->pagesz);
 1127         AUXARGS_ENTRY(pos, AT_FLAGS, args->flags);
 1128         AUXARGS_ENTRY(pos, AT_ENTRY, args->entry);
 1129         AUXARGS_ENTRY(pos, AT_BASE, args->base);
 1130         AUXARGS_ENTRY(pos, AT_EHDRFLAGS, args->hdr_eflags);
 1131         if (imgp->execpathp != 0)
 1132                 AUXARGS_ENTRY(pos, AT_EXECPATH, imgp->execpathp);
 1133         AUXARGS_ENTRY(pos, AT_OSRELDATE,
 1134             imgp->proc->p_ucred->cr_prison->pr_osreldate);
 1135         if (imgp->canary != 0) {
 1136                 AUXARGS_ENTRY(pos, AT_CANARY, imgp->canary);
 1137                 AUXARGS_ENTRY(pos, AT_CANARYLEN, imgp->canarylen);
 1138         }
 1139         AUXARGS_ENTRY(pos, AT_NCPUS, mp_ncpus);
 1140         if (imgp->pagesizes != 0) {
 1141                 AUXARGS_ENTRY(pos, AT_PAGESIZES, imgp->pagesizes);
 1142                 AUXARGS_ENTRY(pos, AT_PAGESIZESLEN, imgp->pagesizeslen);
 1143         }
 1144         if (imgp->sysent->sv_timekeep_base != 0) {
 1145                 AUXARGS_ENTRY(pos, AT_TIMEKEEP,
 1146                     imgp->sysent->sv_timekeep_base);
 1147         }
 1148         AUXARGS_ENTRY(pos, AT_STACKPROT, imgp->sysent->sv_shared_page_obj
 1149             != NULL && imgp->stack_prot != 0 ? imgp->stack_prot :
 1150             imgp->sysent->sv_stackprot);
 1151         if ((imgp->sysent->sv_flags & SV_HWCAP) != 0) {
 1152                 if (imgp->sysent->sv_hwcap != NULL)
 1153                         AUXARGS_ENTRY(pos, AT_HWCAP, *imgp->sysent->sv_hwcap);
 1154                 if (imgp->sysent->sv_hwcap2 != NULL)
 1155                         AUXARGS_ENTRY(pos, AT_HWCAP2, *imgp->sysent->sv_hwcap2);
 1156         }
 1157         AUXARGS_ENTRY(pos, AT_NULL, 0);
 1158 
 1159         free(imgp->auxargs, M_TEMP);
 1160         imgp->auxargs = NULL;
 1161 
 1162         base--;
 1163         suword(base, (long)imgp->args->argc);
 1164         *stack_base = (register_t *)base;
 1165         return (0);
 1166 }
 1167 
 1168 /*
 1169  * Code for generating ELF core dumps.
 1170  */
 1171 
 1172 typedef void (*segment_callback)(vm_map_entry_t, void *);
 1173 
 1174 /* Closure for cb_put_phdr(). */
 1175 struct phdr_closure {
 1176         Elf_Phdr *phdr;         /* Program header to fill in */
 1177         Elf_Off offset;         /* Offset of segment in core file */
 1178 };
 1179 
 1180 /* Closure for cb_size_segment(). */
 1181 struct sseg_closure {
 1182         int count;              /* Count of writable segments. */
 1183         size_t size;            /* Total size of all writable segments. */
 1184 };
 1185 
 1186 typedef void (*outfunc_t)(void *, struct sbuf *, size_t *);
 1187 
 1188 struct note_info {
 1189         int             type;           /* Note type. */
 1190         outfunc_t       outfunc;        /* Output function. */
 1191         void            *outarg;        /* Argument for the output function. */
 1192         size_t          outsize;        /* Output size. */
 1193         TAILQ_ENTRY(note_info) link;    /* Link to the next note info. */
 1194 };
 1195 
 1196 TAILQ_HEAD(note_info_list, note_info);
 1197 
 1198 /* Coredump output parameters. */
 1199 struct coredump_params {
 1200         off_t           offset;
 1201         struct ucred    *active_cred;
 1202         struct ucred    *file_cred;
 1203         struct thread   *td;
 1204         struct vnode    *vp;
 1205         struct gzio_stream *gzs;
 1206 };
 1207 
 1208 static void cb_put_phdr(vm_map_entry_t, void *);
 1209 static void cb_size_segment(vm_map_entry_t, void *);
 1210 static int core_write(struct coredump_params *, const void *, size_t, off_t,
 1211     enum uio_seg);
 1212 static void each_writable_segment(struct thread *, segment_callback, void *);
 1213 static int __elfN(corehdr)(struct coredump_params *, int, void *, size_t,
 1214     struct note_info_list *, size_t);
 1215 static void __elfN(prepare_notes)(struct thread *, struct note_info_list *,
 1216     size_t *);
 1217 static void __elfN(puthdr)(struct thread *, void *, size_t, int, size_t);
 1218 static void __elfN(putnote)(struct note_info *, struct sbuf *);
 1219 static size_t register_note(struct note_info_list *, int, outfunc_t, void *);
 1220 static int sbuf_drain_core_output(void *, const char *, int);
 1221 static int sbuf_drain_count(void *arg, const char *data, int len);
 1222 
 1223 static void __elfN(note_fpregset)(void *, struct sbuf *, size_t *);
 1224 static void __elfN(note_prpsinfo)(void *, struct sbuf *, size_t *);
 1225 static void __elfN(note_prstatus)(void *, struct sbuf *, size_t *);
 1226 static void __elfN(note_threadmd)(void *, struct sbuf *, size_t *);
 1227 static void __elfN(note_thrmisc)(void *, struct sbuf *, size_t *);
 1228 static void __elfN(note_ptlwpinfo)(void *, struct sbuf *, size_t *);
 1229 static void __elfN(note_procstat_auxv)(void *, struct sbuf *, size_t *);
 1230 static void __elfN(note_procstat_proc)(void *, struct sbuf *, size_t *);
 1231 static void __elfN(note_procstat_psstrings)(void *, struct sbuf *, size_t *);
 1232 static void note_procstat_files(void *, struct sbuf *, size_t *);
 1233 static void note_procstat_groups(void *, struct sbuf *, size_t *);
 1234 static void note_procstat_osrel(void *, struct sbuf *, size_t *);
 1235 static void note_procstat_rlimit(void *, struct sbuf *, size_t *);
 1236 static void note_procstat_umask(void *, struct sbuf *, size_t *);
 1237 static void note_procstat_vmmap(void *, struct sbuf *, size_t *);
 1238 
 1239 #ifdef GZIO
 1240 extern int compress_user_cores_gzlevel;
 1241 
 1242 /*
 1243  * Write out a core segment to the compression stream.
 1244  */
 1245 static int
 1246 compress_chunk(struct coredump_params *p, char *base, char *buf, u_int len)
 1247 {
 1248         u_int chunk_len;
 1249         int error;
 1250 
 1251         while (len > 0) {
 1252                 chunk_len = MIN(len, CORE_BUF_SIZE);
 1253 
 1254                 /*
 1255                  * We can get EFAULT error here.
 1256                  * In that case zero out the current chunk of the segment.
 1257                  */
 1258                 error = copyin(base, buf, chunk_len);
 1259                 if (error != 0)
 1260                         bzero(buf, chunk_len);
 1261                 error = gzio_write(p->gzs, buf, chunk_len);
 1262                 if (error != 0)
 1263                         break;
 1264                 base += chunk_len;
 1265                 len -= chunk_len;
 1266         }
 1267         return (error);
 1268 }
 1269 
 1270 static int
 1271 core_gz_write(void *base, size_t len, off_t offset, void *arg)
 1272 {
 1273 
 1274         return (core_write((struct coredump_params *)arg, base, len, offset,
 1275             UIO_SYSSPACE));
 1276 }
 1277 #endif /* GZIO */
 1278 
 1279 static int
 1280 core_write(struct coredump_params *p, const void *base, size_t len,
 1281     off_t offset, enum uio_seg seg)
 1282 {
 1283 
 1284         return (vn_rdwr_inchunks(UIO_WRITE, p->vp, __DECONST(void *, base),
 1285             len, offset, seg, IO_UNIT | IO_DIRECT | IO_RANGELOCKED,
 1286             p->active_cred, p->file_cred, NULL, p->td));
 1287 }
 1288 
 1289 static int
 1290 core_output(void *base, size_t len, off_t offset, struct coredump_params *p,
 1291     void *tmpbuf)
 1292 {
 1293         int error;
 1294 
 1295 #ifdef GZIO
 1296         if (p->gzs != NULL)
 1297                 return (compress_chunk(p, base, tmpbuf, len));
 1298 #endif
 1299         /*
 1300          * EFAULT is a non-fatal error that we can get, for example,
 1301          * if the segment is backed by a file but extends beyond its
 1302          * end.
 1303          */
 1304         error = core_write(p, base, len, offset, UIO_USERSPACE);
 1305         if (error == EFAULT) {
 1306                 log(LOG_WARNING, "Failed to fully fault in a core file segment "
 1307                     "at VA %p with size 0x%zx to be written at offset 0x%jx "
 1308                     "for process %s\n", base, len, offset, curproc->p_comm);
 1309 
 1310                 /*
 1311                  * Write a "real" zero byte at the end of the target region
 1312                  * in the case this is the last segment.
 1313                  * The intermediate space will be implicitly zero-filled.
 1314                  */
 1315                 error = core_write(p, zero_region, 1, offset + len - 1,
 1316                     UIO_SYSSPACE);
 1317         }
 1318         return (error);
 1319 }
 1320 
 1321 /*
 1322  * Drain into a core file.
 1323  */
 1324 static int
 1325 sbuf_drain_core_output(void *arg, const char *data, int len)
 1326 {
 1327         struct coredump_params *p;
 1328         int error, locked;
 1329 
 1330         p = (struct coredump_params *)arg;
 1331 
 1332         /*
 1333          * Some kern_proc out routines that print to this sbuf may
 1334          * call us with the process lock held. Draining with the
 1335          * non-sleepable lock held is unsafe. The lock is needed for
 1336          * those routines when dumping a live process. In our case we
 1337          * can safely release the lock before draining and acquire
 1338          * again after.
 1339          */
 1340         locked = PROC_LOCKED(p->td->td_proc);
 1341         if (locked)
 1342                 PROC_UNLOCK(p->td->td_proc);
 1343 #ifdef GZIO
 1344         if (p->gzs != NULL)
 1345                 error = gzio_write(p->gzs, __DECONST(char *, data), len);
 1346         else
 1347 #endif
 1348                 error = core_write(p, __DECONST(void *, data), len, p->offset,
 1349                     UIO_SYSSPACE);
 1350         if (locked)
 1351                 PROC_LOCK(p->td->td_proc);
 1352         if (error != 0)
 1353                 return (-error);
 1354         p->offset += len;
 1355         return (len);
 1356 }
 1357 
 1358 /*
 1359  * Drain into a counter.
 1360  */
 1361 static int
 1362 sbuf_drain_count(void *arg, const char *data __unused, int len)
 1363 {
 1364         size_t *sizep;
 1365 
 1366         sizep = (size_t *)arg;
 1367         *sizep += len;
 1368         return (len);
 1369 }
 1370 
 1371 int
 1372 __elfN(coredump)(struct thread *td, struct vnode *vp, off_t limit, int flags)
 1373 {
 1374         struct ucred *cred = td->td_ucred;
 1375         int error = 0;
 1376         struct sseg_closure seginfo;
 1377         struct note_info_list notelst;
 1378         struct coredump_params params;
 1379         struct note_info *ninfo;
 1380         void *hdr, *tmpbuf;
 1381         size_t hdrsize, notesz, coresize;
 1382 #ifdef GZIO
 1383         boolean_t compress;
 1384 
 1385         compress = (flags & IMGACT_CORE_COMPRESS) != 0;
 1386 #endif
 1387         hdr = NULL;
 1388         tmpbuf = NULL;
 1389         TAILQ_INIT(&notelst);
 1390 
 1391         /* Size the program segments. */
 1392         seginfo.count = 0;
 1393         seginfo.size = 0;
 1394         each_writable_segment(td, cb_size_segment, &seginfo);
 1395 
 1396         /*
 1397          * Collect info about the core file header area.
 1398          */
 1399         hdrsize = sizeof(Elf_Ehdr) + sizeof(Elf_Phdr) * (1 + seginfo.count);
 1400         __elfN(prepare_notes)(td, &notelst, &notesz);
 1401         coresize = round_page(hdrsize + notesz) + seginfo.size;
 1402 
 1403         /* Set up core dump parameters. */
 1404         params.offset = 0;
 1405         params.active_cred = cred;
 1406         params.file_cred = NOCRED;
 1407         params.td = td;
 1408         params.vp = vp;
 1409         params.gzs = NULL;
 1410 
 1411 #ifdef RACCT
 1412         if (racct_enable) {
 1413                 PROC_LOCK(td->td_proc);
 1414                 error = racct_add(td->td_proc, RACCT_CORE, coresize);
 1415                 PROC_UNLOCK(td->td_proc);
 1416                 if (error != 0) {
 1417                         error = EFAULT;
 1418                         goto done;
 1419                 }
 1420         }
 1421 #endif
 1422         if (coresize >= limit) {
 1423                 error = EFAULT;
 1424                 goto done;
 1425         }
 1426 
 1427 #ifdef GZIO
 1428         /* Create a compression stream if necessary. */
 1429         if (compress) {
 1430                 params.gzs = gzio_init(core_gz_write, GZIO_DEFLATE,
 1431                     CORE_BUF_SIZE, compress_user_cores_gzlevel, &params);
 1432                 if (params.gzs == NULL) {
 1433                         error = EFAULT;
 1434                         goto done;
 1435                 }
 1436                 tmpbuf = malloc(CORE_BUF_SIZE, M_TEMP, M_WAITOK | M_ZERO);
 1437         }
 1438 #endif
 1439 
 1440         /*
 1441          * Allocate memory for building the header, fill it up,
 1442          * and write it out following the notes.
 1443          */
 1444         hdr = malloc(hdrsize, M_TEMP, M_WAITOK);
 1445         error = __elfN(corehdr)(&params, seginfo.count, hdr, hdrsize, &notelst,
 1446             notesz);
 1447 
 1448         /* Write the contents of all of the writable segments. */
 1449         if (error == 0) {
 1450                 Elf_Phdr *php;
 1451                 off_t offset;
 1452                 int i;
 1453 
 1454                 php = (Elf_Phdr *)((char *)hdr + sizeof(Elf_Ehdr)) + 1;
 1455                 offset = round_page(hdrsize + notesz);
 1456                 for (i = 0; i < seginfo.count; i++) {
 1457                         error = core_output((caddr_t)(uintptr_t)php->p_vaddr,
 1458                             php->p_filesz, offset, &params, tmpbuf);
 1459                         if (error != 0)
 1460                                 break;
 1461                         offset += php->p_filesz;
 1462                         php++;
 1463                 }
 1464 #ifdef GZIO
 1465                 if (error == 0 && compress)
 1466                         error = gzio_flush(params.gzs);
 1467 #endif
 1468         }
 1469         if (error) {
 1470                 log(LOG_WARNING,
 1471                     "Failed to write core file for process %s (error %d)\n",
 1472                     curproc->p_comm, error);
 1473         }
 1474 
 1475 done:
 1476 #ifdef GZIO
 1477         if (compress) {
 1478                 free(tmpbuf, M_TEMP);
 1479                 if (params.gzs != NULL)
 1480                         gzio_fini(params.gzs);
 1481         }
 1482 #endif
 1483         while ((ninfo = TAILQ_FIRST(&notelst)) != NULL) {
 1484                 TAILQ_REMOVE(&notelst, ninfo, link);
 1485                 free(ninfo, M_TEMP);
 1486         }
 1487         if (hdr != NULL)
 1488                 free(hdr, M_TEMP);
 1489 
 1490         return (error);
 1491 }
 1492 
 1493 /*
 1494  * A callback for each_writable_segment() to write out the segment's
 1495  * program header entry.
 1496  */
 1497 static void
 1498 cb_put_phdr(entry, closure)
 1499         vm_map_entry_t entry;
 1500         void *closure;
 1501 {
 1502         struct phdr_closure *phc = (struct phdr_closure *)closure;
 1503         Elf_Phdr *phdr = phc->phdr;
 1504 
 1505         phc->offset = round_page(phc->offset);
 1506 
 1507         phdr->p_type = PT_LOAD;
 1508         phdr->p_offset = phc->offset;
 1509         phdr->p_vaddr = entry->start;
 1510         phdr->p_paddr = 0;
 1511         phdr->p_filesz = phdr->p_memsz = entry->end - entry->start;
 1512         phdr->p_align = PAGE_SIZE;
 1513         phdr->p_flags = __elfN(untrans_prot)(entry->protection);
 1514 
 1515         phc->offset += phdr->p_filesz;
 1516         phc->phdr++;
 1517 }
 1518 
 1519 /*
 1520  * A callback for each_writable_segment() to gather information about
 1521  * the number of segments and their total size.
 1522  */
 1523 static void
 1524 cb_size_segment(entry, closure)
 1525         vm_map_entry_t entry;
 1526         void *closure;
 1527 {
 1528         struct sseg_closure *ssc = (struct sseg_closure *)closure;
 1529 
 1530         ssc->count++;
 1531         ssc->size += entry->end - entry->start;
 1532 }
 1533 
 1534 /*
 1535  * For each writable segment in the process's memory map, call the given
 1536  * function with a pointer to the map entry and some arbitrary
 1537  * caller-supplied data.
 1538  */
 1539 static void
 1540 each_writable_segment(td, func, closure)
 1541         struct thread *td;
 1542         segment_callback func;
 1543         void *closure;
 1544 {
 1545         struct proc *p = td->td_proc;
 1546         vm_map_t map = &p->p_vmspace->vm_map;
 1547         vm_map_entry_t entry;
 1548         vm_object_t backing_object, object;
 1549         boolean_t ignore_entry;
 1550 
 1551         vm_map_lock_read(map);
 1552         for (entry = map->header.next; entry != &map->header;
 1553             entry = entry->next) {
 1554                 /*
 1555                  * Don't dump inaccessible mappings, deal with legacy
 1556                  * coredump mode.
 1557                  *
 1558                  * Note that read-only segments related to the elf binary
 1559                  * are marked MAP_ENTRY_NOCOREDUMP now so we no longer
 1560                  * need to arbitrarily ignore such segments.
 1561                  */
 1562                 if (elf_legacy_coredump) {
 1563                         if ((entry->protection & VM_PROT_RW) != VM_PROT_RW)
 1564                                 continue;
 1565                 } else {
 1566                         if ((entry->protection & VM_PROT_ALL) == 0)
 1567                                 continue;
 1568                 }
 1569 
 1570                 /*
 1571                  * Dont include memory segment in the coredump if
 1572                  * MAP_NOCORE is set in mmap(2) or MADV_NOCORE in
 1573                  * madvise(2).  Do not dump submaps (i.e. parts of the
 1574                  * kernel map).
 1575                  */
 1576                 if (entry->eflags & (MAP_ENTRY_NOCOREDUMP|MAP_ENTRY_IS_SUB_MAP))
 1577                         continue;
 1578 
 1579                 if ((object = entry->object.vm_object) == NULL)
 1580                         continue;
 1581 
 1582                 /* Ignore memory-mapped devices and such things. */
 1583                 VM_OBJECT_RLOCK(object);
 1584                 while ((backing_object = object->backing_object) != NULL) {
 1585                         VM_OBJECT_RLOCK(backing_object);
 1586                         VM_OBJECT_RUNLOCK(object);
 1587                         object = backing_object;
 1588                 }
 1589                 ignore_entry = object->type != OBJT_DEFAULT &&
 1590                     object->type != OBJT_SWAP && object->type != OBJT_VNODE &&
 1591                     object->type != OBJT_PHYS;
 1592                 VM_OBJECT_RUNLOCK(object);
 1593                 if (ignore_entry)
 1594                         continue;
 1595 
 1596                 (*func)(entry, closure);
 1597         }
 1598         vm_map_unlock_read(map);
 1599 }
 1600 
 1601 /*
 1602  * Write the core file header to the file, including padding up to
 1603  * the page boundary.
 1604  */
 1605 static int
 1606 __elfN(corehdr)(struct coredump_params *p, int numsegs, void *hdr,
 1607     size_t hdrsize, struct note_info_list *notelst, size_t notesz)
 1608 {
 1609         struct note_info *ninfo;
 1610         struct sbuf *sb;
 1611         int error;
 1612 
 1613         /* Fill in the header. */
 1614         bzero(hdr, hdrsize);
 1615         __elfN(puthdr)(p->td, hdr, hdrsize, numsegs, notesz);
 1616 
 1617         sb = sbuf_new(NULL, NULL, CORE_BUF_SIZE, SBUF_FIXEDLEN);
 1618         sbuf_set_drain(sb, sbuf_drain_core_output, p);
 1619         sbuf_start_section(sb, NULL);
 1620         sbuf_bcat(sb, hdr, hdrsize);
 1621         TAILQ_FOREACH(ninfo, notelst, link)
 1622             __elfN(putnote)(ninfo, sb);
 1623         /* Align up to a page boundary for the program segments. */
 1624         sbuf_end_section(sb, -1, PAGE_SIZE, 0);
 1625         error = sbuf_finish(sb);
 1626         sbuf_delete(sb);
 1627 
 1628         return (error);
 1629 }
 1630 
 1631 static void
 1632 __elfN(prepare_notes)(struct thread *td, struct note_info_list *list,
 1633     size_t *sizep)
 1634 {
 1635         struct proc *p;
 1636         struct thread *thr;
 1637         size_t size;
 1638 
 1639         p = td->td_proc;
 1640         size = 0;
 1641 
 1642         size += register_note(list, NT_PRPSINFO, __elfN(note_prpsinfo), p);
 1643 
 1644         /*
 1645          * To have the debugger select the right thread (LWP) as the initial
 1646          * thread, we dump the state of the thread passed to us in td first.
 1647          * This is the thread that causes the core dump and thus likely to
 1648          * be the right thread one wants to have selected in the debugger.
 1649          */
 1650         thr = td;
 1651         while (thr != NULL) {
 1652                 size += register_note(list, NT_PRSTATUS,
 1653                     __elfN(note_prstatus), thr);
 1654                 size += register_note(list, NT_FPREGSET,
 1655                     __elfN(note_fpregset), thr);
 1656                 size += register_note(list, NT_THRMISC,
 1657                     __elfN(note_thrmisc), thr);
 1658                 size += register_note(list, NT_PTLWPINFO,
 1659                     __elfN(note_ptlwpinfo), thr);
 1660                 size += register_note(list, -1,
 1661                     __elfN(note_threadmd), thr);
 1662 
 1663                 thr = (thr == td) ? TAILQ_FIRST(&p->p_threads) :
 1664                     TAILQ_NEXT(thr, td_plist);
 1665                 if (thr == td)
 1666                         thr = TAILQ_NEXT(thr, td_plist);
 1667         }
 1668 
 1669         size += register_note(list, NT_PROCSTAT_PROC,
 1670             __elfN(note_procstat_proc), p);
 1671         size += register_note(list, NT_PROCSTAT_FILES,
 1672             note_procstat_files, p);
 1673         size += register_note(list, NT_PROCSTAT_VMMAP,
 1674             note_procstat_vmmap, p);
 1675         size += register_note(list, NT_PROCSTAT_GROUPS,
 1676             note_procstat_groups, p);
 1677         size += register_note(list, NT_PROCSTAT_UMASK,
 1678             note_procstat_umask, p);
 1679         size += register_note(list, NT_PROCSTAT_RLIMIT,
 1680             note_procstat_rlimit, p);
 1681         size += register_note(list, NT_PROCSTAT_OSREL,
 1682             note_procstat_osrel, p);
 1683         size += register_note(list, NT_PROCSTAT_PSSTRINGS,
 1684             __elfN(note_procstat_psstrings), p);
 1685         size += register_note(list, NT_PROCSTAT_AUXV,
 1686             __elfN(note_procstat_auxv), p);
 1687 
 1688         *sizep = size;
 1689 }
 1690 
 1691 static void
 1692 __elfN(puthdr)(struct thread *td, void *hdr, size_t hdrsize, int numsegs,
 1693     size_t notesz)
 1694 {
 1695         Elf_Ehdr *ehdr;
 1696         Elf_Phdr *phdr;
 1697         struct phdr_closure phc;
 1698 
 1699         ehdr = (Elf_Ehdr *)hdr;
 1700         phdr = (Elf_Phdr *)((char *)hdr + sizeof(Elf_Ehdr));
 1701 
 1702         ehdr->e_ident[EI_MAG0] = ELFMAG0;
 1703         ehdr->e_ident[EI_MAG1] = ELFMAG1;
 1704         ehdr->e_ident[EI_MAG2] = ELFMAG2;
 1705         ehdr->e_ident[EI_MAG3] = ELFMAG3;
 1706         ehdr->e_ident[EI_CLASS] = ELF_CLASS;
 1707         ehdr->e_ident[EI_DATA] = ELF_DATA;
 1708         ehdr->e_ident[EI_VERSION] = EV_CURRENT;
 1709         ehdr->e_ident[EI_OSABI] = ELFOSABI_FREEBSD;
 1710         ehdr->e_ident[EI_ABIVERSION] = 0;
 1711         ehdr->e_ident[EI_PAD] = 0;
 1712         ehdr->e_type = ET_CORE;
 1713         ehdr->e_machine = td->td_proc->p_elf_machine;
 1714         ehdr->e_version = EV_CURRENT;
 1715         ehdr->e_entry = 0;
 1716         ehdr->e_phoff = sizeof(Elf_Ehdr);
 1717         ehdr->e_flags = td->td_proc->p_elf_flags;
 1718         ehdr->e_ehsize = sizeof(Elf_Ehdr);
 1719         ehdr->e_phentsize = sizeof(Elf_Phdr);
 1720         ehdr->e_phnum = numsegs + 1;
 1721         ehdr->e_shentsize = sizeof(Elf_Shdr);
 1722         ehdr->e_shnum = 0;
 1723         ehdr->e_shstrndx = SHN_UNDEF;
 1724 
 1725         /*
 1726          * Fill in the program header entries.
 1727          */
 1728 
 1729         /* The note segement. */
 1730         phdr->p_type = PT_NOTE;
 1731         phdr->p_offset = hdrsize;
 1732         phdr->p_vaddr = 0;
 1733         phdr->p_paddr = 0;
 1734         phdr->p_filesz = notesz;
 1735         phdr->p_memsz = 0;
 1736         phdr->p_flags = PF_R;
 1737         phdr->p_align = ELF_NOTE_ROUNDSIZE;
 1738         phdr++;
 1739 
 1740         /* All the writable segments from the program. */
 1741         phc.phdr = phdr;
 1742         phc.offset = round_page(hdrsize + notesz);
 1743         each_writable_segment(td, cb_put_phdr, &phc);
 1744 }
 1745 
 1746 static size_t
 1747 register_note(struct note_info_list *list, int type, outfunc_t out, void *arg)
 1748 {
 1749         struct note_info *ninfo;
 1750         size_t size, notesize;
 1751 
 1752         size = 0;
 1753         out(arg, NULL, &size);
 1754         ninfo = malloc(sizeof(*ninfo), M_TEMP, M_ZERO | M_WAITOK);
 1755         ninfo->type = type;
 1756         ninfo->outfunc = out;
 1757         ninfo->outarg = arg;
 1758         ninfo->outsize = size;
 1759         TAILQ_INSERT_TAIL(list, ninfo, link);
 1760 
 1761         if (type == -1)
 1762                 return (size);
 1763 
 1764         notesize = sizeof(Elf_Note) +           /* note header */
 1765             roundup2(sizeof(FREEBSD_ABI_VENDOR), ELF_NOTE_ROUNDSIZE) +
 1766                                                 /* note name */
 1767             roundup2(size, ELF_NOTE_ROUNDSIZE); /* note description */
 1768 
 1769         return (notesize);
 1770 }
 1771 
 1772 static size_t
 1773 append_note_data(const void *src, void *dst, size_t len)
 1774 {
 1775         size_t padded_len;
 1776 
 1777         padded_len = roundup2(len, ELF_NOTE_ROUNDSIZE);
 1778         if (dst != NULL) {
 1779                 bcopy(src, dst, len);
 1780                 bzero((char *)dst + len, padded_len - len);
 1781         }
 1782         return (padded_len);
 1783 }
 1784 
 1785 size_t
 1786 __elfN(populate_note)(int type, void *src, void *dst, size_t size, void **descp)
 1787 {
 1788         Elf_Note *note;
 1789         char *buf;
 1790         size_t notesize;
 1791 
 1792         buf = dst;
 1793         if (buf != NULL) {
 1794                 note = (Elf_Note *)buf;
 1795                 note->n_namesz = sizeof(FREEBSD_ABI_VENDOR);
 1796                 note->n_descsz = size;
 1797                 note->n_type = type;
 1798                 buf += sizeof(*note);
 1799                 buf += append_note_data(FREEBSD_ABI_VENDOR, buf,
 1800                     sizeof(FREEBSD_ABI_VENDOR));
 1801                 append_note_data(src, buf, size);
 1802                 if (descp != NULL)
 1803                         *descp = buf;
 1804         }
 1805 
 1806         notesize = sizeof(Elf_Note) +           /* note header */
 1807             roundup2(sizeof(FREEBSD_ABI_VENDOR), ELF_NOTE_ROUNDSIZE) +
 1808                                                 /* note name */
 1809             roundup2(size, ELF_NOTE_ROUNDSIZE); /* note description */
 1810 
 1811         return (notesize);
 1812 }
 1813 
 1814 static void
 1815 __elfN(putnote)(struct note_info *ninfo, struct sbuf *sb)
 1816 {
 1817         Elf_Note note;
 1818         ssize_t old_len, sect_len;
 1819         size_t new_len, descsz, i;
 1820 
 1821         if (ninfo->type == -1) {
 1822                 ninfo->outfunc(ninfo->outarg, sb, &ninfo->outsize);
 1823                 return;
 1824         }
 1825 
 1826         note.n_namesz = sizeof(FREEBSD_ABI_VENDOR);
 1827         note.n_descsz = ninfo->outsize;
 1828         note.n_type = ninfo->type;
 1829 
 1830         sbuf_bcat(sb, &note, sizeof(note));
 1831         sbuf_start_section(sb, &old_len);
 1832         sbuf_bcat(sb, FREEBSD_ABI_VENDOR, sizeof(FREEBSD_ABI_VENDOR));
 1833         sbuf_end_section(sb, old_len, ELF_NOTE_ROUNDSIZE, 0);
 1834         if (note.n_descsz == 0)
 1835                 return;
 1836         sbuf_start_section(sb, &old_len);
 1837         ninfo->outfunc(ninfo->outarg, sb, &ninfo->outsize);
 1838         sect_len = sbuf_end_section(sb, old_len, ELF_NOTE_ROUNDSIZE, 0);
 1839         if (sect_len < 0)
 1840                 return;
 1841 
 1842         new_len = (size_t)sect_len;
 1843         descsz = roundup(note.n_descsz, ELF_NOTE_ROUNDSIZE);
 1844         if (new_len < descsz) {
 1845                 /*
 1846                  * It is expected that individual note emitters will correctly
 1847                  * predict their expected output size and fill up to that size
 1848                  * themselves, padding in a format-specific way if needed.
 1849                  * However, in case they don't, just do it here with zeros.
 1850                  */
 1851                 for (i = 0; i < descsz - new_len; i++)
 1852                         sbuf_putc(sb, 0);
 1853         } else if (new_len > descsz) {
 1854                 /*
 1855                  * We can't always truncate sb -- we may have drained some
 1856                  * of it already.
 1857                  */
 1858                 KASSERT(new_len == descsz, ("%s: Note type %u changed as we "
 1859                     "read it (%zu > %zu).  Since it is longer than "
 1860                     "expected, this coredump's notes are corrupt.  THIS "
 1861                     "IS A BUG in the note_procstat routine for type %u.\n",
 1862                     __func__, (unsigned)note.n_type, new_len, descsz,
 1863                     (unsigned)note.n_type));
 1864         }
 1865 }
 1866 
 1867 /*
 1868  * Miscellaneous note out functions.
 1869  */
 1870 
 1871 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
 1872 #include <compat/freebsd32/freebsd32.h>
 1873 #include <compat/freebsd32/freebsd32_signal.h>
 1874 
 1875 typedef struct prstatus32 elf_prstatus_t;
 1876 typedef struct prpsinfo32 elf_prpsinfo_t;
 1877 typedef struct fpreg32 elf_prfpregset_t;
 1878 typedef struct fpreg32 elf_fpregset_t;
 1879 typedef struct reg32 elf_gregset_t;
 1880 typedef struct thrmisc32 elf_thrmisc_t;
 1881 #define ELF_KERN_PROC_MASK      KERN_PROC_MASK32
 1882 typedef struct kinfo_proc32 elf_kinfo_proc_t;
 1883 typedef uint32_t elf_ps_strings_t;
 1884 #else
 1885 typedef prstatus_t elf_prstatus_t;
 1886 typedef prpsinfo_t elf_prpsinfo_t;
 1887 typedef prfpregset_t elf_prfpregset_t;
 1888 typedef prfpregset_t elf_fpregset_t;
 1889 typedef gregset_t elf_gregset_t;
 1890 typedef thrmisc_t elf_thrmisc_t;
 1891 #define ELF_KERN_PROC_MASK      0
 1892 typedef struct kinfo_proc elf_kinfo_proc_t;
 1893 typedef vm_offset_t elf_ps_strings_t;
 1894 #endif
 1895 
 1896 static void
 1897 __elfN(note_prpsinfo)(void *arg, struct sbuf *sb, size_t *sizep)
 1898 {
 1899         struct sbuf sbarg;
 1900         size_t len;
 1901         char *cp, *end;
 1902         struct proc *p;
 1903         elf_prpsinfo_t *psinfo;
 1904         int error;
 1905 
 1906         p = (struct proc *)arg;
 1907         if (sb != NULL) {
 1908                 KASSERT(*sizep == sizeof(*psinfo), ("invalid size"));
 1909                 psinfo = malloc(sizeof(*psinfo), M_TEMP, M_ZERO | M_WAITOK);
 1910                 psinfo->pr_version = PRPSINFO_VERSION;
 1911                 psinfo->pr_psinfosz = sizeof(elf_prpsinfo_t);
 1912                 strlcpy(psinfo->pr_fname, p->p_comm, sizeof(psinfo->pr_fname));
 1913                 PROC_LOCK(p);
 1914                 if (p->p_args != NULL) {
 1915                         len = sizeof(psinfo->pr_psargs) - 1;
 1916                         if (len > p->p_args->ar_length)
 1917                                 len = p->p_args->ar_length;
 1918                         memcpy(psinfo->pr_psargs, p->p_args->ar_args, len);
 1919                         PROC_UNLOCK(p);
 1920                         error = 0;
 1921                 } else {
 1922                         _PHOLD(p);
 1923                         PROC_UNLOCK(p);
 1924                         sbuf_new(&sbarg, psinfo->pr_psargs,
 1925                             sizeof(psinfo->pr_psargs), SBUF_FIXEDLEN);
 1926                         error = proc_getargv(curthread, p, &sbarg);
 1927                         PRELE(p);
 1928                         if (sbuf_finish(&sbarg) == 0)
 1929                                 len = sbuf_len(&sbarg) - 1;
 1930                         else
 1931                                 len = sizeof(psinfo->pr_psargs) - 1;
 1932                         sbuf_delete(&sbarg);
 1933                 }
 1934                 if (error || len == 0)
 1935                         strlcpy(psinfo->pr_psargs, p->p_comm,
 1936                             sizeof(psinfo->pr_psargs));
 1937                 else {
 1938                         KASSERT(len < sizeof(psinfo->pr_psargs),
 1939                             ("len is too long: %zu vs %zu", len,
 1940                             sizeof(psinfo->pr_psargs)));
 1941                         cp = psinfo->pr_psargs;
 1942                         end = cp + len - 1;
 1943                         for (;;) {
 1944                                 cp = memchr(cp, '\0', end - cp);
 1945                                 if (cp == NULL)
 1946                                         break;
 1947                                 *cp = ' ';
 1948                         }
 1949                 }
 1950                 psinfo->pr_pid = p->p_pid;
 1951                 sbuf_bcat(sb, psinfo, sizeof(*psinfo));
 1952                 free(psinfo, M_TEMP);
 1953         }
 1954         *sizep = sizeof(*psinfo);
 1955 }
 1956 
 1957 static void
 1958 __elfN(note_prstatus)(void *arg, struct sbuf *sb, size_t *sizep)
 1959 {
 1960         struct thread *td;
 1961         elf_prstatus_t *status;
 1962 
 1963         td = (struct thread *)arg;
 1964         if (sb != NULL) {
 1965                 KASSERT(*sizep == sizeof(*status), ("invalid size"));
 1966                 status = malloc(sizeof(*status), M_TEMP, M_ZERO | M_WAITOK);
 1967                 status->pr_version = PRSTATUS_VERSION;
 1968                 status->pr_statussz = sizeof(elf_prstatus_t);
 1969                 status->pr_gregsetsz = sizeof(elf_gregset_t);
 1970                 status->pr_fpregsetsz = sizeof(elf_fpregset_t);
 1971                 status->pr_osreldate = osreldate;
 1972                 status->pr_cursig = td->td_proc->p_sig;
 1973                 status->pr_pid = td->td_tid;
 1974 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
 1975                 fill_regs32(td, &status->pr_reg);
 1976 #else
 1977                 fill_regs(td, &status->pr_reg);
 1978 #endif
 1979                 sbuf_bcat(sb, status, sizeof(*status));
 1980                 free(status, M_TEMP);
 1981         }
 1982         *sizep = sizeof(*status);
 1983 }
 1984 
 1985 static void
 1986 __elfN(note_fpregset)(void *arg, struct sbuf *sb, size_t *sizep)
 1987 {
 1988         struct thread *td;
 1989         elf_prfpregset_t *fpregset;
 1990 
 1991         td = (struct thread *)arg;
 1992         if (sb != NULL) {
 1993                 KASSERT(*sizep == sizeof(*fpregset), ("invalid size"));
 1994                 fpregset = malloc(sizeof(*fpregset), M_TEMP, M_ZERO | M_WAITOK);
 1995 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
 1996                 fill_fpregs32(td, fpregset);
 1997 #else
 1998                 fill_fpregs(td, fpregset);
 1999 #endif
 2000                 sbuf_bcat(sb, fpregset, sizeof(*fpregset));
 2001                 free(fpregset, M_TEMP);
 2002         }
 2003         *sizep = sizeof(*fpregset);
 2004 }
 2005 
 2006 static void
 2007 __elfN(note_thrmisc)(void *arg, struct sbuf *sb, size_t *sizep)
 2008 {
 2009         struct thread *td;
 2010         elf_thrmisc_t thrmisc;
 2011 
 2012         td = (struct thread *)arg;
 2013         if (sb != NULL) {
 2014                 KASSERT(*sizep == sizeof(thrmisc), ("invalid size"));
 2015                 bzero(&thrmisc, sizeof(thrmisc));
 2016                 strcpy(thrmisc.pr_tname, td->td_name);
 2017                 sbuf_bcat(sb, &thrmisc, sizeof(thrmisc));
 2018         }
 2019         *sizep = sizeof(thrmisc);
 2020 }
 2021 
 2022 static void
 2023 __elfN(note_ptlwpinfo)(void *arg, struct sbuf *sb, size_t *sizep)
 2024 {
 2025         struct thread *td;
 2026         size_t size;
 2027         int structsize;
 2028 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
 2029         struct ptrace_lwpinfo32 pl;
 2030 #else
 2031         struct ptrace_lwpinfo pl;
 2032 #endif
 2033 
 2034         td = (struct thread *)arg;
 2035         size = sizeof(structsize) + sizeof(pl);
 2036         if (sb != NULL) {
 2037                 KASSERT(*sizep == size, ("invalid size"));
 2038                 structsize = sizeof(pl);
 2039                 sbuf_bcat(sb, &structsize, sizeof(structsize));
 2040                 bzero(&pl, sizeof(pl));
 2041                 pl.pl_lwpid = td->td_tid;
 2042                 pl.pl_event = PL_EVENT_NONE;
 2043                 pl.pl_sigmask = td->td_sigmask;
 2044                 pl.pl_siglist = td->td_siglist;
 2045                 if (td->td_si.si_signo != 0) {
 2046                         pl.pl_event = PL_EVENT_SIGNAL;
 2047                         pl.pl_flags |= PL_FLAG_SI;
 2048 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
 2049                         siginfo_to_siginfo32(&td->td_si, &pl.pl_siginfo);
 2050 #else
 2051                         pl.pl_siginfo = td->td_si;
 2052 #endif
 2053                 }
 2054                 strcpy(pl.pl_tdname, td->td_name);
 2055                 /* XXX TODO: supply more information in struct ptrace_lwpinfo*/
 2056                 sbuf_bcat(sb, &pl, sizeof(pl));
 2057         }
 2058         *sizep = size;
 2059 }
 2060 
 2061 /*
 2062  * Allow for MD specific notes, as well as any MD
 2063  * specific preparations for writing MI notes.
 2064  */
 2065 static void
 2066 __elfN(note_threadmd)(void *arg, struct sbuf *sb, size_t *sizep)
 2067 {
 2068         struct thread *td;
 2069         void *buf;
 2070         size_t size;
 2071 
 2072         td = (struct thread *)arg;
 2073         size = *sizep;
 2074         if (size != 0 && sb != NULL)
 2075                 buf = malloc(size, M_TEMP, M_ZERO | M_WAITOK);
 2076         else
 2077                 buf = NULL;
 2078         size = 0;
 2079         __elfN(dump_thread)(td, buf, &size);
 2080         KASSERT(sb == NULL || *sizep == size, ("invalid size"));
 2081         if (size != 0 && sb != NULL)
 2082                 sbuf_bcat(sb, buf, size);
 2083         free(buf, M_TEMP);
 2084         *sizep = size;
 2085 }
 2086 
 2087 #ifdef KINFO_PROC_SIZE
 2088 CTASSERT(sizeof(struct kinfo_proc) == KINFO_PROC_SIZE);
 2089 #endif
 2090 
 2091 static void
 2092 __elfN(note_procstat_proc)(void *arg, struct sbuf *sb, size_t *sizep)
 2093 {
 2094         struct proc *p;
 2095         size_t size;
 2096         int structsize;
 2097 
 2098         p = (struct proc *)arg;
 2099         size = sizeof(structsize) + p->p_numthreads *
 2100             sizeof(elf_kinfo_proc_t);
 2101 
 2102         if (sb != NULL) {
 2103                 KASSERT(*sizep == size, ("invalid size"));
 2104                 structsize = sizeof(elf_kinfo_proc_t);
 2105                 sbuf_bcat(sb, &structsize, sizeof(structsize));
 2106                 sx_slock(&proctree_lock);
 2107                 PROC_LOCK(p);
 2108                 kern_proc_out(p, sb, ELF_KERN_PROC_MASK);
 2109                 sx_sunlock(&proctree_lock);
 2110         }
 2111         *sizep = size;
 2112 }
 2113 
 2114 #ifdef KINFO_FILE_SIZE
 2115 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
 2116 #endif
 2117 
 2118 static void
 2119 note_procstat_files(void *arg, struct sbuf *sb, size_t *sizep)
 2120 {
 2121         struct proc *p;
 2122         size_t size, sect_sz, i;
 2123         ssize_t start_len, sect_len;
 2124         int structsize, filedesc_flags;
 2125 
 2126         if (coredump_pack_fileinfo)
 2127                 filedesc_flags = KERN_FILEDESC_PACK_KINFO;
 2128         else
 2129                 filedesc_flags = 0;
 2130 
 2131         p = (struct proc *)arg;
 2132         structsize = sizeof(struct kinfo_file);
 2133         if (sb == NULL) {
 2134                 size = 0;
 2135                 sb = sbuf_new(NULL, NULL, 128, SBUF_FIXEDLEN);
 2136                 sbuf_set_drain(sb, sbuf_drain_count, &size);
 2137                 sbuf_bcat(sb, &structsize, sizeof(structsize));
 2138                 PROC_LOCK(p);
 2139                 kern_proc_filedesc_out(p, sb, -1, filedesc_flags);
 2140                 sbuf_finish(sb);
 2141                 sbuf_delete(sb);
 2142                 *sizep = size;
 2143         } else {
 2144                 sbuf_start_section(sb, &start_len);
 2145 
 2146                 sbuf_bcat(sb, &structsize, sizeof(structsize));
 2147                 PROC_LOCK(p);
 2148                 kern_proc_filedesc_out(p, sb, *sizep - sizeof(structsize),
 2149                     filedesc_flags);
 2150 
 2151                 sect_len = sbuf_end_section(sb, start_len, 0, 0);
 2152                 if (sect_len < 0)
 2153                         return;
 2154                 sect_sz = sect_len;
 2155 
 2156                 KASSERT(sect_sz <= *sizep,
 2157                     ("kern_proc_filedesc_out did not respect maxlen; "
 2158                      "requested %zu, got %zu", *sizep - sizeof(structsize),
 2159                      sect_sz - sizeof(structsize)));
 2160 
 2161                 for (i = 0; i < *sizep - sect_sz && sb->s_error == 0; i++)
 2162                         sbuf_putc(sb, 0);
 2163         }
 2164 }
 2165 
 2166 #ifdef KINFO_VMENTRY_SIZE
 2167 CTASSERT(sizeof(struct kinfo_vmentry) == KINFO_VMENTRY_SIZE);
 2168 #endif
 2169 
 2170 static void
 2171 note_procstat_vmmap(void *arg, struct sbuf *sb, size_t *sizep)
 2172 {
 2173         struct proc *p;
 2174         size_t size;
 2175         int structsize, vmmap_flags;
 2176 
 2177         if (coredump_pack_vmmapinfo)
 2178                 vmmap_flags = KERN_VMMAP_PACK_KINFO;
 2179         else
 2180                 vmmap_flags = 0;
 2181 
 2182         p = (struct proc *)arg;
 2183         structsize = sizeof(struct kinfo_vmentry);
 2184         if (sb == NULL) {
 2185                 size = 0;
 2186                 sb = sbuf_new(NULL, NULL, 128, SBUF_FIXEDLEN);
 2187                 sbuf_set_drain(sb, sbuf_drain_count, &size);
 2188                 sbuf_bcat(sb, &structsize, sizeof(structsize));
 2189                 PROC_LOCK(p);
 2190                 kern_proc_vmmap_out(p, sb, -1, vmmap_flags);
 2191                 sbuf_finish(sb);
 2192                 sbuf_delete(sb);
 2193                 *sizep = size;
 2194         } else {
 2195                 sbuf_bcat(sb, &structsize, sizeof(structsize));
 2196                 PROC_LOCK(p);
 2197                 kern_proc_vmmap_out(p, sb, *sizep - sizeof(structsize),
 2198                     vmmap_flags);
 2199         }
 2200 }
 2201 
 2202 static void
 2203 note_procstat_groups(void *arg, struct sbuf *sb, size_t *sizep)
 2204 {
 2205         struct proc *p;
 2206         size_t size;
 2207         int structsize;
 2208 
 2209         p = (struct proc *)arg;
 2210         size = sizeof(structsize) + p->p_ucred->cr_ngroups * sizeof(gid_t);
 2211         if (sb != NULL) {
 2212                 KASSERT(*sizep == size, ("invalid size"));
 2213                 structsize = sizeof(gid_t);
 2214                 sbuf_bcat(sb, &structsize, sizeof(structsize));
 2215                 sbuf_bcat(sb, p->p_ucred->cr_groups, p->p_ucred->cr_ngroups *
 2216                     sizeof(gid_t));
 2217         }
 2218         *sizep = size;
 2219 }
 2220 
 2221 static void
 2222 note_procstat_umask(void *arg, struct sbuf *sb, size_t *sizep)
 2223 {
 2224         struct proc *p;
 2225         size_t size;
 2226         int structsize;
 2227 
 2228         p = (struct proc *)arg;
 2229         size = sizeof(structsize) + sizeof(p->p_fd->fd_cmask);
 2230         if (sb != NULL) {
 2231                 KASSERT(*sizep == size, ("invalid size"));
 2232                 structsize = sizeof(p->p_fd->fd_cmask);
 2233                 sbuf_bcat(sb, &structsize, sizeof(structsize));
 2234                 sbuf_bcat(sb, &p->p_fd->fd_cmask, sizeof(p->p_fd->fd_cmask));
 2235         }
 2236         *sizep = size;
 2237 }
 2238 
 2239 static void
 2240 note_procstat_rlimit(void *arg, struct sbuf *sb, size_t *sizep)
 2241 {
 2242         struct proc *p;
 2243         struct rlimit rlim[RLIM_NLIMITS];
 2244         size_t size;
 2245         int structsize, i;
 2246 
 2247         p = (struct proc *)arg;
 2248         size = sizeof(structsize) + sizeof(rlim);
 2249         if (sb != NULL) {
 2250                 KASSERT(*sizep == size, ("invalid size"));
 2251                 structsize = sizeof(rlim);
 2252                 sbuf_bcat(sb, &structsize, sizeof(structsize));
 2253                 PROC_LOCK(p);
 2254                 for (i = 0; i < RLIM_NLIMITS; i++)
 2255                         lim_rlimit_proc(p, i, &rlim[i]);
 2256                 PROC_UNLOCK(p);
 2257                 sbuf_bcat(sb, rlim, sizeof(rlim));
 2258         }
 2259         *sizep = size;
 2260 }
 2261 
 2262 static void
 2263 note_procstat_osrel(void *arg, struct sbuf *sb, size_t *sizep)
 2264 {
 2265         struct proc *p;
 2266         size_t size;
 2267         int structsize;
 2268 
 2269         p = (struct proc *)arg;
 2270         size = sizeof(structsize) + sizeof(p->p_osrel);
 2271         if (sb != NULL) {
 2272                 KASSERT(*sizep == size, ("invalid size"));
 2273                 structsize = sizeof(p->p_osrel);
 2274                 sbuf_bcat(sb, &structsize, sizeof(structsize));
 2275                 sbuf_bcat(sb, &p->p_osrel, sizeof(p->p_osrel));
 2276         }
 2277         *sizep = size;
 2278 }
 2279 
 2280 static void
 2281 __elfN(note_procstat_psstrings)(void *arg, struct sbuf *sb, size_t *sizep)
 2282 {
 2283         struct proc *p;
 2284         elf_ps_strings_t ps_strings;
 2285         size_t size;
 2286         int structsize;
 2287 
 2288         p = (struct proc *)arg;
 2289         size = sizeof(structsize) + sizeof(ps_strings);
 2290         if (sb != NULL) {
 2291                 KASSERT(*sizep == size, ("invalid size"));
 2292                 structsize = sizeof(ps_strings);
 2293 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
 2294                 ps_strings = PTROUT(p->p_sysent->sv_psstrings);
 2295 #else
 2296                 ps_strings = p->p_sysent->sv_psstrings;
 2297 #endif
 2298                 sbuf_bcat(sb, &structsize, sizeof(structsize));
 2299                 sbuf_bcat(sb, &ps_strings, sizeof(ps_strings));
 2300         }
 2301         *sizep = size;
 2302 }
 2303 
 2304 static void
 2305 __elfN(note_procstat_auxv)(void *arg, struct sbuf *sb, size_t *sizep)
 2306 {
 2307         struct proc *p;
 2308         size_t size;
 2309         int structsize;
 2310 
 2311         p = (struct proc *)arg;
 2312         if (sb == NULL) {
 2313                 size = 0;
 2314                 sb = sbuf_new(NULL, NULL, 128, SBUF_FIXEDLEN);
 2315                 sbuf_set_drain(sb, sbuf_drain_count, &size);
 2316                 sbuf_bcat(sb, &structsize, sizeof(structsize));
 2317                 PHOLD(p);
 2318                 proc_getauxv(curthread, p, sb);
 2319                 PRELE(p);
 2320                 sbuf_finish(sb);
 2321                 sbuf_delete(sb);
 2322                 *sizep = size;
 2323         } else {
 2324                 structsize = sizeof(Elf_Auxinfo);
 2325                 sbuf_bcat(sb, &structsize, sizeof(structsize));
 2326                 PHOLD(p);
 2327                 proc_getauxv(curthread, p, sb);
 2328                 PRELE(p);
 2329         }
 2330 }
 2331 
 2332 static boolean_t
 2333 __elfN(parse_notes)(struct image_params *imgp, Elf_Note *checknote,
 2334     const char *note_vendor, const Elf_Phdr *pnote,
 2335     boolean_t (*cb)(const Elf_Note *, void *, boolean_t *), void *cb_arg)
 2336 {
 2337         const Elf_Note *note, *note0, *note_end;
 2338         const char *note_name;
 2339         char *buf;
 2340         int i, error;
 2341         boolean_t res;
 2342 
 2343         /* We need some limit, might as well use PAGE_SIZE. */
 2344         if (pnote == NULL || pnote->p_filesz > PAGE_SIZE)
 2345                 return (FALSE);
 2346         ASSERT_VOP_LOCKED(imgp->vp, "parse_notes");
 2347         if (pnote->p_offset > PAGE_SIZE ||
 2348             pnote->p_filesz > PAGE_SIZE - pnote->p_offset) {
 2349                 VOP_UNLOCK(imgp->vp, 0);
 2350                 buf = malloc(pnote->p_filesz, M_TEMP, M_WAITOK);
 2351                 vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
 2352                 error = vn_rdwr(UIO_READ, imgp->vp, buf, pnote->p_filesz,
 2353                     pnote->p_offset, UIO_SYSSPACE, IO_NODELOCKED,
 2354                     curthread->td_ucred, NOCRED, NULL, curthread);
 2355                 if (error != 0) {
 2356                         uprintf("i/o error PT_NOTE\n");
 2357                         goto retf;
 2358                 }
 2359                 note = note0 = (const Elf_Note *)buf;
 2360                 note_end = (const Elf_Note *)(buf + pnote->p_filesz);
 2361         } else {
 2362                 note = note0 = (const Elf_Note *)(imgp->image_header +
 2363                     pnote->p_offset);
 2364                 note_end = (const Elf_Note *)(imgp->image_header +
 2365                     pnote->p_offset + pnote->p_filesz);
 2366                 buf = NULL;
 2367         }
 2368         for (i = 0; i < 100 && note >= note0 && note < note_end; i++) {
 2369                 if (!aligned(note, Elf32_Addr) || (const char *)note_end -
 2370                     (const char *)note < sizeof(Elf_Note)) {
 2371                         goto retf;
 2372                 }
 2373                 if (note->n_namesz != checknote->n_namesz ||
 2374                     note->n_descsz != checknote->n_descsz ||
 2375                     note->n_type != checknote->n_type)
 2376                         goto nextnote;
 2377                 note_name = (const char *)(note + 1);
 2378                 if (note_name + checknote->n_namesz >=
 2379                     (const char *)note_end || strncmp(note_vendor,
 2380                     note_name, checknote->n_namesz) != 0)
 2381                         goto nextnote;
 2382 
 2383                 if (cb(note, cb_arg, &res))
 2384                         goto ret;
 2385 nextnote:
 2386                 note = (const Elf_Note *)((const char *)(note + 1) +
 2387                     roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE) +
 2388                     roundup2(note->n_descsz, ELF_NOTE_ROUNDSIZE));
 2389         }
 2390 retf:
 2391         res = FALSE;
 2392 ret:
 2393         free(buf, M_TEMP);
 2394         return (res);
 2395 }
 2396 
 2397 struct brandnote_cb_arg {
 2398         Elf_Brandnote *brandnote;
 2399         int32_t *osrel;
 2400 };
 2401 
 2402 static boolean_t
 2403 brandnote_cb(const Elf_Note *note, void *arg0, boolean_t *res)
 2404 {
 2405         struct brandnote_cb_arg *arg;
 2406 
 2407         arg = arg0;
 2408 
 2409         /*
 2410          * Fetch the osreldate for binary from the ELF OSABI-note if
 2411          * necessary.
 2412          */
 2413         *res = (arg->brandnote->flags & BN_TRANSLATE_OSREL) != 0 &&
 2414             arg->brandnote->trans_osrel != NULL ?
 2415             arg->brandnote->trans_osrel(note, arg->osrel) : TRUE;
 2416 
 2417         return (TRUE);
 2418 }
 2419 
 2420 /*
 2421  * Try to find the appropriate ABI-note section for checknote,
 2422  * fetch the osreldate for binary from the ELF OSABI-note. Only the
 2423  * first page of the image is searched, the same as for headers.
 2424  */
 2425 static boolean_t
 2426 __elfN(check_note)(struct image_params *imgp, Elf_Brandnote *brandnote,
 2427     int32_t *osrel)
 2428 {
 2429         const Elf_Phdr *phdr;
 2430         const Elf_Ehdr *hdr;
 2431         struct brandnote_cb_arg b_arg;
 2432         int i;
 2433 
 2434         hdr = (const Elf_Ehdr *)imgp->image_header;
 2435         phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
 2436         b_arg.brandnote = brandnote;
 2437         b_arg.osrel = osrel;
 2438 
 2439         for (i = 0; i < hdr->e_phnum; i++) {
 2440                 if (phdr[i].p_type == PT_NOTE && __elfN(parse_notes)(imgp,
 2441                     &brandnote->hdr, brandnote->vendor, &phdr[i], brandnote_cb,
 2442                     &b_arg)) {
 2443                         return (TRUE);
 2444                 }
 2445         }
 2446         return (FALSE);
 2447 
 2448 }
 2449 
 2450 /*
 2451  * Tell kern_execve.c about it, with a little help from the linker.
 2452  */
 2453 static struct execsw __elfN(execsw) = {
 2454         __CONCAT(exec_, __elfN(imgact)),
 2455         __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE))
 2456 };
 2457 EXEC_SET(__CONCAT(elf, __ELF_WORD_SIZE), __elfN(execsw));
 2458 
 2459 static vm_prot_t
 2460 __elfN(trans_prot)(Elf_Word flags)
 2461 {
 2462         vm_prot_t prot;
 2463 
 2464         prot = 0;
 2465         if (flags & PF_X)
 2466                 prot |= VM_PROT_EXECUTE;
 2467         if (flags & PF_W)
 2468                 prot |= VM_PROT_WRITE;
 2469         if (flags & PF_R)
 2470                 prot |= VM_PROT_READ;
 2471 #if __ELF_WORD_SIZE == 32
 2472 #if defined(__amd64__)
 2473         if (i386_read_exec && (flags & PF_R))
 2474                 prot |= VM_PROT_EXECUTE;
 2475 #endif
 2476 #endif
 2477         return (prot);
 2478 }
 2479 
 2480 static Elf_Word
 2481 __elfN(untrans_prot)(vm_prot_t prot)
 2482 {
 2483         Elf_Word flags;
 2484 
 2485         flags = 0;
 2486         if (prot & VM_PROT_EXECUTE)
 2487                 flags |= PF_X;
 2488         if (prot & VM_PROT_READ)
 2489                 flags |= PF_R;
 2490         if (prot & VM_PROT_WRITE)
 2491                 flags |= PF_W;
 2492         return (flags);
 2493 }

Cache object: 8766f0697822b5fb18318f6ea1f952ca


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.