1 /*
   2  * Copyright (c) 2003, 2018, 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 "libproc_impl.h"
  32 
  33 #ifdef __APPLE__
  34 #include "sun_jvm_hotspot_debugger_amd64_AMD64ThreadContext.h"
  35 #endif
  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) {
 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   return map;
 119 }
 120 
 121 // add map info with given fd, offset, vaddr and memsz
 122 static map_info* add_map_info(struct ps_prochandle* ph, int fd, off_t offset,
 123                              uintptr_t vaddr, size_t memsz) {
 124   map_info* map;
 125   if ((map = allocate_init_map(fd, offset, vaddr, memsz)) == NULL) {
 126     return NULL;
 127   }
 128 
 129   // add this to map list
 130   map->next  = ph->core->maps;
 131   ph->core->maps   = map;
 132   ph->core->num_maps++;
 133 
 134   return map;
 135 }
 136 
 137 // Part of the class sharing workaround
 138 static map_info* add_class_share_map_info(struct ps_prochandle* ph, off_t offset,
 139                              uintptr_t vaddr, size_t memsz) {
 140   map_info* map;
 141   if ((map = allocate_init_map(ph->core->classes_jsa_fd,
 142                                offset, vaddr, memsz)) == NULL) {
 143     return NULL;
 144   }
 145 
 146   map->next = ph->core->class_share_maps;
 147   ph->core->class_share_maps = map;
 148   return map;
 149 }
 150 
 151 // Return the map_info for the given virtual address.  We keep a sorted
 152 // array of pointers in ph->map_array, so we can binary search.
 153 static map_info* core_lookup(struct ps_prochandle *ph, uintptr_t addr) {
 154   int mid, lo = 0, hi = ph->core->num_maps - 1;
 155   map_info *mp;
 156 
 157   while (hi - lo > 1) {
 158     mid = (lo + hi) / 2;
 159     if (addr >= ph->core->map_array[mid]->vaddr) {
 160       lo = mid;
 161     } else {
 162       hi = mid;
 163     }
 164   }
 165 
 166   if (addr < ph->core->map_array[hi]->vaddr) {
 167     mp = ph->core->map_array[lo];
 168   } else {
 169     mp = ph->core->map_array[hi];
 170   }
 171 
 172   if (addr >= mp->vaddr && addr < mp->vaddr + mp->memsz) {
 173     return (mp);
 174   }
 175 
 176 
 177   // Part of the class sharing workaround
 178   // Unfortunately, we have no way of detecting -Xshare state.
 179   // Check out the share maps atlast, if we don't find anywhere.
 180   // This is done this way so to avoid reading share pages
 181   // ahead of other normal maps. For eg. with -Xshare:off we don't
 182   // want to prefer class sharing data to data from core.
 183   mp = ph->core->class_share_maps;
 184   if (mp) {
 185     print_debug("can't locate map_info at 0x%lx, trying class share maps\n", addr);
 186   }
 187   while (mp) {
 188     if (addr >= mp->vaddr && addr < mp->vaddr + mp->memsz) {
 189       print_debug("located map_info at 0x%lx from class share maps\n", addr);
 190       return (mp);
 191     }
 192     mp = mp->next;
 193   }
 194 
 195   print_debug("can't locate map_info at 0x%lx\n", addr);
 196   return (NULL);
 197 }
 198 
 199 //---------------------------------------------------------------
 200 // Part of the class sharing workaround:
 201 //
 202 // With class sharing, pages are mapped from classes.jsa file.
 203 // The read-only class sharing pages are mapped as MAP_SHARED,
 204 // PROT_READ pages. These pages are not dumped into core dump.
 205 // With this workaround, these pages are read from classes.jsa.
 206 
 207 // FIXME: !HACK ALERT!
 208 // The format of sharing achive file header is needed to read shared heap
 209 // file mappings. For now, I am hard coding portion of FileMapHeader here.
 210 // Refer to filemap.hpp.
 211 
 212 // FileMapHeader describes the shared space data in the file to be
 213 // mapped.  This structure gets written to a file.  It is not a class,
 214 // so that the compilers don't add any compiler-private data to it.
 215 
 216 #define NUM_SHARED_MAPS 9
 217 
 218 // Refer to FileMapInfo::_current_version in filemap.hpp
 219 #define CURRENT_ARCHIVE_VERSION 3
 220 
 221 typedef unsigned char* address;
 222 typedef uintptr_t      uintx;
 223 typedef intptr_t       intx;
 224 
 225 
 226 struct FileMapHeader {
 227   int     _magic;                   // identify file type.
 228   int     _crc;                     // header crc checksum.
 229   int     _version;                 // (from enum, above.)
 230   size_t  _alignment;               // how shared archive should be aligned
 231   int     _obj_alignment;           // value of ObjectAlignmentInBytes
 232   address _narrow_oop_base;         // compressed oop encoding base
 233   int     _narrow_oop_shift;        // compressed oop encoding shift
 234   bool    _compact_strings;         // value of CompactStrings
 235   uintx   _max_heap_size;           // java max heap size during dumping
 236   int     _narrow_oop_mode;         // compressed oop encoding mode
 237   int     _narrow_klass_shift;      // save narrow klass base and shift
 238   address _narrow_klass_base;
 239   char*   _misc_data_patching_start;
 240   char*   _read_only_tables_start;
 241   address _cds_i2i_entry_code_buffers;
 242   size_t  _cds_i2i_entry_code_buffers_size;
 243   size_t  _core_spaces_size;        // number of bytes allocated by the core spaces
 244                                     // (mc, md, ro, rw and od).
 245 
 246 
 247   struct space_info {
 248     int     _crc;          // crc checksum of the current space
 249     size_t  _file_offset;  // sizeof(this) rounded to vm page size
 250     union {
 251       char*  _base;        // copy-on-write base address
 252       intx   _offset;      // offset from the compressed oop encoding base, only used
 253                            // by archive heap space
 254     } _addr;
 255     size_t _used;          // for setting space top on read
 256     // 4991491 NOTICE These are C++ bool's in filemap.hpp and must match up with
 257     // the C type matching the C++ bool type on any given platform.
 258     // We assume the corresponding C type is char but licensees
 259     // may need to adjust the type of these fields.
 260     char   _read_only;     // read only space?
 261     char   _allow_exec;    // executable code in space?
 262   } _space[NUM_SHARED_MAPS];
 263 
 264   // Ignore the rest of the FileMapHeader. We don't need those fields here.
 265 };
 266 
 267 static bool read_jboolean(struct ps_prochandle* ph, uintptr_t addr, jboolean* pvalue) {
 268   jboolean i;
 269   if (ps_pread(ph, (psaddr_t) addr, &i, sizeof(i)) == PS_OK) {
 270     *pvalue = i;
 271     return true;
 272   } else {
 273     return false;
 274   }
 275 }
 276 
 277 static bool read_pointer(struct ps_prochandle* ph, uintptr_t addr, uintptr_t* pvalue) {
 278   uintptr_t uip;
 279   if (ps_pread(ph, (psaddr_t) addr, (char *)&uip, sizeof(uip)) == PS_OK) {
 280     *pvalue = uip;
 281     return true;
 282   } else {
 283     return false;
 284   }
 285 }
 286 
 287 // used to read strings from debuggee
 288 static bool read_string(struct ps_prochandle* ph, uintptr_t addr, char* buf, size_t size) {
 289   size_t i = 0;
 290   char  c = ' ';
 291 
 292   while (c != '\0') {
 293     if (ps_pread(ph, (psaddr_t) addr, &c, sizeof(char)) != PS_OK) {
 294       return false;
 295     }
 296     if (i < size - 1) {
 297       buf[i] = c;
 298     } else {
 299       // smaller buffer
 300       return false;
 301     }
 302     i++; addr++;
 303   }
 304   buf[i] = '\0';
 305   return true;
 306 }
 307 
 308 // mangled name of Arguments::SharedArchivePath
 309 #define SHARED_ARCHIVE_PATH_SYM "__ZN9Arguments17SharedArchivePathE"
 310 
 311 #ifdef __APPLE__
 312 #define USE_SHARED_SPACES_SYM "_UseSharedSpaces"
 313 #define LIBJVM_NAME "/libjvm.dylib"
 314 #else
 315 #define USE_SHARED_SPACES_SYM "UseSharedSpaces"
 316 #define LIBJVM_NAME "/libjvm.so"
 317 #endif // __APPLE_
 318 
 319 static bool init_classsharing_workaround(struct ps_prochandle* ph) {
 320   int m;
 321   size_t n;
 322   lib_info* lib = ph->libs;
 323   while (lib != NULL) {
 324     // we are iterating over shared objects from the core dump. look for
 325     // libjvm.so.
 326     const char *jvm_name = 0;
 327     if ((jvm_name = strstr(lib->name, LIBJVM_NAME)) != 0) {
 328       char classes_jsa[PATH_MAX];
 329       struct FileMapHeader header;
 330       int fd = -1;
 331       uintptr_t base = 0, useSharedSpacesAddr = 0;
 332       uintptr_t sharedArchivePathAddrAddr = 0, sharedArchivePathAddr = 0;
 333       jboolean useSharedSpaces = 0;
 334 
 335       memset(classes_jsa, 0, sizeof(classes_jsa));
 336       jvm_name = lib->name;
 337       useSharedSpacesAddr = lookup_symbol(ph, jvm_name, USE_SHARED_SPACES_SYM);
 338       if (useSharedSpacesAddr == 0) {
 339         print_debug("can't lookup 'UseSharedSpaces' flag\n");
 340         return false;
 341       }
 342 
 343       // Hotspot vm types are not exported to build this library. So
 344       // using equivalent type jboolean to read the value of
 345       // UseSharedSpaces which is same as hotspot type "bool".
 346       if (read_jboolean(ph, useSharedSpacesAddr, &useSharedSpaces) != true) {
 347         print_debug("can't read the value of 'UseSharedSpaces' flag\n");
 348         return false;
 349       }
 350 
 351       if ((int)useSharedSpaces == 0) {
 352         print_debug("UseSharedSpaces is false, assuming -Xshare:off!\n");
 353         return true;
 354       }
 355 
 356       sharedArchivePathAddrAddr = lookup_symbol(ph, jvm_name, SHARED_ARCHIVE_PATH_SYM);
 357       if (sharedArchivePathAddrAddr == 0) {
 358         print_debug("can't lookup shared archive path symbol\n");
 359         return false;
 360       }
 361 
 362       if (read_pointer(ph, sharedArchivePathAddrAddr, &sharedArchivePathAddr) != true) {
 363         print_debug("can't read shared archive path pointer\n");
 364         return false;
 365       }
 366 
 367       if (read_string(ph, sharedArchivePathAddr, classes_jsa, sizeof(classes_jsa)) != true) {
 368         print_debug("can't read shared archive path value\n");
 369         return false;
 370       }
 371 
 372       print_debug("looking for %s\n", classes_jsa);
 373       // open the class sharing archive file
 374       fd = pathmap_open(classes_jsa);
 375       if (fd < 0) {
 376         print_debug("can't open %s!\n", classes_jsa);
 377         ph->core->classes_jsa_fd = -1;
 378         return false;
 379       } else {
 380         print_debug("opened %s\n", classes_jsa);
 381       }
 382 
 383       // read FileMapHeader from the file
 384       memset(&header, 0, sizeof(struct FileMapHeader));
 385       if ((n = read(fd, &header, sizeof(struct FileMapHeader)))
 386            != sizeof(struct FileMapHeader)) {
 387         print_debug("can't read shared archive file map header from %s\n", classes_jsa);
 388         close(fd);
 389         return false;
 390       }
 391 
 392       // check file magic
 393       if (header._magic != 0xf00baba2) {
 394         print_debug("%s has bad shared archive file magic number 0x%x, expecing 0xf00baba2\n",
 395                      classes_jsa, header._magic);
 396         close(fd);
 397         return false;
 398       }
 399 
 400       // check version
 401       if (header._version != CURRENT_ARCHIVE_VERSION) {
 402         print_debug("%s has wrong shared archive file version %d, expecting %d\n",
 403                      classes_jsa, header._version, CURRENT_ARCHIVE_VERSION);
 404         close(fd);
 405         return false;
 406       }
 407 
 408       ph->core->classes_jsa_fd = fd;
 409       // add read-only maps from classes.jsa to the list of maps
 410       for (m = 0; m < NUM_SHARED_MAPS; m++) {
 411         if (header._space[m]._read_only) {
 412           base = (uintptr_t) header._space[m]._addr._base;
 413           // no need to worry about the fractional pages at-the-end.
 414           // possible fractional pages are handled by core_read_data.
 415           add_class_share_map_info(ph, (off_t) header._space[m]._file_offset,
 416                                    base, (size_t) header._space[m]._used);
 417           print_debug("added a share archive map at 0x%lx\n", base);
 418         }
 419       }
 420       return true;
 421    }
 422    lib = lib->next;
 423   }
 424   return true;
 425 }
 426 
 427 //---------------------------------------------------------------------------
 428 // functions to handle map_info
 429 
 430 // Order mappings based on virtual address.  We use this function as the
 431 // callback for sorting the array of map_info pointers.
 432 static int core_cmp_mapping(const void *lhsp, const void *rhsp)
 433 {
 434   const map_info *lhs = *((const map_info **)lhsp);
 435   const map_info *rhs = *((const map_info **)rhsp);
 436 
 437   if (lhs->vaddr == rhs->vaddr) {
 438     return (0);
 439   }
 440 
 441   return (lhs->vaddr < rhs->vaddr ? -1 : 1);
 442 }
 443 
 444 // we sort map_info by starting virtual address so that we can do
 445 // binary search to read from an address.
 446 static bool sort_map_array(struct ps_prochandle* ph) {
 447   size_t num_maps = ph->core->num_maps;
 448   map_info* map = ph->core->maps;
 449   int i = 0;
 450 
 451   // allocate map_array
 452   map_info** array;
 453   if ( (array = (map_info**) malloc(sizeof(map_info*) * num_maps)) == NULL) {
 454     print_debug("can't allocate memory for map array\n");
 455     return false;
 456   }
 457 
 458   // add maps to array
 459   while (map) {
 460     array[i] = map;
 461     i++;
 462     map = map->next;
 463   }
 464 
 465   // sort is called twice. If this is second time, clear map array
 466   if (ph->core->map_array) {
 467     free(ph->core->map_array);
 468   }
 469   ph->core->map_array = array;
 470   // sort the map_info array by base virtual address.
 471   qsort(ph->core->map_array, ph->core->num_maps, sizeof (map_info*),
 472         core_cmp_mapping);
 473 
 474   // print map
 475   if (is_debug()) {
 476     int j = 0;
 477     print_debug("---- sorted virtual address map ----\n");
 478     for (j = 0; j < ph->core->num_maps; j++) {
 479       print_debug("base = 0x%lx\tsize = %d\n", ph->core->map_array[j]->vaddr,
 480                   ph->core->map_array[j]->memsz);
 481     }
 482   }
 483 
 484   return true;
 485 }
 486 
 487 #ifndef MIN
 488 #define MIN(x, y) (((x) < (y))? (x): (y))
 489 #endif
 490 
 491 static bool core_read_data(struct ps_prochandle* ph, uintptr_t addr, char *buf, size_t size) {
 492    ssize_t resid = size;
 493    int page_size=sysconf(_SC_PAGE_SIZE);
 494    while (resid != 0) {
 495       map_info *mp = core_lookup(ph, addr);
 496       uintptr_t mapoff;
 497       ssize_t len, rem;
 498       off_t off;
 499       int fd;
 500 
 501       if (mp == NULL) {
 502          break;  /* No mapping for this address */
 503       }
 504 
 505       fd = mp->fd;
 506       mapoff = addr - mp->vaddr;
 507       len = MIN(resid, mp->memsz - mapoff);
 508       off = mp->offset + mapoff;
 509 
 510       if ((len = pread(fd, buf, len, off)) <= 0) {
 511          break;
 512       }
 513 
 514       resid -= len;
 515       addr += len;
 516       buf = (char *)buf + len;
 517 
 518       // mappings always start at page boundary. But, may end in fractional
 519       // page. fill zeros for possible fractional page at the end of a mapping.
 520       rem = mp->memsz % page_size;
 521       if (rem > 0) {
 522          rem = page_size - rem;
 523          len = MIN(resid, rem);
 524          resid -= len;
 525          addr += len;
 526          // we are not assuming 'buf' to be zero initialized.
 527          memset(buf, 0, len);
 528          buf += len;
 529       }
 530    }
 531 
 532    if (resid) {
 533       print_debug("core read failed for %d byte(s) @ 0x%lx (%d more bytes)\n",
 534               size, addr, resid);
 535       return false;
 536    } else {
 537       return true;
 538    }
 539 }
 540 
 541 // null implementation for write
 542 static bool core_write_data(struct ps_prochandle* ph,
 543                              uintptr_t addr, const char *buf , size_t size) {
 544    return false;
 545 }
 546 
 547 static bool core_get_lwp_regs(struct ps_prochandle* ph, lwpid_t lwp_id,
 548                           struct reg* regs) {
 549    // for core we have cached the lwp regs after segment parsed
 550    sa_thread_info* thr = ph->threads;
 551    while (thr) {
 552      if (thr->lwp_id == lwp_id) {
 553        memcpy(regs, &thr->regs, sizeof(struct reg));
 554        return true;
 555      }
 556      thr = thr->next;
 557    }
 558    return false;
 559 }
 560 
 561 static bool core_get_lwp_info(struct ps_prochandle *ph, lwpid_t id, void *info) {
 562    print_debug("core_get_lwp_info not implemented\n");
 563    return false;
 564 }
 565 
 566 static ps_prochandle_ops core_ops = {
 567    .release=  core_release,
 568    .p_pread=  core_read_data,
 569    .p_pwrite= core_write_data,
 570    .get_lwp_regs= core_get_lwp_regs,
 571    .get_lwp_info= core_get_lwp_info
 572 };
 573 
 574 // from this point, mainly two blocks divided by def __APPLE__
 575 // one for Macosx, the other for regular Bsd
 576 
 577 #ifdef __APPLE__
 578 
 579 void print_thread(sa_thread_info *threadinfo) {
 580   print_debug("thread added: %d\n", threadinfo->lwp_id);
 581   print_debug("registers:\n");
 582   print_debug("  r_r15: 0x%" PRIx64 "\n", threadinfo->regs.r_r15);
 583   print_debug("  r_r14: 0x%" PRIx64 "\n", threadinfo->regs.r_r14);
 584   print_debug("  r_r13: 0x%" PRIx64 "\n", threadinfo->regs.r_r13);
 585   print_debug("  r_r12: 0x%" PRIx64 "\n", threadinfo->regs.r_r12);
 586   print_debug("  r_r11: 0x%" PRIx64 "\n", threadinfo->regs.r_r11);
 587   print_debug("  r_r10: 0x%" PRIx64 "\n", threadinfo->regs.r_r10);
 588   print_debug("  r_r9:  0x%" PRIx64 "\n", threadinfo->regs.r_r9);
 589   print_debug("  r_r8:  0x%" PRIx64 "\n", threadinfo->regs.r_r8);
 590   print_debug("  r_rdi: 0x%" PRIx64 "\n", threadinfo->regs.r_rdi);
 591   print_debug("  r_rsi: 0x%" PRIx64 "\n", threadinfo->regs.r_rsi);
 592   print_debug("  r_rbp: 0x%" PRIx64 "\n", threadinfo->regs.r_rbp);
 593   print_debug("  r_rbx: 0x%" PRIx64 "\n", threadinfo->regs.r_rbx);
 594   print_debug("  r_rdx: 0x%" PRIx64 "\n", threadinfo->regs.r_rdx);
 595   print_debug("  r_rcx: 0x%" PRIx64 "\n", threadinfo->regs.r_rcx);
 596   print_debug("  r_rax: 0x%" PRIx64 "\n", threadinfo->regs.r_rax);
 597   print_debug("  r_fs:  0x%" PRIx32 "\n", threadinfo->regs.r_fs);
 598   print_debug("  r_gs:  0x%" PRIx32 "\n", threadinfo->regs.r_gs);
 599   print_debug("  r_rip  0x%" PRIx64 "\n", threadinfo->regs.r_rip);
 600   print_debug("  r_cs:  0x%" PRIx64 "\n", threadinfo->regs.r_cs);
 601   print_debug("  r_rsp: 0x%" PRIx64 "\n", threadinfo->regs.r_rsp);
 602   print_debug("  r_rflags: 0x%" PRIx64 "\n", threadinfo->regs.r_rflags);
 603 }
 604 
 605 // read all segments64 commands from core file
 606 // read all thread commands from core file
 607 static bool read_core_segments(struct ps_prochandle* ph) {
 608   int i = 0;
 609   int num_threads = 0;
 610   int fd = ph->core->core_fd;
 611   off_t offset = 0;
 612   mach_header_64      fhead;
 613   load_command        lcmd;
 614   segment_command_64  segcmd;
 615   // thread_command      thrcmd;
 616 
 617   lseek(fd, offset, SEEK_SET);
 618   if(read(fd, (void *)&fhead, sizeof(mach_header_64)) != sizeof(mach_header_64)) {
 619      goto err;
 620   }
 621   print_debug("total commands: %d\n", fhead.ncmds);
 622   offset += sizeof(mach_header_64);
 623   for (i = 0; i < fhead.ncmds; i++) {
 624     lseek(fd, offset, SEEK_SET);
 625     if (read(fd, (void *)&lcmd, sizeof(load_command)) != sizeof(load_command)) {
 626       goto err;
 627     }
 628     offset += lcmd.cmdsize;    // next command position
 629     if (lcmd.cmd == LC_SEGMENT_64) {
 630       lseek(fd, -sizeof(load_command), SEEK_CUR);
 631       if (read(fd, (void *)&segcmd, sizeof(segment_command_64)) != sizeof(segment_command_64)) {
 632         print_debug("failed to read LC_SEGMENT_64 i = %d!\n", i);
 633         goto err;
 634       }
 635       if (add_map_info(ph, fd, segcmd.fileoff, segcmd.vmaddr, segcmd.vmsize) == NULL) {
 636         print_debug("Failed to add map_info at i = %d\n", i);
 637         goto err;
 638       }
 639       print_debug("segment added: %" PRIu64 " 0x%" PRIx64 " %d\n",
 640                    segcmd.fileoff, segcmd.vmaddr, segcmd.vmsize);
 641     } else if (lcmd.cmd == LC_THREAD || lcmd.cmd == LC_UNIXTHREAD) {
 642       typedef struct thread_fc {
 643         uint32_t  flavor;
 644         uint32_t  count;
 645       } thread_fc;
 646       thread_fc fc;
 647       uint32_t size = sizeof(load_command);
 648       while (size < lcmd.cmdsize) {
 649         if (read(fd, (void *)&fc, sizeof(thread_fc)) != sizeof(thread_fc)) {
 650           printf("Reading flavor, count failed.\n");
 651           goto err;
 652         }
 653         size += sizeof(thread_fc);
 654         if (fc.flavor == x86_THREAD_STATE) {
 655           x86_thread_state_t thrstate;
 656           if (read(fd, (void *)&thrstate, sizeof(x86_thread_state_t)) != sizeof(x86_thread_state_t)) {
 657             printf("Reading flavor, count failed.\n");
 658             goto err;
 659           }
 660           size += sizeof(x86_thread_state_t);
 661           // create thread info list, update lwp_id later
 662           sa_thread_info* newthr = add_thread_info(ph, (pthread_t) -1, (lwpid_t) num_threads++);
 663           if (newthr == NULL) {
 664             printf("create thread_info failed\n");
 665             goto err;
 666           }
 667 
 668           // note __DARWIN_UNIX03 depengs on other definitions
 669 #if __DARWIN_UNIX03
 670 #define get_register_v(regst, regname) \
 671   regst.uts.ts64.__##regname
 672 #else
 673 #define get_register_v(regst, regname) \
 674   regst.uts.ts64.##regname
 675 #endif // __DARWIN_UNIX03
 676           newthr->regs.r_rax = get_register_v(thrstate, rax);
 677           newthr->regs.r_rbx = get_register_v(thrstate, rbx);
 678           newthr->regs.r_rcx = get_register_v(thrstate, rcx);
 679           newthr->regs.r_rdx = get_register_v(thrstate, rdx);
 680           newthr->regs.r_rdi = get_register_v(thrstate, rdi);
 681           newthr->regs.r_rsi = get_register_v(thrstate, rsi);
 682           newthr->regs.r_rbp = get_register_v(thrstate, rbp);
 683           newthr->regs.r_rsp = get_register_v(thrstate, rsp);
 684           newthr->regs.r_r8  = get_register_v(thrstate, r8);
 685           newthr->regs.r_r9  = get_register_v(thrstate, r9);
 686           newthr->regs.r_r10 = get_register_v(thrstate, r10);
 687           newthr->regs.r_r11 = get_register_v(thrstate, r11);
 688           newthr->regs.r_r12 = get_register_v(thrstate, r12);
 689           newthr->regs.r_r13 = get_register_v(thrstate, r13);
 690           newthr->regs.r_r14 = get_register_v(thrstate, r14);
 691           newthr->regs.r_r15 = get_register_v(thrstate, r15);
 692           newthr->regs.r_rip = get_register_v(thrstate, rip);
 693           newthr->regs.r_rflags = get_register_v(thrstate, rflags);
 694           newthr->regs.r_cs  = get_register_v(thrstate, cs);
 695           newthr->regs.r_fs  = get_register_v(thrstate, fs);
 696           newthr->regs.r_gs  = get_register_v(thrstate, gs);
 697           print_thread(newthr);
 698         } else if (fc.flavor == x86_FLOAT_STATE) {
 699           x86_float_state_t flstate;
 700           if (read(fd, (void *)&flstate, sizeof(x86_float_state_t)) != sizeof(x86_float_state_t)) {
 701             print_debug("Reading flavor, count failed.\n");
 702             goto err;
 703           }
 704           size += sizeof(x86_float_state_t);
 705         } else if (fc.flavor == x86_EXCEPTION_STATE) {
 706           x86_exception_state_t excpstate;
 707           if (read(fd, (void *)&excpstate, sizeof(x86_exception_state_t)) != sizeof(x86_exception_state_t)) {
 708             printf("Reading flavor, count failed.\n");
 709             goto err;
 710           }
 711           size += sizeof(x86_exception_state_t);
 712         }
 713       }
 714     }
 715   }
 716   return true;
 717 err:
 718   return false;
 719 }
 720 
 721 /**local function **/
 722 bool exists(const char *fname) {
 723   return access(fname, F_OK) == 0;
 724 }
 725 
 726 // we check: 1. lib
 727 //           2. lib/server
 728 //           3. jre/lib
 729 //           4. jre/lib/server
 730 // from: 1. exe path
 731 //       2. JAVA_HOME
 732 //       3. DYLD_LIBRARY_PATH
 733 static bool get_real_path(struct ps_prochandle* ph, char *rpath) {
 734   /** check if they exist in JAVA ***/
 735   char* execname = ph->core->exec_path;
 736   char  filepath[4096];
 737   char* filename = strrchr(rpath, '/');               // like /libjvm.dylib
 738   if (filename == NULL) {
 739     return false;
 740   }
 741 
 742   char* posbin = strstr(execname, "/bin/java");
 743   if (posbin != NULL) {
 744     memcpy(filepath, execname, posbin - execname);    // not include trailing '/'
 745     filepath[posbin - execname] = '\0';
 746   } else {
 747     char* java_home = getenv("JAVA_HOME");
 748     if (java_home != NULL) {
 749       strcpy(filepath, java_home);
 750     } else {
 751       char* dyldpath = getenv("DYLD_LIBRARY_PATH");
 752       char* dypath = strtok(dyldpath, ":");
 753       while (dypath != NULL) {
 754         strcpy(filepath, dypath);
 755         strcat(filepath, filename);
 756         if (exists(filepath)) {
 757            strcpy(rpath, filepath);
 758            return true;
 759         }
 760         dypath = strtok(dyldpath, ":");
 761       }
 762       // not found
 763       return false;
 764     }
 765   }
 766   // for exec and java_home, jdkpath now is filepath
 767   size_t filepath_base_size = strlen(filepath);
 768 
 769   // first try /lib/ and /lib/server
 770   strcat(filepath, "/lib");
 771   strcat(filepath, filename);
 772   if (exists(filepath)) {
 773     strcpy(rpath, filepath);
 774     return true;
 775   }
 776   char* pos = strstr(filepath, filename);    // like /libjvm.dylib
 777   *pos = '\0';
 778   strcat(filepath, "/server");
 779   strcat(filepath, filename);
 780   if (exists(filepath)) {
 781     strcpy(rpath, filepath);
 782     return true;
 783   }
 784 
 785   // then try /jre/lib/ and /jre/lib/server
 786   filepath[filepath_base_size] = '\0';
 787   strcat(filepath, "/jre/lib");
 788   strcat(filepath, filename);
 789   if (exists(filepath)) {
 790     strcpy(rpath, filepath);
 791     return true;
 792   }
 793   pos = strstr(filepath, filename);
 794   *pos = '\0';
 795   strcat(filepath, "/server");
 796   strcat(filepath, filename);
 797   if (exists(filepath)) {
 798     strcpy(rpath, filepath);
 799     return true;
 800   }
 801 
 802   return false;
 803 }
 804 
 805 static bool read_shared_lib_info(struct ps_prochandle* ph) {
 806   static int pagesize = 0;
 807   int fd = ph->core->core_fd;
 808   int i = 0, j;
 809   uint32_t  v;
 810   mach_header_64 header;        // used to check if a file header in segment
 811   load_command lcmd;
 812   dylib_command dylibcmd;
 813 
 814   char name[BUF_SIZE];  // use to store name
 815 
 816   if (pagesize == 0) {
 817     pagesize = getpagesize();
 818     print_debug("page size is %d\n", pagesize);
 819   }
 820   for (j = 0; j < ph->core->num_maps; j++) {
 821     map_info *iter = ph->core->map_array[j];   // head
 822     off_t fpos = iter->offset;
 823     if (iter->fd != fd) {
 824       // only search core file!
 825       continue;
 826     }
 827     print_debug("map_info %d: vmaddr = 0x%016" PRIx64 "  fileoff = %" PRIu64 "  vmsize = %" PRIu64 "\n",
 828                            j, iter->vaddr, iter->offset, iter->memsz);
 829     lseek(fd, fpos, SEEK_SET);
 830     // we assume .dylib loaded at segment address --- which is true for JVM libraries
 831     // multiple files may be loaded in one segment.
 832     // if first word is not a magic word, means this segment does not contain lib file.
 833     if (read(fd, (void *)&v, sizeof(uint32_t)) == sizeof(uint32_t)) {
 834       if (v != MH_MAGIC_64) {
 835         continue;
 836       }
 837     } else {
 838       // may be encountered last map, which is not readable
 839       continue;
 840     }
 841     while (ltell(fd) - iter->offset < iter->memsz) {
 842       lseek(fd, fpos, SEEK_SET);
 843       if (read(fd, (void *)&v, sizeof(uint32_t)) != sizeof(uint32_t)) {
 844         break;
 845       }
 846       if (v != MH_MAGIC_64) {
 847         fpos = (ltell(fd) + pagesize -1)/pagesize * pagesize;
 848         continue;
 849       }
 850       lseek(fd, -sizeof(uint32_t), SEEK_CUR);
 851       // this is the file begining to core file.
 852       if (read(fd, (void *)&header, sizeof(mach_header_64)) != sizeof(mach_header_64)) {
 853         goto err;
 854       }
 855       fpos = ltell(fd);
 856 
 857       // found a mach-o file in this segment
 858       for (i = 0; i < header.ncmds; i++) {
 859         // read commands in this "file"
 860         // LC_ID_DYLIB is the file itself for a .dylib
 861         lseek(fd, fpos, SEEK_SET);
 862         if (read(fd, (void *)&lcmd, sizeof(load_command)) != sizeof(load_command)) {
 863           return false;   // error
 864         }
 865         fpos += lcmd.cmdsize;  // next command position
 866         // make sure still within seg size.
 867         if (fpos  - lcmd.cmdsize - iter->offset > iter->memsz) {
 868           print_debug("Warning: out of segement limit: %ld \n", fpos  - lcmd.cmdsize - iter->offset);
 869           break;  // no need to iterate all commands
 870         }
 871         if (lcmd.cmd == LC_ID_DYLIB) {
 872           lseek(fd, -sizeof(load_command), SEEK_CUR);
 873           if (read(fd, (void *)&dylibcmd, sizeof(dylib_command)) != sizeof(dylib_command)) {
 874             return false;
 875           }
 876           /**** name stored at dylib_command.dylib.name.offset, is a C string  */
 877           lseek(fd, dylibcmd.dylib.name.offset - sizeof(dylib_command), SEEK_CUR);
 878           int j = 0;
 879           while (j < BUF_SIZE) {
 880             read(fd, (void *)(name + j), sizeof(char));
 881             if (name[j] == '\0') break;
 882             j++;
 883           }
 884           print_debug("%s\n", name);
 885           // changed name from @rpath/xxxx.dylib to real path
 886           if (strrchr(name, '@')) {
 887             get_real_path(ph, name);
 888             print_debug("get_real_path returned: %s\n", name);
 889           }
 890           add_lib_info(ph, name, iter->vaddr);
 891           break;
 892         }
 893       }
 894       // done with the file, advanced to next page to search more files
 895       fpos = (ltell(fd) + pagesize - 1) / pagesize * pagesize;
 896     }
 897   }
 898   return true;
 899 err:
 900   return false;
 901 }
 902 
 903 bool read_macho64_header(int fd, mach_header_64* core_header) {
 904   bool is_macho = false;
 905   if (fd < 0) return false;
 906   off_t pos = ltell(fd);
 907   lseek(fd, 0, SEEK_SET);
 908   if (read(fd, (void *)core_header, sizeof(mach_header_64)) != sizeof(mach_header_64)) {
 909     is_macho = false;
 910   } else {
 911     is_macho = (core_header->magic ==  MH_MAGIC_64 || core_header->magic ==  MH_CIGAM_64);
 912   }
 913   lseek(fd, pos, SEEK_SET);
 914   return is_macho;
 915 }
 916 
 917 // the one and only one exposed stuff from this file
 918 struct ps_prochandle* Pgrab_core(const char* exec_file, const char* core_file) {
 919   mach_header_64 core_header;
 920   mach_header_64 exec_header;
 921 
 922   struct ps_prochandle* ph = (struct ps_prochandle*) calloc(1, sizeof(struct ps_prochandle));
 923   if (ph == NULL) {
 924     print_debug("cant allocate ps_prochandle\n");
 925     return NULL;
 926   }
 927 
 928   if ((ph->core = (struct core_data*) calloc(1, sizeof(struct core_data))) == NULL) {
 929     free(ph);
 930     print_debug("can't allocate ps_prochandle\n");
 931     return NULL;
 932   }
 933 
 934   // initialize ph
 935   ph->ops = &core_ops;
 936   ph->core->core_fd   = -1;
 937   ph->core->exec_fd   = -1;
 938   ph->core->interp_fd = -1;
 939 
 940   print_debug("exec: %s   core: %s", exec_file, core_file);
 941 
 942   strncpy(ph->core->exec_path, exec_file, sizeof(ph->core->exec_path));
 943 
 944   // open the core file
 945   if ((ph->core->core_fd = open(core_file, O_RDONLY)) < 0) {
 946     print_error("can't open core file\n");
 947     goto err;
 948   }
 949 
 950   // read core file header
 951   if (read_macho64_header(ph->core->core_fd, &core_header) != true || core_header.filetype != MH_CORE) {
 952     print_debug("core file is not a valid Mach-O file\n");
 953     goto err;
 954   }
 955 
 956   if ((ph->core->exec_fd = open(exec_file, O_RDONLY)) < 0) {
 957     print_error("can't open executable file\n");
 958     goto err;
 959   }
 960 
 961   if (read_macho64_header(ph->core->exec_fd, &exec_header) != true ||
 962                           exec_header.filetype != MH_EXECUTE) {
 963     print_error("executable file is not a valid Mach-O file\n");
 964     goto err;
 965   }
 966 
 967   // process core file segments
 968   if (read_core_segments(ph) != true) {
 969     print_error("failed to read core segments\n");
 970     goto err;
 971   }
 972 
 973   // allocate and sort maps into map_array, we need to do this
 974   // here because read_shared_lib_info needs to read from debuggee
 975   // address space
 976   if (sort_map_array(ph) != true) {
 977     print_error("failed to sort segment map array\n");
 978     goto err;
 979   }
 980 
 981   if (read_shared_lib_info(ph) != true) {
 982     print_error("failed to read libraries\n");
 983     goto err;
 984   }
 985 
 986   // sort again because we have added more mappings from shared objects
 987   if (sort_map_array(ph) != true) {
 988     print_error("failed to sort segment map array\n");
 989     goto err;
 990   }
 991 
 992   if (init_classsharing_workaround(ph) != true) {
 993     print_error("failed to workaround classshareing\n");
 994     goto err;
 995   }
 996 
 997   print_debug("Leave Pgrab_core\n");
 998   return ph;
 999 
1000 err:
1001   Prelease(ph);
1002   return NULL;
1003 }
1004 
1005 #else // __APPLE__ (none macosx)
1006 
1007 // read regs and create thread from core file
1008 static bool core_handle_prstatus(struct ps_prochandle* ph, const char* buf, size_t nbytes) {
1009    // we have to read prstatus_t from buf
1010    // assert(nbytes == sizeof(prstaus_t), "size mismatch on prstatus_t");
1011    prstatus_t* prstat = (prstatus_t*) buf;
1012    sa_thread_info* newthr;
1013    print_debug("got integer regset for lwp %d\n", prstat->pr_pid);
1014    // we set pthread_t to -1 for core dump
1015    if((newthr = add_thread_info(ph, (pthread_t) -1,  prstat->pr_pid)) == NULL)
1016       return false;
1017 
1018    // copy regs
1019    memcpy(&newthr->regs, &prstat->pr_reg, sizeof(struct reg));
1020 
1021    if (is_debug()) {
1022       print_debug("integer regset\n");
1023 #ifdef i386
1024       // print the regset
1025       print_debug("\teax = 0x%x\n", newthr->regs.r_eax);
1026       print_debug("\tebx = 0x%x\n", newthr->regs.r_ebx);
1027       print_debug("\tecx = 0x%x\n", newthr->regs.r_ecx);
1028       print_debug("\tedx = 0x%x\n", newthr->regs.r_edx);
1029       print_debug("\tesp = 0x%x\n", newthr->regs.r_esp);
1030       print_debug("\tebp = 0x%x\n", newthr->regs.r_ebp);
1031       print_debug("\tesi = 0x%x\n", newthr->regs.r_esi);
1032       print_debug("\tedi = 0x%x\n", newthr->regs.r_edi);
1033       print_debug("\teip = 0x%x\n", newthr->regs.r_eip);
1034 #endif
1035 
1036 #if defined(amd64) || defined(x86_64)
1037       // print the regset
1038       print_debug("\tr15 = 0x%lx\n", newthr->regs.r_r15);
1039       print_debug("\tr14 = 0x%lx\n", newthr->regs.r_r14);
1040       print_debug("\tr13 = 0x%lx\n", newthr->regs.r_r13);
1041       print_debug("\tr12 = 0x%lx\n", newthr->regs.r_r12);
1042       print_debug("\trbp = 0x%lx\n", newthr->regs.r_rbp);
1043       print_debug("\trbx = 0x%lx\n", newthr->regs.r_rbx);
1044       print_debug("\tr11 = 0x%lx\n", newthr->regs.r_r11);
1045       print_debug("\tr10 = 0x%lx\n", newthr->regs.r_r10);
1046       print_debug("\tr9 = 0x%lx\n", newthr->regs.r_r9);
1047       print_debug("\tr8 = 0x%lx\n", newthr->regs.r_r8);
1048       print_debug("\trax = 0x%lx\n", newthr->regs.r_rax);
1049       print_debug("\trcx = 0x%lx\n", newthr->regs.r_rcx);
1050       print_debug("\trdx = 0x%lx\n", newthr->regs.r_rdx);
1051       print_debug("\trsi = 0x%lx\n", newthr->regs.r_rsi);
1052       print_debug("\trdi = 0x%lx\n", newthr->regs.r_rdi);
1053       //print_debug("\torig_rax = 0x%lx\n", newthr->regs.orig_rax);
1054       print_debug("\trip = 0x%lx\n", newthr->regs.r_rip);
1055       print_debug("\tcs = 0x%lx\n", newthr->regs.r_cs);
1056       //print_debug("\teflags = 0x%lx\n", newthr->regs.eflags);
1057       print_debug("\trsp = 0x%lx\n", newthr->regs.r_rsp);
1058       print_debug("\tss = 0x%lx\n", newthr->regs.r_ss);
1059       //print_debug("\tfs_base = 0x%lx\n", newthr->regs.fs_base);
1060       //print_debug("\tgs_base = 0x%lx\n", newthr->regs.gs_base);
1061       //print_debug("\tds = 0x%lx\n", newthr->regs.ds);
1062       //print_debug("\tes = 0x%lx\n", newthr->regs.es);
1063       //print_debug("\tfs = 0x%lx\n", newthr->regs.fs);
1064       //print_debug("\tgs = 0x%lx\n", newthr->regs.gs);
1065 #endif
1066    }
1067 
1068    return true;
1069 }
1070 
1071 #define ROUNDUP(x, y)  ((((x)+((y)-1))/(y))*(y))
1072 
1073 // read NT_PRSTATUS entries from core NOTE segment
1074 static bool core_handle_note(struct ps_prochandle* ph, ELF_PHDR* note_phdr) {
1075    char* buf = NULL;
1076    char* p = NULL;
1077    size_t size = note_phdr->p_filesz;
1078 
1079    // we are interested in just prstatus entries. we will ignore the rest.
1080    // Advance the seek pointer to the start of the PT_NOTE data
1081    if (lseek(ph->core->core_fd, note_phdr->p_offset, SEEK_SET) == (off_t)-1) {
1082       print_debug("failed to lseek to PT_NOTE data\n");
1083       return false;
1084    }
1085 
1086    // Now process the PT_NOTE structures.  Each one is preceded by
1087    // an Elf{32/64}_Nhdr structure describing its type and size.
1088    if ( (buf = (char*) malloc(size)) == NULL) {
1089       print_debug("can't allocate memory for reading core notes\n");
1090       goto err;
1091    }
1092 
1093    // read notes into buffer
1094    if (read(ph->core->core_fd, buf, size) != size) {
1095       print_debug("failed to read notes, core file must have been truncated\n");
1096       goto err;
1097    }
1098 
1099    p = buf;
1100    while (p < buf + size) {
1101       ELF_NHDR* notep = (ELF_NHDR*) p;
1102       char* descdata  = p + sizeof(ELF_NHDR) + ROUNDUP(notep->n_namesz, 4);
1103       print_debug("Note header with n_type = %d and n_descsz = %u\n",
1104                                    notep->n_type, notep->n_descsz);
1105 
1106       if (notep->n_type == NT_PRSTATUS) {
1107         if (core_handle_prstatus(ph, descdata, notep->n_descsz) != true) {
1108           return false;
1109         }
1110       }
1111       p = descdata + ROUNDUP(notep->n_descsz, 4);
1112    }
1113 
1114    free(buf);
1115    return true;
1116 
1117 err:
1118    if (buf) free(buf);
1119    return false;
1120 }
1121 
1122 // read all segments from core file
1123 static bool read_core_segments(struct ps_prochandle* ph, ELF_EHDR* core_ehdr) {
1124    int i = 0;
1125    ELF_PHDR* phbuf = NULL;
1126    ELF_PHDR* core_php = NULL;
1127 
1128    if ((phbuf =  read_program_header_table(ph->core->core_fd, core_ehdr)) == NULL)
1129       return false;
1130 
1131    /*
1132     * Now iterate through the program headers in the core file.
1133     * We're interested in two types of Phdrs: PT_NOTE (which
1134     * contains a set of saved /proc structures), and PT_LOAD (which
1135     * represents a memory mapping from the process's address space).
1136     *
1137     * Difference b/w Solaris PT_NOTE and Linux/BSD PT_NOTE:
1138     *
1139     *     In Solaris there are two PT_NOTE segments the first PT_NOTE (if present)
1140     *     contains /proc structs in the pre-2.6 unstructured /proc format. the last
1141     *     PT_NOTE has data in new /proc format.
1142     *
1143     *     In Solaris, there is only one pstatus (process status). pstatus contains
1144     *     integer register set among other stuff. For each LWP, we have one lwpstatus
1145     *     entry that has integer regset for that LWP.
1146     *
1147     *     Linux threads are actually 'clone'd processes. To support core analysis
1148     *     of "multithreaded" process, Linux creates more than one pstatus (called
1149     *     "prstatus") entry in PT_NOTE. Each prstatus entry has integer regset for one
1150     *     "thread". Please refer to Linux kernel src file 'fs/binfmt_elf.c', in particular
1151     *     function "elf_core_dump".
1152     */
1153 
1154     for (core_php = phbuf, i = 0; i < core_ehdr->e_phnum; i++) {
1155       switch (core_php->p_type) {
1156          case PT_NOTE:
1157             if (core_handle_note(ph, core_php) != true) {
1158               goto err;
1159             }
1160             break;
1161 
1162          case PT_LOAD: {
1163             if (core_php->p_filesz != 0) {
1164                if (add_map_info(ph, ph->core->core_fd, core_php->p_offset,
1165                   core_php->p_vaddr, core_php->p_filesz) == NULL) goto err;
1166             }
1167             break;
1168          }
1169       }
1170 
1171       core_php++;
1172    }
1173 
1174    free(phbuf);
1175    return true;
1176 err:
1177    free(phbuf);
1178    return false;
1179 }
1180 
1181 // read segments of a shared object
1182 static bool read_lib_segments(struct ps_prochandle* ph, int lib_fd, ELF_EHDR* lib_ehdr, uintptr_t lib_base) {
1183   int i = 0;
1184   ELF_PHDR* phbuf;
1185   ELF_PHDR* lib_php = NULL;
1186 
1187   int page_size=sysconf(_SC_PAGE_SIZE);
1188 
1189   if ((phbuf = read_program_header_table(lib_fd, lib_ehdr)) == NULL) {
1190     return false;
1191   }
1192 
1193   // we want to process only PT_LOAD segments that are not writable.
1194   // i.e., text segments. The read/write/exec (data) segments would
1195   // have been already added from core file segments.
1196   for (lib_php = phbuf, i = 0; i < lib_ehdr->e_phnum; i++) {
1197     if ((lib_php->p_type == PT_LOAD) && !(lib_php->p_flags & PF_W) && (lib_php->p_filesz != 0)) {
1198 
1199       uintptr_t target_vaddr = lib_php->p_vaddr + lib_base;
1200       map_info *existing_map = core_lookup(ph, target_vaddr);
1201 
1202       if (existing_map == NULL){
1203         if (add_map_info(ph, lib_fd, lib_php->p_offset,
1204                           target_vaddr, lib_php->p_filesz) == NULL) {
1205           goto err;
1206         }
1207       } else {
1208         if ((existing_map->memsz != page_size) &&
1209             (existing_map->fd != lib_fd) &&
1210             (existing_map->memsz != lib_php->p_filesz)){
1211 
1212           print_debug("address conflict @ 0x%lx (size = %ld, flags = %d\n)",
1213                         target_vaddr, lib_php->p_filesz, lib_php->p_flags);
1214           goto err;
1215         }
1216 
1217         /* replace PT_LOAD segment with library segment */
1218         print_debug("overwrote with new address mapping (memsz %ld -> %ld)\n",
1219                      existing_map->memsz, lib_php->p_filesz);
1220 
1221         existing_map->fd = lib_fd;
1222         existing_map->offset = lib_php->p_offset;
1223         existing_map->memsz = lib_php->p_filesz;
1224       }
1225     }
1226 
1227     lib_php++;
1228   }
1229 
1230   free(phbuf);
1231   return true;
1232 err:
1233   free(phbuf);
1234   return false;
1235 }
1236 
1237 // process segments from interpreter (ld.so or ld-linux.so or ld-elf.so)
1238 static bool read_interp_segments(struct ps_prochandle* ph) {
1239    ELF_EHDR interp_ehdr;
1240 
1241    if (read_elf_header(ph->core->interp_fd, &interp_ehdr) != true) {
1242        print_debug("interpreter is not a valid ELF file\n");
1243        return false;
1244    }
1245 
1246    if (read_lib_segments(ph, ph->core->interp_fd, &interp_ehdr, ph->core->ld_base_addr) != true) {
1247        print_debug("can't read segments of interpreter\n");
1248        return false;
1249    }
1250 
1251    return true;
1252 }
1253 
1254 // process segments of a a.out
1255 static bool read_exec_segments(struct ps_prochandle* ph, ELF_EHDR* exec_ehdr) {
1256    int i = 0;
1257    ELF_PHDR* phbuf = NULL;
1258    ELF_PHDR* exec_php = NULL;
1259 
1260    if ((phbuf = read_program_header_table(ph->core->exec_fd, exec_ehdr)) == NULL)
1261       return false;
1262 
1263    for (exec_php = phbuf, i = 0; i < exec_ehdr->e_phnum; i++) {
1264       switch (exec_php->p_type) {
1265 
1266          // add mappings for PT_LOAD segments
1267          case PT_LOAD: {
1268             // add only non-writable segments of non-zero filesz
1269             if (!(exec_php->p_flags & PF_W) && exec_php->p_filesz != 0) {
1270                if (add_map_info(ph, ph->core->exec_fd, exec_php->p_offset, exec_php->p_vaddr, exec_php->p_filesz) == NULL) goto err;
1271             }
1272             break;
1273          }
1274 
1275          // read the interpreter and it's segments
1276          case PT_INTERP: {
1277             char interp_name[BUF_SIZE];
1278 
1279             pread(ph->core->exec_fd, interp_name, MIN(exec_php->p_filesz, BUF_SIZE), exec_php->p_offset);
1280             print_debug("ELF interpreter %s\n", interp_name);
1281             // read interpreter segments as well
1282             if ((ph->core->interp_fd = pathmap_open(interp_name)) < 0) {
1283                print_debug("can't open runtime loader\n");
1284                goto err;
1285             }
1286             break;
1287          }
1288 
1289          // from PT_DYNAMIC we want to read address of first link_map addr
1290          case PT_DYNAMIC: {
1291             ph->core->dynamic_addr = exec_php->p_vaddr;
1292             print_debug("address of _DYNAMIC is 0x%lx\n", ph->core->dynamic_addr);
1293             break;
1294          }
1295 
1296       } // switch
1297       exec_php++;
1298    } // for
1299 
1300    free(phbuf);
1301    return true;
1302 err:
1303    free(phbuf);
1304    return false;
1305 }
1306 
1307 #define FIRST_LINK_MAP_OFFSET offsetof(struct r_debug,  r_map)
1308 #define LD_BASE_OFFSET        offsetof(struct r_debug,  r_ldbase)
1309 #define LINK_MAP_ADDR_OFFSET  offsetof(struct link_map, l_addr)
1310 #define LINK_MAP_NAME_OFFSET  offsetof(struct link_map, l_name)
1311 #define LINK_MAP_NEXT_OFFSET  offsetof(struct link_map, l_next)
1312 
1313 // read shared library info from runtime linker's data structures.
1314 // This work is done by librtlb_db in Solaris
1315 static bool read_shared_lib_info(struct ps_prochandle* ph) {
1316   uintptr_t addr = ph->core->dynamic_addr;
1317   uintptr_t debug_base;
1318   uintptr_t first_link_map_addr;
1319   uintptr_t ld_base_addr;
1320   uintptr_t link_map_addr;
1321   uintptr_t lib_base_diff;
1322   uintptr_t lib_base;
1323   uintptr_t lib_name_addr;
1324   char lib_name[BUF_SIZE];
1325   ELF_DYN dyn;
1326   ELF_EHDR elf_ehdr;
1327   int lib_fd;
1328 
1329   // _DYNAMIC has information of the form
1330   //         [tag] [data] [tag] [data] .....
1331   // Both tag and data are pointer sized.
1332   // We look for dynamic info with DT_DEBUG. This has shared object info.
1333   // refer to struct r_debug in link.h
1334 
1335   dyn.d_tag = DT_NULL;
1336   while (dyn.d_tag != DT_DEBUG) {
1337     if (ps_pread(ph, (psaddr_t) addr, &dyn, sizeof(ELF_DYN)) != PS_OK) {
1338       print_debug("can't read debug info from _DYNAMIC\n");
1339       return false;
1340     }
1341     addr += sizeof(ELF_DYN);
1342   }
1343 
1344   // we have got Dyn entry with DT_DEBUG
1345   debug_base = dyn.d_un.d_ptr;
1346   // at debug_base we have struct r_debug. This has first link map in r_map field
1347   if (ps_pread(ph, (psaddr_t) debug_base + FIRST_LINK_MAP_OFFSET,
1348                  &first_link_map_addr, sizeof(uintptr_t)) != PS_OK) {
1349     print_debug("can't read first link map address\n");
1350     return false;
1351   }
1352 
1353   // read ld_base address from struct r_debug
1354 #if 0  // There is no r_ldbase member on BSD
1355   if (ps_pread(ph, (psaddr_t) debug_base + LD_BASE_OFFSET, &ld_base_addr,
1356                   sizeof(uintptr_t)) != PS_OK) {
1357     print_debug("can't read ld base address\n");
1358     return false;
1359   }
1360   ph->core->ld_base_addr = ld_base_addr;
1361 #else
1362   ph->core->ld_base_addr = 0;
1363 #endif
1364 
1365   print_debug("interpreter base address is 0x%lx\n", ld_base_addr);
1366 
1367   // now read segments from interp (i.e ld.so or ld-linux.so or ld-elf.so)
1368   if (read_interp_segments(ph) != true) {
1369     return false;
1370   }
1371 
1372   // after adding interpreter (ld.so) mappings sort again
1373   if (sort_map_array(ph) != true) {
1374     return false;
1375   }
1376 
1377   print_debug("first link map is at 0x%lx\n", first_link_map_addr);
1378 
1379   link_map_addr = first_link_map_addr;
1380   while (link_map_addr != 0) {
1381     // read library base address of the .so. Note that even though <sys/link.h> calls
1382     // link_map->l_addr as "base address",  this is * not * really base virtual
1383     // address of the shared object. This is actually the difference b/w the virtual
1384     // address mentioned in shared object and the actual virtual base where runtime
1385     // linker loaded it. We use "base diff" in read_lib_segments call below.
1386 
1387     if (ps_pread(ph, (psaddr_t) link_map_addr + LINK_MAP_ADDR_OFFSET,
1388                  &lib_base_diff, sizeof(uintptr_t)) != PS_OK) {
1389       print_debug("can't read shared object base address diff\n");
1390       return false;
1391     }
1392 
1393     // read address of the name
1394     if (ps_pread(ph, (psaddr_t) link_map_addr + LINK_MAP_NAME_OFFSET,
1395                   &lib_name_addr, sizeof(uintptr_t)) != PS_OK) {
1396       print_debug("can't read address of shared object name\n");
1397       return false;
1398     }
1399 
1400     // read name of the shared object
1401     if (read_string(ph, (uintptr_t) lib_name_addr, lib_name, sizeof(lib_name)) != true) {
1402       print_debug("can't read shared object name\n");
1403       return false;
1404     }
1405 
1406     if (lib_name[0] != '\0') {
1407       // ignore empty lib names
1408       lib_fd = pathmap_open(lib_name);
1409 
1410       if (lib_fd < 0) {
1411         print_debug("can't open shared object %s\n", lib_name);
1412         // continue with other libraries...
1413       } else {
1414         if (read_elf_header(lib_fd, &elf_ehdr)) {
1415           lib_base = lib_base_diff + find_base_address(lib_fd, &elf_ehdr);
1416           print_debug("reading library %s @ 0x%lx [ 0x%lx ]\n",
1417                        lib_name, lib_base, lib_base_diff);
1418           // while adding library mappings we need to use "base difference".
1419           if (! read_lib_segments(ph, lib_fd, &elf_ehdr, lib_base_diff)) {
1420             print_debug("can't read shared object's segments\n");
1421             close(lib_fd);
1422             return false;
1423           }
1424           add_lib_info_fd(ph, lib_name, lib_fd, lib_base);
1425           // Map info is added for the library (lib_name) so
1426           // we need to re-sort it before calling the p_pdread.
1427           if (sort_map_array(ph) != true) {
1428             return false;
1429           }
1430         } else {
1431           print_debug("can't read ELF header for shared object %s\n", lib_name);
1432           close(lib_fd);
1433           // continue with other libraries...
1434         }
1435       }
1436     }
1437 
1438     // read next link_map address
1439     if (ps_pread(ph, (psaddr_t) link_map_addr + LINK_MAP_NEXT_OFFSET,
1440                   &link_map_addr, sizeof(uintptr_t)) != PS_OK) {
1441       print_debug("can't read next link in link_map\n");
1442       return false;
1443     }
1444   }
1445 
1446   return true;
1447 }
1448 
1449 // the one and only one exposed stuff from this file
1450 struct ps_prochandle* Pgrab_core(const char* exec_file, const char* core_file) {
1451   ELF_EHDR core_ehdr;
1452   ELF_EHDR exec_ehdr;
1453 
1454   struct ps_prochandle* ph = (struct ps_prochandle*) calloc(1, sizeof(struct ps_prochandle));
1455   if (ph == NULL) {
1456     print_debug("can't allocate ps_prochandle\n");
1457     return NULL;
1458   }
1459 
1460   if ((ph->core = (struct core_data*) calloc(1, sizeof(struct core_data))) == NULL) {
1461     free(ph);
1462     print_debug("can't allocate ps_prochandle\n");
1463     return NULL;
1464   }
1465 
1466   // initialize ph
1467   ph->ops = &core_ops;
1468   ph->core->core_fd   = -1;
1469   ph->core->exec_fd   = -1;
1470   ph->core->interp_fd = -1;
1471 
1472   print_debug("exec: %s   core: %s", exec_file, core_file);
1473 
1474   // open the core file
1475   if ((ph->core->core_fd = open(core_file, O_RDONLY)) < 0) {
1476     print_debug("can't open core file\n");
1477     goto err;
1478   }
1479 
1480   // read core file ELF header
1481   if (read_elf_header(ph->core->core_fd, &core_ehdr) != true || core_ehdr.e_type != ET_CORE) {
1482     print_debug("core file is not a valid ELF ET_CORE file\n");
1483     goto err;
1484   }
1485 
1486   if ((ph->core->exec_fd = open(exec_file, O_RDONLY)) < 0) {
1487     print_debug("can't open executable file\n");
1488     goto err;
1489   }
1490 
1491   if (read_elf_header(ph->core->exec_fd, &exec_ehdr) != true || exec_ehdr.e_type != ET_EXEC) {
1492     print_debug("executable file is not a valid ELF ET_EXEC file\n");
1493     goto err;
1494   }
1495 
1496   // process core file segments
1497   if (read_core_segments(ph, &core_ehdr) != true) {
1498     goto err;
1499   }
1500 
1501   // process exec file segments
1502   if (read_exec_segments(ph, &exec_ehdr) != true) {
1503     goto err;
1504   }
1505 
1506   // exec file is also treated like a shared object for symbol search
1507   if (add_lib_info_fd(ph, exec_file, ph->core->exec_fd,
1508                       (uintptr_t)0 + find_base_address(ph->core->exec_fd, &exec_ehdr)) == NULL) {
1509     goto err;
1510   }
1511 
1512   // allocate and sort maps into map_array, we need to do this
1513   // here because read_shared_lib_info needs to read from debuggee
1514   // address space
1515   if (sort_map_array(ph) != true) {
1516     goto err;
1517   }
1518 
1519   if (read_shared_lib_info(ph) != true) {
1520     goto err;
1521   }
1522 
1523   // sort again because we have added more mappings from shared objects
1524   if (sort_map_array(ph) != true) {
1525     goto err;
1526   }
1527 
1528   if (init_classsharing_workaround(ph) != true) {
1529     goto err;
1530   }
1531 
1532   print_debug("Leave Pgrab_core\n");
1533   return ph;
1534 
1535 err:
1536   Prelease(ph);
1537   return NULL;
1538 }
1539 
1540 #endif // __APPLE__