1 /*
   2  * Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include <jni.h>
  26 #include <unistd.h>
  27 #include <fcntl.h>
  28 #include <string.h>
  29 #include <stdlib.h>
  30 #include <stddef.h>
  31 #include <elf.h>
  32 #include <link.h>
  33 #include "libproc_impl.h"
  34 #include "salibelf.h"
  35 #include "cds.h"
  36 
  37 // This file has the libproc implementation to read core files.
  38 // For live processes, refer to ps_proc.c. Portions of this is adapted
  39 // /modelled after Solaris libproc.so (in particular Pcore.c)
  40 
  41 //----------------------------------------------------------------------
  42 // ps_prochandle cleanup helper functions
  43 
  44 // close all file descriptors
  45 static void close_files(struct ps_prochandle* ph) {
  46   lib_info* lib = NULL;
  47 
  48   // close core file descriptor
  49   if (ph->core->core_fd >= 0)
  50     close(ph->core->core_fd);
  51 
  52   // close exec file descriptor
  53   if (ph->core->exec_fd >= 0)
  54     close(ph->core->exec_fd);
  55 
  56   // close interp file descriptor
  57   if (ph->core->interp_fd >= 0)
  58     close(ph->core->interp_fd);
  59 
  60   // close class share archive file
  61   if (ph->core->classes_jsa_fd >= 0)
  62     close(ph->core->classes_jsa_fd);
  63 
  64   // close all library file descriptors
  65   lib = ph->libs;
  66   while (lib) {
  67     int fd = lib->fd;
  68     if (fd >= 0 && fd != ph->core->exec_fd) {
  69       close(fd);
  70     }
  71     lib = lib->next;
  72   }
  73 }
  74 
  75 // clean all map_info stuff
  76 static void destroy_map_info(struct ps_prochandle* ph) {
  77   map_info* map = ph->core->maps;
  78   while (map) {
  79     map_info* next = map->next;
  80     free(map);
  81     map = next;
  82   }
  83 
  84   if (ph->core->map_array) {
  85     free(ph->core->map_array);
  86   }
  87 
  88   // Part of the class sharing workaround
  89   map = ph->core->class_share_maps;
  90   while (map) {
  91     map_info* next = map->next;
  92     free(map);
  93     map = next;
  94   }
  95 }
  96 
  97 // ps_prochandle operations
  98 static void core_release(struct ps_prochandle* ph) {
  99   if (ph->core) {
 100     close_files(ph);
 101     destroy_map_info(ph);
 102     free(ph->core);
 103   }
 104 }
 105 
 106 static map_info* allocate_init_map(int fd, off_t offset, uintptr_t vaddr, size_t memsz, uint32_t flags) {
 107   map_info* map;
 108   if ( (map = (map_info*) calloc(1, sizeof(map_info))) == NULL) {
 109     print_debug("can't allocate memory for map_info\n");
 110     return NULL;
 111   }
 112 
 113   // initialize map
 114   map->fd     = fd;
 115   map->offset = offset;
 116   map->vaddr  = vaddr;
 117   map->memsz  = memsz;
 118   map->flags  = flags;
 119   return map;
 120 }
 121 
 122 // add map info with given fd, offset, vaddr and memsz
 123 static map_info* add_map_info(struct ps_prochandle* ph, int fd, off_t offset,
 124                              uintptr_t vaddr, size_t memsz, uint32_t flags) {
 125   map_info* map;
 126   if ((map = allocate_init_map(fd, offset, vaddr, memsz, flags)) == NULL) {
 127     return NULL;
 128   }
 129 
 130   // add this to map list
 131   map->next  = ph->core->maps;
 132   ph->core->maps   = map;
 133   ph->core->num_maps++;
 134 
 135   return map;
 136 }
 137 
 138 // Part of the class sharing workaround
 139 static map_info* add_class_share_map_info(struct ps_prochandle* ph, off_t offset,
 140                              uintptr_t vaddr, size_t memsz) {
 141   map_info* map;
 142   if ((map = allocate_init_map(ph->core->classes_jsa_fd,
 143                                offset, vaddr, memsz, PF_R)) == NULL) {
 144     return NULL;
 145   }
 146 
 147   map->next = ph->core->class_share_maps;
 148   ph->core->class_share_maps = map;
 149   return map;
 150 }
 151 
 152 // Return the map_info for the given virtual address.  We keep a sorted
 153 // array of pointers in ph->map_array, so we can binary search.
 154 static map_info* core_lookup(struct ps_prochandle *ph, uintptr_t addr) {
 155   int mid, lo = 0, hi = ph->core->num_maps - 1;
 156   map_info *mp;
 157 
 158   while (hi - lo > 1) {
 159     mid = (lo + hi) / 2;
 160     if (addr >= ph->core->map_array[mid]->vaddr) {
 161       lo = mid;
 162     } else {
 163       hi = mid;
 164     }
 165   }
 166 
 167   if (addr < ph->core->map_array[hi]->vaddr) {
 168     mp = ph->core->map_array[lo];
 169   } else {
 170     mp = ph->core->map_array[hi];
 171   }
 172 
 173   if (addr >= mp->vaddr && addr < mp->vaddr + mp->memsz) {
 174     return (mp);
 175   }
 176 
 177 
 178   // Part of the class sharing workaround
 179   // Unfortunately, we have no way of detecting -Xshare state.
 180   // Check out the share maps atlast, if we don't find anywhere.
 181   // This is done this way so to avoid reading share pages
 182   // ahead of other normal maps. For eg. with -Xshare:off we don't
 183   // want to prefer class sharing data to data from core.
 184   mp = ph->core->class_share_maps;
 185   if (mp) {
 186     print_debug("can't locate map_info at 0x%lx, trying class share maps\n", addr);
 187   }
 188   while (mp) {
 189     if (addr >= mp->vaddr && addr < mp->vaddr + mp->memsz) {
 190       print_debug("located map_info at 0x%lx from class share maps\n", addr);
 191       return (mp);
 192     }
 193     mp = mp->next;
 194   }
 195 
 196   print_debug("can't locate map_info at 0x%lx\n", addr);
 197   return (NULL);
 198 }
 199 
 200 //---------------------------------------------------------------
 201 // Part of the class sharing workaround:
 202 //
 203 // With class sharing, pages are mapped from classes.jsa file.
 204 // The read-only class sharing pages are mapped as MAP_SHARED,
 205 // PROT_READ pages. These pages are not dumped into core dump.
 206 // With this workaround, these pages are read from classes.jsa.
 207 
 208 static bool read_jboolean(struct ps_prochandle* ph, uintptr_t addr, jboolean* pvalue) {
 209   jboolean i;
 210   if (ps_pdread(ph, (psaddr_t) addr, &i, sizeof(i)) == PS_OK) {
 211     *pvalue = i;
 212     return true;
 213   } else {
 214     return false;
 215   }
 216 }
 217 
 218 static bool read_pointer(struct ps_prochandle* ph, uintptr_t addr, uintptr_t* pvalue) {
 219   uintptr_t uip;
 220   if (ps_pdread(ph, (psaddr_t) addr, (char *)&uip, sizeof(uip)) == PS_OK) {
 221     *pvalue = uip;
 222     return true;
 223   } else {
 224     return false;
 225   }
 226 }
 227 
 228 // used to read strings from debuggee
 229 static bool read_string(struct ps_prochandle* ph, uintptr_t addr, char* buf, size_t size) {
 230   size_t i = 0;
 231   char  c = ' ';
 232 
 233   while (c != '\0') {
 234     if (ps_pdread(ph, (psaddr_t) addr, &c, sizeof(char)) != PS_OK) {
 235       return false;
 236     }
 237     if (i < size - 1) {
 238       buf[i] = c;
 239     } else {
 240       // smaller buffer
 241       return false;
 242     }
 243     i++; addr++;
 244   }
 245 
 246   buf[i] = '\0';
 247   return true;
 248 }
 249 
 250 #define USE_SHARED_SPACES_SYM "UseSharedSpaces"
 251 // mangled name of Arguments::SharedArchivePath
 252 #define SHARED_ARCHIVE_PATH_SYM "_ZN9Arguments17SharedArchivePathE"
 253 #define LIBJVM_NAME "/libjvm.so"
 254 
 255 static bool init_classsharing_workaround(struct ps_prochandle* ph) {
 256   lib_info* lib = ph->libs;
 257   while (lib != NULL) {
 258     // we are iterating over shared objects from the core dump. look for
 259     // libjvm.so.
 260     const char *jvm_name = 0;
 261     if ((jvm_name = strstr(lib->name, LIBJVM_NAME)) != 0) {
 262       char classes_jsa[PATH_MAX];
 263       CDSFileMapHeaderBase header;
 264       int fd = -1;
 265       int m = 0;
 266       size_t n = 0;
 267       uintptr_t base = 0, useSharedSpacesAddr = 0;
 268       uintptr_t sharedArchivePathAddrAddr = 0, sharedArchivePathAddr = 0;
 269       jboolean useSharedSpaces = 0;
 270       map_info* mi = 0;
 271 
 272       memset(classes_jsa, 0, sizeof(classes_jsa));
 273       jvm_name = lib->name;
 274       useSharedSpacesAddr = lookup_symbol(ph, jvm_name, USE_SHARED_SPACES_SYM);
 275       if (useSharedSpacesAddr == 0) {
 276         print_debug("can't lookup 'UseSharedSpaces' flag\n");
 277         return false;
 278       }
 279 
 280       // Hotspot vm types are not exported to build this library. So
 281       // using equivalent type jboolean to read the value of
 282       // UseSharedSpaces which is same as hotspot type "bool".
 283       if (read_jboolean(ph, useSharedSpacesAddr, &useSharedSpaces) != true) {
 284         print_debug("can't read the value of 'UseSharedSpaces' flag\n");
 285         return false;
 286       }
 287 
 288       if ((int)useSharedSpaces == 0) {
 289         print_debug("UseSharedSpaces is false, assuming -Xshare:off!\n");
 290         return true;
 291       }
 292 
 293       sharedArchivePathAddrAddr = lookup_symbol(ph, jvm_name, SHARED_ARCHIVE_PATH_SYM);
 294       if (sharedArchivePathAddrAddr == 0) {
 295         print_debug("can't lookup shared archive path symbol\n");
 296         return false;
 297       }
 298 
 299       if (read_pointer(ph, sharedArchivePathAddrAddr, &sharedArchivePathAddr) != true) {
 300         print_debug("can't read shared archive path pointer\n");
 301         return false;
 302       }
 303 
 304       if (read_string(ph, sharedArchivePathAddr, classes_jsa, sizeof(classes_jsa)) != true) {
 305         print_debug("can't read shared archive path value\n");
 306         return false;
 307       }
 308 
 309       print_debug("looking for %s\n", classes_jsa);
 310       // open the class sharing archive file
 311       fd = pathmap_open(classes_jsa);
 312       if (fd < 0) {
 313         print_debug("can't open %s!\n", classes_jsa);
 314         ph->core->classes_jsa_fd = -1;
 315         return false;
 316       } else {
 317         print_debug("opened %s\n", classes_jsa);
 318       }
 319 
 320       // read CDSFileMapHeaderBase from the file
 321       memset(&header, 0, sizeof(CDSFileMapHeaderBase));
 322       if ((n = read(fd, &header, sizeof(CDSFileMapHeaderBase)))
 323            != sizeof(CDSFileMapHeaderBase)) {
 324         print_debug("can't read shared archive file map header from %s\n", classes_jsa);
 325         close(fd);
 326         return false;
 327       }
 328 
 329       // check file magic
 330       if (header._magic != CDS_ARCHIVE_MAGIC) {
 331         print_debug("%s has bad shared archive file magic number 0x%x, expecting 0x%x\n",
 332                     classes_jsa, header._magic, CDS_ARCHIVE_MAGIC);
 333         close(fd);
 334         return false;
 335       }
 336 
 337       // check version
 338       if (header._version != CURRENT_CDS_ARCHIVE_VERSION) {
 339         print_debug("%s has wrong shared archive file version %d, expecting %d\n",
 340                      classes_jsa, header._version, CURRENT_CDS_ARCHIVE_VERSION);
 341         close(fd);
 342         return false;
 343       }
 344 
 345       ph->core->classes_jsa_fd = fd;
 346       // add read-only maps from classes.jsa to the list of maps
 347       for (m = 0; m < NUM_CDS_REGIONS; m++) {
 348         if (header._space[m]._read_only) {
 349           base = (uintptr_t) header._space[m]._addr._base;
 350           // no need to worry about the fractional pages at-the-end.
 351           // possible fractional pages are handled by core_read_data.
 352           add_class_share_map_info(ph, (off_t) header._space[m]._file_offset,
 353                                    base, (size_t) header._space[m]._used);
 354           print_debug("added a share archive map at 0x%lx\n", base);
 355         }
 356       }
 357       return true;
 358    }
 359    lib = lib->next;
 360   }
 361   return true;
 362 }
 363 
 364 
 365 //---------------------------------------------------------------------------
 366 // functions to handle map_info
 367 
 368 // Order mappings based on virtual address.  We use this function as the
 369 // callback for sorting the array of map_info pointers.
 370 static int core_cmp_mapping(const void *lhsp, const void *rhsp)
 371 {
 372   const map_info *lhs = *((const map_info **)lhsp);
 373   const map_info *rhs = *((const map_info **)rhsp);
 374 
 375   if (lhs->vaddr == rhs->vaddr) {
 376     return (0);
 377   }
 378 
 379   return (lhs->vaddr < rhs->vaddr ? -1 : 1);
 380 }
 381 
 382 // we sort map_info by starting virtual address so that we can do
 383 // binary search to read from an address.
 384 static bool sort_map_array(struct ps_prochandle* ph) {
 385   size_t num_maps = ph->core->num_maps;
 386   map_info* map = ph->core->maps;
 387   int i = 0;
 388 
 389   // allocate map_array
 390   map_info** array;
 391   if ( (array = (map_info**) malloc(sizeof(map_info*) * num_maps)) == NULL) {
 392     print_debug("can't allocate memory for map array\n");
 393     return false;
 394   }
 395 
 396   // add maps to array
 397   while (map) {
 398     array[i] = map;
 399     i++;
 400     map = map->next;
 401   }
 402 
 403   // sort is called twice. If this is second time, clear map array
 404   if (ph->core->map_array) {
 405     free(ph->core->map_array);
 406   }
 407 
 408   ph->core->map_array = array;
 409   // sort the map_info array by base virtual address.
 410   qsort(ph->core->map_array, ph->core->num_maps, sizeof (map_info*),
 411         core_cmp_mapping);
 412 
 413   // print map
 414   if (is_debug()) {
 415     int j = 0;
 416     print_debug("---- sorted virtual address map ----\n");
 417     for (j = 0; j < ph->core->num_maps; j++) {
 418       print_debug("base = 0x%lx\tsize = %zu\n", ph->core->map_array[j]->vaddr,
 419                   ph->core->map_array[j]->memsz);
 420     }
 421   }
 422 
 423   return true;
 424 }
 425 
 426 #ifndef MIN
 427 #define MIN(x, y) (((x) < (y))? (x): (y))
 428 #endif
 429 
 430 static bool core_read_data(struct ps_prochandle* ph, uintptr_t addr, char *buf, size_t size) {
 431    ssize_t resid = size;
 432    int page_size=sysconf(_SC_PAGE_SIZE);
 433    while (resid != 0) {
 434       map_info *mp = core_lookup(ph, addr);
 435       uintptr_t mapoff;
 436       ssize_t len, rem;
 437       off_t off;
 438       int fd;
 439 
 440       if (mp == NULL) {
 441          break;  /* No mapping for this address */
 442       }
 443 
 444       fd = mp->fd;
 445       mapoff = addr - mp->vaddr;
 446       len = MIN(resid, mp->memsz - mapoff);
 447       off = mp->offset + mapoff;
 448 
 449       if ((len = pread(fd, buf, len, off)) <= 0) {
 450          break;
 451       }
 452 
 453       resid -= len;
 454       addr += len;
 455       buf = (char *)buf + len;
 456 
 457       // mappings always start at page boundary. But, may end in fractional
 458       // page. fill zeros for possible fractional page at the end of a mapping.
 459       rem = mp->memsz % page_size;
 460       if (rem > 0) {
 461          rem = page_size - rem;
 462          len = MIN(resid, rem);
 463          resid -= len;
 464          addr += len;
 465          // we are not assuming 'buf' to be zero initialized.
 466          memset(buf, 0, len);
 467          buf += len;
 468       }
 469    }
 470 
 471    if (resid) {
 472       print_debug("core read failed for %d byte(s) @ 0x%lx (%d more bytes)\n",
 473               size, addr, resid);
 474       return false;
 475    } else {
 476       return true;
 477    }
 478 }
 479 
 480 // null implementation for write
 481 static bool core_write_data(struct ps_prochandle* ph,
 482                              uintptr_t addr, const char *buf , size_t size) {
 483    return false;
 484 }
 485 
 486 static bool core_get_lwp_regs(struct ps_prochandle* ph, lwpid_t lwp_id,
 487                           struct user_regs_struct* regs) {
 488    // for core we have cached the lwp regs from NOTE section
 489    thread_info* thr = ph->threads;
 490    while (thr) {
 491      if (thr->lwp_id == lwp_id) {
 492        memcpy(regs, &thr->regs, sizeof(struct user_regs_struct));
 493        return true;
 494      }
 495      thr = thr->next;
 496    }
 497    return false;
 498 }
 499 
 500 static ps_prochandle_ops core_ops = {
 501    .release=  core_release,
 502    .p_pread=  core_read_data,
 503    .p_pwrite= core_write_data,
 504    .get_lwp_regs= core_get_lwp_regs
 505 };
 506 
 507 // read regs and create thread from NT_PRSTATUS entries from core file
 508 static bool core_handle_prstatus(struct ps_prochandle* ph, const char* buf, size_t nbytes) {
 509    // we have to read prstatus_t from buf
 510    // assert(nbytes == sizeof(prstaus_t), "size mismatch on prstatus_t");
 511    prstatus_t* prstat = (prstatus_t*) buf;
 512    thread_info* newthr;
 513    print_debug("got integer regset for lwp %d\n", prstat->pr_pid);
 514    // we set pthread_t to -1 for core dump
 515    if((newthr = add_thread_info(ph, (pthread_t) -1,  prstat->pr_pid)) == NULL)
 516       return false;
 517 
 518    // copy regs
 519    memcpy(&newthr->regs, prstat->pr_reg, sizeof(struct user_regs_struct));
 520 
 521    if (is_debug()) {
 522       print_debug("integer regset\n");
 523 #ifdef i386
 524       // print the regset
 525       print_debug("\teax = 0x%x\n", newthr->regs.eax);
 526       print_debug("\tebx = 0x%x\n", newthr->regs.ebx);
 527       print_debug("\tecx = 0x%x\n", newthr->regs.ecx);
 528       print_debug("\tedx = 0x%x\n", newthr->regs.edx);
 529       print_debug("\tesp = 0x%x\n", newthr->regs.esp);
 530       print_debug("\tebp = 0x%x\n", newthr->regs.ebp);
 531       print_debug("\tesi = 0x%x\n", newthr->regs.esi);
 532       print_debug("\tedi = 0x%x\n", newthr->regs.edi);
 533       print_debug("\teip = 0x%x\n", newthr->regs.eip);
 534 #endif
 535 
 536 #if defined(amd64) || defined(x86_64)
 537       // print the regset
 538       print_debug("\tr15 = 0x%lx\n", newthr->regs.r15);
 539       print_debug("\tr14 = 0x%lx\n", newthr->regs.r14);
 540       print_debug("\tr13 = 0x%lx\n", newthr->regs.r13);
 541       print_debug("\tr12 = 0x%lx\n", newthr->regs.r12);
 542       print_debug("\trbp = 0x%lx\n", newthr->regs.rbp);
 543       print_debug("\trbx = 0x%lx\n", newthr->regs.rbx);
 544       print_debug("\tr11 = 0x%lx\n", newthr->regs.r11);
 545       print_debug("\tr10 = 0x%lx\n", newthr->regs.r10);
 546       print_debug("\tr9 = 0x%lx\n", newthr->regs.r9);
 547       print_debug("\tr8 = 0x%lx\n", newthr->regs.r8);
 548       print_debug("\trax = 0x%lx\n", newthr->regs.rax);
 549       print_debug("\trcx = 0x%lx\n", newthr->regs.rcx);
 550       print_debug("\trdx = 0x%lx\n", newthr->regs.rdx);
 551       print_debug("\trsi = 0x%lx\n", newthr->regs.rsi);
 552       print_debug("\trdi = 0x%lx\n", newthr->regs.rdi);
 553       print_debug("\torig_rax = 0x%lx\n", newthr->regs.orig_rax);
 554       print_debug("\trip = 0x%lx\n", newthr->regs.rip);
 555       print_debug("\tcs = 0x%lx\n", newthr->regs.cs);
 556       print_debug("\teflags = 0x%lx\n", newthr->regs.eflags);
 557       print_debug("\trsp = 0x%lx\n", newthr->regs.rsp);
 558       print_debug("\tss = 0x%lx\n", newthr->regs.ss);
 559       print_debug("\tfs_base = 0x%lx\n", newthr->regs.fs_base);
 560       print_debug("\tgs_base = 0x%lx\n", newthr->regs.gs_base);
 561       print_debug("\tds = 0x%lx\n", newthr->regs.ds);
 562       print_debug("\tes = 0x%lx\n", newthr->regs.es);
 563       print_debug("\tfs = 0x%lx\n", newthr->regs.fs);
 564       print_debug("\tgs = 0x%lx\n", newthr->regs.gs);
 565 #endif
 566    }
 567 
 568    return true;
 569 }
 570 
 571 #define ROUNDUP(x, y)  ((((x)+((y)-1))/(y))*(y))
 572 
 573 // read NT_PRSTATUS entries from core NOTE segment
 574 static bool core_handle_note(struct ps_prochandle* ph, ELF_PHDR* note_phdr) {
 575    char* buf = NULL;
 576    char* p = NULL;
 577    size_t size = note_phdr->p_filesz;
 578 
 579    // we are interested in just prstatus entries. we will ignore the rest.
 580    // Advance the seek pointer to the start of the PT_NOTE data
 581    if (lseek(ph->core->core_fd, note_phdr->p_offset, SEEK_SET) == (off_t)-1) {
 582       print_debug("failed to lseek to PT_NOTE data\n");
 583       return false;
 584    }
 585 
 586    // Now process the PT_NOTE structures.  Each one is preceded by
 587    // an Elf{32/64}_Nhdr structure describing its type and size.
 588    if ( (buf = (char*) malloc(size)) == NULL) {
 589       print_debug("can't allocate memory for reading core notes\n");
 590       goto err;
 591    }
 592 
 593    // read notes into buffer
 594    if (read(ph->core->core_fd, buf, size) != size) {
 595       print_debug("failed to read notes, core file must have been truncated\n");
 596       goto err;
 597    }
 598 
 599    p = buf;
 600    while (p < buf + size) {
 601       ELF_NHDR* notep = (ELF_NHDR*) p;
 602       char* descdata  = p + sizeof(ELF_NHDR) + ROUNDUP(notep->n_namesz, 4);
 603       print_debug("Note header with n_type = %d and n_descsz = %u\n",
 604                                    notep->n_type, notep->n_descsz);
 605 
 606       if (notep->n_type == NT_PRSTATUS) {
 607         if (core_handle_prstatus(ph, descdata, notep->n_descsz) != true) {
 608           return false;
 609         }
 610       } else if (notep->n_type == NT_AUXV) {
 611         // Get first segment from entry point
 612         ELF_AUXV *auxv = (ELF_AUXV *)descdata;
 613         while (auxv->a_type != AT_NULL) {
 614           if (auxv->a_type == AT_ENTRY) {
 615             // Set entry point address to address of dynamic section.
 616             // We will adjust it in read_exec_segments().
 617             ph->core->dynamic_addr = auxv->a_un.a_val;
 618             break;
 619           }
 620           auxv++;
 621         }
 622       }
 623       p = descdata + ROUNDUP(notep->n_descsz, 4);
 624    }
 625 
 626    free(buf);
 627    return true;
 628 
 629 err:
 630    if (buf) free(buf);
 631    return false;
 632 }
 633 
 634 // read all segments from core file
 635 static bool read_core_segments(struct ps_prochandle* ph, ELF_EHDR* core_ehdr) {
 636    int i = 0;
 637    ELF_PHDR* phbuf = NULL;
 638    ELF_PHDR* core_php = NULL;
 639 
 640    if ((phbuf =  read_program_header_table(ph->core->core_fd, core_ehdr)) == NULL)
 641       return false;
 642 
 643    /*
 644     * Now iterate through the program headers in the core file.
 645     * We're interested in two types of Phdrs: PT_NOTE (which
 646     * contains a set of saved /proc structures), and PT_LOAD (which
 647     * represents a memory mapping from the process's address space).
 648     *
 649     * Difference b/w Solaris PT_NOTE and Linux/BSD PT_NOTE:
 650     *
 651     *     In Solaris there are two PT_NOTE segments the first PT_NOTE (if present)
 652     *     contains /proc structs in the pre-2.6 unstructured /proc format. the last
 653     *     PT_NOTE has data in new /proc format.
 654     *
 655     *     In Solaris, there is only one pstatus (process status). pstatus contains
 656     *     integer register set among other stuff. For each LWP, we have one lwpstatus
 657     *     entry that has integer regset for that LWP.
 658     *
 659     *     Linux threads are actually 'clone'd processes. To support core analysis
 660     *     of "multithreaded" process, Linux creates more than one pstatus (called
 661     *     "prstatus") entry in PT_NOTE. Each prstatus entry has integer regset for one
 662     *     "thread". Please refer to Linux kernel src file 'fs/binfmt_elf.c', in particular
 663     *     function "elf_core_dump".
 664     */
 665 
 666     for (core_php = phbuf, i = 0; i < core_ehdr->e_phnum; i++) {
 667       switch (core_php->p_type) {
 668          case PT_NOTE:
 669             if (core_handle_note(ph, core_php) != true) {
 670               goto err;
 671             }
 672             break;
 673 
 674          case PT_LOAD: {
 675             if (core_php->p_filesz != 0) {
 676                if (add_map_info(ph, ph->core->core_fd, core_php->p_offset,
 677                   core_php->p_vaddr, core_php->p_filesz, core_php->p_flags) == NULL) goto err;
 678             }
 679             break;
 680          }
 681       }
 682 
 683       core_php++;
 684    }
 685 
 686    free(phbuf);
 687    return true;
 688 err:
 689    free(phbuf);
 690    return false;
 691 }
 692 
 693 // read segments of a shared object
 694 static bool read_lib_segments(struct ps_prochandle* ph, int lib_fd, ELF_EHDR* lib_ehdr, uintptr_t lib_base) {
 695   int i = 0;
 696   ELF_PHDR* phbuf;
 697   ELF_PHDR* lib_php = NULL;
 698 
 699   int page_size = sysconf(_SC_PAGE_SIZE);
 700 
 701   if ((phbuf = read_program_header_table(lib_fd, lib_ehdr)) == NULL) {
 702     return false;
 703   }
 704 
 705   // we want to process only PT_LOAD segments that are not writable.
 706   // i.e., text segments. The read/write/exec (data) segments would
 707   // have been already added from core file segments.
 708   for (lib_php = phbuf, i = 0; i < lib_ehdr->e_phnum; i++) {
 709     if ((lib_php->p_type == PT_LOAD) && !(lib_php->p_flags & PF_W) && (lib_php->p_filesz != 0)) {
 710 
 711       uintptr_t target_vaddr = lib_php->p_vaddr + lib_base;
 712       map_info *existing_map = core_lookup(ph, target_vaddr);
 713 
 714       if (existing_map == NULL){
 715         if (add_map_info(ph, lib_fd, lib_php->p_offset,
 716                           target_vaddr, lib_php->p_memsz, lib_php->p_flags) == NULL) {
 717           goto err;
 718         }
 719       } else if (lib_php->p_flags != existing_map->flags) {
 720         // Access flags for this memory region are different between the library
 721         // and coredump. It might be caused by mprotect() call at runtime.
 722         // We should respect the coredump.
 723         continue;
 724       } else {
 725         // Read only segments in ELF should not be any different from PT_LOAD segments
 726         // in the coredump.
 727         // Also the first page of the ELF header might be included
 728         // in the coredump (See JDK-7133122).
 729         // Thus we need to replace the PT_LOAD segment with the library version.
 730         //
 731         // Coredump stores value of p_memsz elf field
 732         // rounded up to page boundary.
 733 
 734         if ((existing_map->memsz != page_size) &&
 735             (existing_map->fd != lib_fd) &&
 736             (ROUNDUP(existing_map->memsz, page_size) != ROUNDUP(lib_php->p_memsz, page_size))) {
 737 
 738           print_debug("address conflict @ 0x%lx (existing map size = %ld, size = %ld, flags = %d)\n",
 739                         target_vaddr, existing_map->memsz, lib_php->p_memsz, lib_php->p_flags);
 740           goto err;
 741         }
 742 
 743         /* replace PT_LOAD segment with library segment */
 744         print_debug("overwrote with new address mapping (memsz %ld -> %ld)\n",
 745                      existing_map->memsz, ROUNDUP(lib_php->p_memsz, page_size));
 746 
 747         existing_map->fd = lib_fd;
 748         existing_map->offset = lib_php->p_offset;
 749         existing_map->memsz = ROUNDUP(lib_php->p_memsz, page_size);
 750       }
 751     }
 752 
 753     lib_php++;
 754   }
 755 
 756   free(phbuf);
 757   return true;
 758 err:
 759   free(phbuf);
 760   return false;
 761 }
 762 
 763 // process segments from interpreter (ld.so or ld-linux.so)
 764 static bool read_interp_segments(struct ps_prochandle* ph) {
 765   ELF_EHDR interp_ehdr;
 766 
 767   if (read_elf_header(ph->core->interp_fd, &interp_ehdr) != true) {
 768     print_debug("interpreter is not a valid ELF file\n");
 769     return false;
 770   }
 771 
 772   if (read_lib_segments(ph, ph->core->interp_fd, &interp_ehdr, ph->core->ld_base_addr) != true) {
 773     print_debug("can't read segments of interpreter\n");
 774     return false;
 775   }
 776 
 777   return true;
 778 }
 779 
 780 // process segments of a a.out
 781 static bool read_exec_segments(struct ps_prochandle* ph, ELF_EHDR* exec_ehdr) {
 782   int i = 0;
 783   ELF_PHDR* phbuf = NULL;
 784   ELF_PHDR* exec_php = NULL;
 785 
 786   if ((phbuf = read_program_header_table(ph->core->exec_fd, exec_ehdr)) == NULL) {
 787     return false;
 788   }
 789 
 790   for (exec_php = phbuf, i = 0; i < exec_ehdr->e_phnum; i++) {
 791     switch (exec_php->p_type) {
 792 
 793       // add mappings for PT_LOAD segments
 794     case PT_LOAD: {
 795       // add only non-writable segments of non-zero filesz
 796       if (!(exec_php->p_flags & PF_W) && exec_php->p_filesz != 0) {
 797         if (add_map_info(ph, ph->core->exec_fd, exec_php->p_offset, exec_php->p_vaddr, exec_php->p_filesz, exec_php->p_flags) == NULL) goto err;
 798       }
 799       break;
 800     }
 801 
 802     // read the interpreter and it's segments
 803     case PT_INTERP: {
 804       char interp_name[BUF_SIZE + 1];
 805 
 806       // BUF_SIZE is PATH_MAX + NAME_MAX + 1.
 807       if (exec_php->p_filesz > BUF_SIZE) {
 808         goto err;
 809       }
 810       if (pread(ph->core->exec_fd, interp_name,
 811                 exec_php->p_filesz, exec_php->p_offset) != exec_php->p_filesz) {
 812         print_debug("Unable to read in the ELF interpreter\n");
 813         goto err;
 814       }
 815       interp_name[exec_php->p_filesz] = '\0';
 816       print_debug("ELF interpreter %s\n", interp_name);
 817       // read interpreter segments as well
 818       if ((ph->core->interp_fd = pathmap_open(interp_name)) < 0) {
 819         print_debug("can't open runtime loader\n");
 820         goto err;
 821       }
 822       break;
 823     }
 824 
 825     // from PT_DYNAMIC we want to read address of first link_map addr
 826     case PT_DYNAMIC: {
 827       if (exec_ehdr->e_type == ET_EXEC) {
 828         ph->core->dynamic_addr = exec_php->p_vaddr;
 829       } else { // ET_DYN
 830         // dynamic_addr has entry point of executable.
 831         // Thus we should substract it.
 832         ph->core->dynamic_addr += exec_php->p_vaddr - exec_ehdr->e_entry;
 833       }
 834       print_debug("address of _DYNAMIC is 0x%lx\n", ph->core->dynamic_addr);
 835       break;
 836     }
 837 
 838     } // switch
 839     exec_php++;
 840   } // for
 841 
 842   free(phbuf);
 843   return true;
 844  err:
 845   free(phbuf);
 846   return false;
 847 }
 848 
 849 
 850 #define FIRST_LINK_MAP_OFFSET offsetof(struct r_debug,  r_map)
 851 #define LD_BASE_OFFSET        offsetof(struct r_debug,  r_ldbase)
 852 #define LINK_MAP_ADDR_OFFSET  offsetof(struct link_map, l_addr)
 853 #define LINK_MAP_NAME_OFFSET  offsetof(struct link_map, l_name)
 854 #define LINK_MAP_LD_OFFSET    offsetof(struct link_map, l_ld)
 855 #define LINK_MAP_NEXT_OFFSET  offsetof(struct link_map, l_next)
 856 
 857 #define INVALID_LOAD_ADDRESS -1L
 858 #define ZERO_LOAD_ADDRESS 0x0L
 859 
 860 // Calculate the load address of shared library
 861 // on prelink-enabled environment.
 862 //
 863 // In case of GDB, it would be calculated by offset of link_map.l_ld
 864 // and the address of .dynamic section.
 865 // See GDB implementation: lm_addr_check @ solib-svr4.c
 866 static uintptr_t calc_prelinked_load_address(struct ps_prochandle* ph, int lib_fd, ELF_EHDR* elf_ehdr, uintptr_t link_map_addr) {
 867   ELF_PHDR *phbuf;
 868   uintptr_t lib_ld;
 869   uintptr_t lib_dyn_addr = 0L;
 870   uintptr_t load_addr;
 871   int i;
 872 
 873   phbuf = read_program_header_table(lib_fd, elf_ehdr);
 874   if (phbuf == NULL) {
 875     print_debug("can't read program header of shared object\n");
 876     return INVALID_LOAD_ADDRESS;
 877   }
 878 
 879   // Get the address of .dynamic section from shared library.
 880   for (i = 0; i < elf_ehdr->e_phnum; i++) {
 881     if (phbuf[i].p_type == PT_DYNAMIC) {
 882       lib_dyn_addr = phbuf[i].p_vaddr;
 883       break;
 884     }
 885   }
 886 
 887   free(phbuf);
 888 
 889   if (ps_pdread(ph, (psaddr_t)link_map_addr + LINK_MAP_LD_OFFSET,
 890                &lib_ld, sizeof(uintptr_t)) != PS_OK) {
 891     print_debug("can't read address of dynamic section in shared object\n");
 892     return INVALID_LOAD_ADDRESS;
 893   }
 894 
 895   // Return the load address which is calculated by the address of .dynamic
 896   // and link_map.l_ld .
 897   load_addr = lib_ld - lib_dyn_addr;
 898   print_debug("lib_ld = 0x%lx, lib_dyn_addr = 0x%lx -> lib_base_diff = 0x%lx\n", lib_ld, lib_dyn_addr, load_addr);
 899   return load_addr;
 900 }
 901 
 902 // read shared library info from runtime linker's data structures.
 903 // This work is done by librtlb_db in Solaris
 904 static bool read_shared_lib_info(struct ps_prochandle* ph) {
 905   uintptr_t addr = ph->core->dynamic_addr;
 906   uintptr_t debug_base;
 907   uintptr_t first_link_map_addr;
 908   uintptr_t ld_base_addr;
 909   uintptr_t link_map_addr;
 910   uintptr_t lib_base_diff;
 911   uintptr_t lib_base;
 912   uintptr_t lib_name_addr;
 913   char lib_name[BUF_SIZE];
 914   ELF_DYN dyn;
 915   ELF_EHDR elf_ehdr;
 916   int lib_fd;
 917 
 918   // _DYNAMIC has information of the form
 919   //         [tag] [data] [tag] [data] .....
 920   // Both tag and data are pointer sized.
 921   // We look for dynamic info with DT_DEBUG. This has shared object info.
 922   // refer to struct r_debug in link.h
 923 
 924   dyn.d_tag = DT_NULL;
 925   while (dyn.d_tag != DT_DEBUG) {
 926     if (ps_pdread(ph, (psaddr_t) addr, &dyn, sizeof(ELF_DYN)) != PS_OK) {
 927       print_debug("can't read debug info from _DYNAMIC\n");
 928       return false;
 929     }
 930     addr += sizeof(ELF_DYN);
 931   }
 932 
 933   // we have got Dyn entry with DT_DEBUG
 934   debug_base = dyn.d_un.d_ptr;
 935   // at debug_base we have struct r_debug. This has first link map in r_map field
 936   if (ps_pdread(ph, (psaddr_t) debug_base + FIRST_LINK_MAP_OFFSET,
 937                  &first_link_map_addr, sizeof(uintptr_t)) != PS_OK) {
 938     print_debug("can't read first link map address\n");
 939     return false;
 940   }
 941 
 942   // read ld_base address from struct r_debug
 943   if (ps_pdread(ph, (psaddr_t) debug_base + LD_BASE_OFFSET, &ld_base_addr,
 944                  sizeof(uintptr_t)) != PS_OK) {
 945     print_debug("can't read ld base address\n");
 946     return false;
 947   }
 948   ph->core->ld_base_addr = ld_base_addr;
 949 
 950   print_debug("interpreter base address is 0x%lx\n", ld_base_addr);
 951 
 952   // now read segments from interp (i.e ld.so or ld-linux.so or ld-elf.so)
 953   if (read_interp_segments(ph) != true) {
 954       return false;
 955   }
 956 
 957   // after adding interpreter (ld.so) mappings sort again
 958   if (sort_map_array(ph) != true) {
 959     return false;
 960   }
 961 
 962    print_debug("first link map is at 0x%lx\n", first_link_map_addr);
 963 
 964    link_map_addr = first_link_map_addr;
 965    while (link_map_addr != 0) {
 966       // read library base address of the .so. Note that even though <sys/link.h> calls
 967       // link_map->l_addr as "base address",  this is * not * really base virtual
 968       // address of the shared object. This is actually the difference b/w the virtual
 969       // address mentioned in shared object and the actual virtual base where runtime
 970       // linker loaded it. We use "base diff" in read_lib_segments call below.
 971 
 972       if (ps_pdread(ph, (psaddr_t) link_map_addr + LINK_MAP_ADDR_OFFSET,
 973                    &lib_base_diff, sizeof(uintptr_t)) != PS_OK) {
 974          print_debug("can't read shared object base address diff\n");
 975          return false;
 976       }
 977 
 978       // read address of the name
 979       if (ps_pdread(ph, (psaddr_t) link_map_addr + LINK_MAP_NAME_OFFSET,
 980                     &lib_name_addr, sizeof(uintptr_t)) != PS_OK) {
 981          print_debug("can't read address of shared object name\n");
 982          return false;
 983       }
 984 
 985       // read name of the shared object
 986       lib_name[0] = '\0';
 987       if (lib_name_addr != 0 &&
 988           read_string(ph, (uintptr_t) lib_name_addr, lib_name, sizeof(lib_name)) != true) {
 989          print_debug("can't read shared object name\n");
 990          // don't let failure to read the name stop opening the file.  If something is really wrong
 991          // it will fail later.
 992       }
 993 
 994       if (lib_name[0] != '\0') {
 995          // ignore empty lib names
 996          lib_fd = pathmap_open(lib_name);
 997 
 998          if (lib_fd < 0) {
 999             print_debug("can't open shared object %s\n", lib_name);
1000             // continue with other libraries...
1001          } else {
1002             if (read_elf_header(lib_fd, &elf_ehdr)) {
1003                if (lib_base_diff == ZERO_LOAD_ADDRESS ) {
1004                  lib_base_diff = calc_prelinked_load_address(ph, lib_fd, &elf_ehdr, link_map_addr);
1005                  if (lib_base_diff == INVALID_LOAD_ADDRESS) {
1006                    close(lib_fd);
1007                    return false;
1008                  }
1009                }
1010 
1011                lib_base = lib_base_diff + find_base_address(lib_fd, &elf_ehdr);
1012                print_debug("reading library %s @ 0x%lx [ 0x%lx ]\n",
1013                            lib_name, lib_base, lib_base_diff);
1014                // while adding library mappings we need to use "base difference".
1015                if (! read_lib_segments(ph, lib_fd, &elf_ehdr, lib_base_diff)) {
1016                   print_debug("can't read shared object's segments\n");
1017                   close(lib_fd);
1018                   return false;
1019                }
1020                add_lib_info_fd(ph, lib_name, lib_fd, lib_base);
1021                // Map info is added for the library (lib_name) so
1022                // we need to re-sort it before calling the p_pdread.
1023                if (sort_map_array(ph) != true)
1024                   return false;
1025             } else {
1026                print_debug("can't read ELF header for shared object %s\n", lib_name);
1027                close(lib_fd);
1028                // continue with other libraries...
1029             }
1030          }
1031       }
1032 
1033     // read next link_map address
1034     if (ps_pdread(ph, (psaddr_t) link_map_addr + LINK_MAP_NEXT_OFFSET,
1035                    &link_map_addr, sizeof(uintptr_t)) != PS_OK) {
1036       print_debug("can't read next link in link_map\n");
1037       return false;
1038     }
1039   }
1040 
1041   return true;
1042 }
1043 
1044 // the one and only one exposed stuff from this file
1045 JNIEXPORT struct ps_prochandle* JNICALL
1046 Pgrab_core(const char* exec_file, const char* core_file) {
1047   ELF_EHDR core_ehdr;
1048   ELF_EHDR exec_ehdr;
1049   ELF_EHDR lib_ehdr;
1050 
1051   struct ps_prochandle* ph = (struct ps_prochandle*) calloc(1, sizeof(struct ps_prochandle));
1052   if (ph == NULL) {
1053     print_debug("can't allocate ps_prochandle\n");
1054     return NULL;
1055   }
1056 
1057   if ((ph->core = (struct core_data*) calloc(1, sizeof(struct core_data))) == NULL) {
1058     free(ph);
1059     print_debug("can't allocate ps_prochandle\n");
1060     return NULL;
1061   }
1062 
1063   // initialize ph
1064   ph->ops = &core_ops;
1065   ph->core->core_fd   = -1;
1066   ph->core->exec_fd   = -1;
1067   ph->core->interp_fd = -1;
1068 
1069   // open the core file
1070   if ((ph->core->core_fd = open(core_file, O_RDONLY)) < 0) {
1071     print_debug("can't open core file\n");
1072     goto err;
1073   }
1074 
1075   // read core file ELF header
1076   if (read_elf_header(ph->core->core_fd, &core_ehdr) != true || core_ehdr.e_type != ET_CORE) {
1077     print_debug("core file is not a valid ELF ET_CORE file\n");
1078     goto err;
1079   }
1080 
1081   if ((ph->core->exec_fd = open(exec_file, O_RDONLY)) < 0) {
1082     print_debug("can't open executable file\n");
1083     goto err;
1084   }
1085 
1086   if (read_elf_header(ph->core->exec_fd, &exec_ehdr) != true ||
1087       ((exec_ehdr.e_type != ET_EXEC) && (exec_ehdr.e_type != ET_DYN))) {
1088     print_debug("executable file is not a valid ELF file\n");
1089     goto err;
1090   }
1091 
1092   // process core file segments
1093   if (read_core_segments(ph, &core_ehdr) != true) {
1094     goto err;
1095   }
1096 
1097   // process exec file segments
1098   if (read_exec_segments(ph, &exec_ehdr) != true) {
1099     goto err;
1100   }
1101 
1102   // exec file is also treated like a shared object for symbol search
1103   if (add_lib_info_fd(ph, exec_file, ph->core->exec_fd,
1104                       (uintptr_t)0 + find_base_address(ph->core->exec_fd, &exec_ehdr)) == NULL) {
1105     goto err;
1106   }
1107 
1108   // allocate and sort maps into map_array, we need to do this
1109   // here because read_shared_lib_info needs to read from debuggee
1110   // address space
1111   if (sort_map_array(ph) != true) {
1112     goto err;
1113   }
1114 
1115   if (read_shared_lib_info(ph) != true) {
1116     goto err;
1117   }
1118 
1119   // sort again because we have added more mappings from shared objects
1120   if (sort_map_array(ph) != true) {
1121     goto err;
1122   }
1123 
1124   if (init_classsharing_workaround(ph) != true) {
1125     goto err;
1126   }
1127 
1128   return ph;
1129 
1130 err:
1131   Prelease(ph);
1132   return NULL;
1133 }