1 /*
   2  * Copyright (c) 2002, 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 "salibproc.h"
  26 #include "sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal.h"
  27 #include <thread_db.h>
  28 #include <strings.h>
  29 #include <limits.h>
  30 #include <demangle.h>
  31 #include <stdarg.h>
  32 #include <stdlib.h>
  33 #include <errno.h>
  34 
  35 #define CHECK_EXCEPTION_(value) if(env->ExceptionOccurred()) { return value; }
  36 #define CHECK_EXCEPTION if(env->ExceptionOccurred()) { return;}
  37 #define THROW_NEW_DEBUGGER_EXCEPTION_(str, value) { throwNewDebuggerException(env, str); return value; }
  38 #define THROW_NEW_DEBUGGER_EXCEPTION(str) { throwNewDebuggerException(env, str); return;}
  39 
  40 #define SYMBOL_BUF_SIZE  256
  41 #define ERR_MSG_SIZE     (PATH_MAX + 256)
  42 
  43 // debug modes
  44 static int _libsaproc_debug = 0;
  45 
  46 static void print_debug(const char* format,...) {
  47   if (_libsaproc_debug) {
  48     va_list alist;
  49 
  50     va_start(alist, format);
  51     fputs("libsaproc DEBUG: ", stderr);
  52     vfprintf(stderr, format, alist);
  53     va_end(alist);
  54   }
  55 }
  56 
  57 struct Debugger {
  58     JNIEnv* env;
  59     jobject this_obj;
  60 };
  61 
  62 struct DebuggerWithObject : Debugger {
  63     jobject obj;
  64 };
  65 
  66 struct DebuggerWith2Objects : DebuggerWithObject {
  67     jobject obj2;
  68 };
  69 
  70 /*
  71 * Portions of user thread level detail gathering code is from pstack source
  72 * code. See pstack.c in Solaris 2.8 user commands source code.
  73 */
  74 
  75 static void throwNewDebuggerException(JNIEnv* env, const char* errMsg) {
  76   env->ThrowNew(env->FindClass("sun/jvm/hotspot/debugger/DebuggerException"), errMsg);
  77 }
  78 
  79 // JNI ids for some fields, methods
  80 
  81 // libproc handler pointer
  82 static jfieldID p_ps_prochandle_ID = 0;
  83 
  84 // libthread.so dlopen handle, thread agent ptr and function pointers
  85 static jfieldID libthread_db_handle_ID   = 0;
  86 static jfieldID p_td_thragent_t_ID       = 0;
  87 static jfieldID p_td_init_ID             = 0;
  88 static jfieldID p_td_ta_new_ID           = 0;
  89 static jfieldID p_td_ta_delete_ID        = 0;
  90 static jfieldID p_td_ta_thr_iter_ID      = 0;
  91 static jfieldID p_td_thr_get_info_ID     = 0;
  92 static jfieldID p_td_ta_map_id2thr_ID    = 0;
  93 static jfieldID p_td_thr_getgregs_ID     = 0;
  94 
  95 // reg index fields
  96 static jfieldID pcRegIndex_ID            = 0;
  97 static jfieldID fpRegIndex_ID            = 0;
  98 
  99 // part of the class sharing workaround
 100 static jfieldID classes_jsa_fd_ID        = 0;
 101 static jfieldID p_file_map_header_ID     = 0;
 102 
 103 // method ids
 104 
 105 static jmethodID getThreadForThreadId_ID = 0;
 106 static jmethodID createSenderFrame_ID    = 0;
 107 static jmethodID createLoadObject_ID     = 0;
 108 static jmethodID createClosestSymbol_ID  = 0;
 109 static jmethodID listAdd_ID              = 0;
 110 
 111 /*
 112  * Functions we need from libthread_db
 113  */
 114 typedef td_err_e
 115         (*p_td_init_t)(void);
 116 typedef td_err_e
 117         (*p_td_ta_new_t)(void *, td_thragent_t **);
 118 typedef td_err_e
 119         (*p_td_ta_delete_t)(td_thragent_t *);
 120 typedef td_err_e
 121         (*p_td_ta_thr_iter_t)(const td_thragent_t *, td_thr_iter_f *, void *,
 122                 td_thr_state_e, int, sigset_t *, unsigned);
 123 typedef td_err_e
 124         (*p_td_thr_get_info_t)(const td_thrhandle_t *, td_thrinfo_t *);
 125 typedef td_err_e
 126         (*p_td_ta_map_id2thr_t)(const td_thragent_t *, thread_t,  td_thrhandle_t *);
 127 typedef td_err_e
 128         (*p_td_thr_getgregs_t)(const td_thrhandle_t *, prgregset_t);
 129 
 130 static void
 131 clear_libthread_db_ptrs(JNIEnv* env, jobject this_obj) {
 132   // release libthread_db agent, if we had created
 133   p_td_ta_delete_t p_td_ta_delete = 0;
 134   p_td_ta_delete = (p_td_ta_delete_t) env->GetLongField(this_obj, p_td_ta_delete_ID);
 135 
 136   td_thragent_t *p_td_thragent_t = 0;
 137   p_td_thragent_t = (td_thragent_t*) env->GetLongField(this_obj, p_td_thragent_t_ID);
 138   if (p_td_thragent_t != 0 && p_td_ta_delete != 0) {
 139      p_td_ta_delete(p_td_thragent_t);
 140   }
 141 
 142   // dlclose libthread_db.so
 143   void* libthread_db_handle = (void*) env->GetLongField(this_obj, libthread_db_handle_ID);
 144   if (libthread_db_handle != 0) {
 145     dlclose(libthread_db_handle);
 146   }
 147 
 148   env->SetLongField(this_obj, libthread_db_handle_ID, (jlong)0);
 149   env->SetLongField(this_obj, p_td_init_ID, (jlong)0);
 150   env->SetLongField(this_obj, p_td_ta_new_ID, (jlong)0);
 151   env->SetLongField(this_obj, p_td_ta_delete_ID, (jlong)0);
 152   env->SetLongField(this_obj, p_td_ta_thr_iter_ID, (jlong)0);
 153   env->SetLongField(this_obj, p_td_thr_get_info_ID, (jlong)0);
 154   env->SetLongField(this_obj, p_td_ta_map_id2thr_ID, (jlong)0);
 155   env->SetLongField(this_obj, p_td_thr_getgregs_ID, (jlong)0);
 156 }
 157 
 158 
 159 static void detach_internal(JNIEnv* env, jobject this_obj) {
 160   // clear libthread_db stuff
 161   clear_libthread_db_ptrs(env, this_obj);
 162 
 163   // release ptr to ps_prochandle
 164   jlong p_ps_prochandle;
 165   p_ps_prochandle = env->GetLongField(this_obj, p_ps_prochandle_ID);
 166   if (p_ps_prochandle != 0L) {
 167     Prelease((struct ps_prochandle*) p_ps_prochandle, PRELEASE_CLEAR);
 168   }
 169 
 170   // part of the class sharing workaround
 171   int classes_jsa_fd = env->GetIntField(this_obj, classes_jsa_fd_ID);
 172   if (classes_jsa_fd != -1) {
 173     close(classes_jsa_fd);
 174     struct FileMapHeader* pheader = (struct FileMapHeader*) env->GetLongField(this_obj, p_file_map_header_ID);
 175     if (pheader != NULL) {
 176       free(pheader);
 177     }
 178   }
 179 }
 180 
 181 // Is it okay to ignore libthread_db failure? Set env var to ignore
 182 // libthread_db failure. You can still debug, but will miss threads
 183 // related functionality.
 184 static bool sa_ignore_threaddb = (getenv("SA_IGNORE_THREADDB") != 0);
 185 
 186 #define HANDLE_THREADDB_FAILURE(msg)          \
 187   if (sa_ignore_threaddb) {                   \
 188      printf("libsaproc WARNING: %s\n", msg);  \
 189      return;                                  \
 190   } else {                                    \
 191      THROW_NEW_DEBUGGER_EXCEPTION(msg);       \
 192   }
 193 
 194 #define HANDLE_THREADDB_FAILURE_(msg, ret)    \
 195   if (sa_ignore_threaddb) {                   \
 196      printf("libsaproc WARNING: %s\n", msg);  \
 197      return ret;                              \
 198   } else {                                    \
 199      THROW_NEW_DEBUGGER_EXCEPTION_(msg, ret); \
 200   }
 201 
 202 static const char * alt_root = NULL;
 203 static int alt_root_len = -1;
 204 
 205 #define SA_ALTROOT "SA_ALTROOT"
 206 
 207 static void init_alt_root() {
 208   if (alt_root_len == -1) {
 209     alt_root = getenv(SA_ALTROOT);
 210     if (alt_root)
 211       alt_root_len = strlen(alt_root);
 212     else
 213       alt_root_len = 0;
 214   }
 215 }
 216 
 217 // This function is a complete substitute for the open system call
 218 // since it's also used to override open calls from libproc to
 219 // implement as a pathmap style facility for the SA.  If libproc
 220 // starts using other interfaces then this might have to extended to
 221 // cover other calls.
 222 extern "C" int libsaproc_open(const char * name, int oflag, ...) {
 223   if (oflag == O_RDONLY) {
 224     init_alt_root();
 225 
 226     if (_libsaproc_debug) {
 227       printf("libsaproc DEBUG: libsaproc_open %s\n", name);
 228     }
 229 
 230     if (alt_root_len > 0) {
 231       int fd = -1;
 232       char alt_path[PATH_MAX+1];
 233 
 234       strcpy(alt_path, alt_root);
 235       strcat(alt_path, name);
 236       fd = open(alt_path, O_RDONLY);
 237       if (fd >= 0) {
 238         if (_libsaproc_debug) {
 239           printf("libsaproc DEBUG: libsaproc_open substituted %s\n", alt_path);
 240         }
 241         return fd;
 242       }
 243 
 244       if (strrchr(name, '/')) {
 245         strcpy(alt_path, alt_root);
 246         strcat(alt_path, strrchr(name, '/'));
 247         fd = open(alt_path, O_RDONLY);
 248         if (fd >= 0) {
 249           if (_libsaproc_debug) {
 250             printf("libsaproc DEBUG: libsaproc_open substituted %s\n", alt_path);
 251           }
 252           return fd;
 253         }
 254       }
 255     }
 256   }
 257 
 258   {
 259     mode_t mode;
 260     va_list ap;
 261     va_start(ap, oflag);
 262     mode = va_arg(ap, mode_t);
 263     va_end(ap);
 264 
 265     return open(name, oflag, mode);
 266   }
 267 }
 268 
 269 
 270 static void * pathmap_dlopen(const char * name, int mode) {
 271   init_alt_root();
 272 
 273   if (_libsaproc_debug) {
 274     printf("libsaproc DEBUG: pathmap_dlopen %s\n", name);
 275   }
 276 
 277   void * handle = NULL;
 278   if (alt_root_len > 0) {
 279     char alt_path[PATH_MAX+1];
 280     strcpy(alt_path, alt_root);
 281     strcat(alt_path, name);
 282     handle = dlopen(alt_path, mode);
 283     if (_libsaproc_debug && handle) {
 284       printf("libsaproc DEBUG: pathmap_dlopen substituted %s\n", alt_path);
 285     }
 286 
 287     if (handle == NULL && strrchr(name, '/')) {
 288       strcpy(alt_path, alt_root);
 289       strcat(alt_path, strrchr(name, '/'));
 290       handle = dlopen(alt_path, mode);
 291       if (_libsaproc_debug && handle) {
 292         printf("libsaproc DEBUG: pathmap_dlopen substituted %s\n", alt_path);
 293       }
 294     }
 295   }
 296   if (handle == NULL) {
 297     handle = dlopen(name, mode);
 298   }
 299   if (_libsaproc_debug) {
 300     printf("libsaproc DEBUG: pathmap_dlopen %s return 0x%lx\n", name, (unsigned long) handle);
 301   }
 302   return handle;
 303 }
 304 
 305 // libproc and libthread_db callback functions
 306 
 307 extern "C" {
 308 
 309 static int
 310 init_libthread_db_ptrs(void *cd, const prmap_t *pmp, const char *object_name) {
 311   Debugger* dbg = (Debugger*) cd;
 312   JNIEnv* env = dbg->env;
 313   jobject this_obj = dbg->this_obj;
 314   struct ps_prochandle* ph = (struct ps_prochandle*) env->GetLongField(this_obj, p_ps_prochandle_ID);
 315 
 316   char *s1 = 0, *s2 = 0;
 317   char libthread_db[PATH_MAX];
 318 
 319   if (strstr(object_name, "/libthread.so.") == NULL)
 320      return (0);
 321 
 322   /*
 323    * We found a libthread.
 324    * dlopen() the matching libthread_db and get the thread agent handle.
 325    */
 326   if (Pstatus(ph)->pr_dmodel == PR_MODEL_NATIVE) {
 327      (void) strcpy(libthread_db, object_name);
 328      s1 = (char*) strstr(object_name, ".so.");
 329      s2 = (char*) strstr(libthread_db, ".so.");
 330      (void) strcpy(s2, "_db");
 331      s2 += 3;
 332      (void) strcpy(s2, s1);
 333   } else {
 334 #ifdef _LP64
 335      /*
 336       * The victim process is 32-bit, we are 64-bit.
 337       * We have to find the 64-bit version of libthread_db
 338       * that matches the victim's 32-bit version of libthread.
 339       */
 340      (void) strcpy(libthread_db, object_name);
 341      s1 = (char*) strstr(object_name, "/libthread.so.");
 342      s2 = (char*) strstr(libthread_db, "/libthread.so.");
 343      (void) strcpy(s2, "/64");
 344      s2 += 3;
 345      (void) strcpy(s2, s1);
 346      s1 = (char*) strstr(s1, ".so.");
 347      s2 = (char*) strstr(s2, ".so.");
 348      (void) strcpy(s2, "_db");
 349      s2 += 3;
 350      (void) strcpy(s2, s1);
 351 #else
 352      return (0);
 353 #endif  /* _LP64 */
 354   }
 355 
 356   void* libthread_db_handle = 0;
 357   if ((libthread_db_handle = pathmap_dlopen(libthread_db, RTLD_LAZY|RTLD_LOCAL)) == NULL) {
 358      char errMsg[PATH_MAX + 256];
 359      sprintf(errMsg, "Can't load %s!", libthread_db);
 360      HANDLE_THREADDB_FAILURE_(errMsg, 0);
 361   }
 362   env->SetLongField(this_obj, libthread_db_handle_ID, (jlong)(uintptr_t)libthread_db_handle);
 363 
 364   void* tmpPtr = 0;
 365   tmpPtr = dlsym(libthread_db_handle, "td_init");
 366   if (tmpPtr == 0) {
 367      HANDLE_THREADDB_FAILURE_("dlsym failed on td_init!", 0);
 368   }
 369   env->SetLongField(this_obj, p_td_init_ID, (jlong)(uintptr_t) tmpPtr);
 370 
 371   tmpPtr =dlsym(libthread_db_handle, "td_ta_new");
 372   if (tmpPtr == 0) {
 373      HANDLE_THREADDB_FAILURE_("dlsym failed on td_ta_new!", 0);
 374   }
 375   env->SetLongField(this_obj, p_td_ta_new_ID, (jlong)(uintptr_t) tmpPtr);
 376 
 377   tmpPtr = dlsym(libthread_db_handle, "td_ta_delete");
 378   if (tmpPtr == 0) {
 379      HANDLE_THREADDB_FAILURE_("dlsym failed on td_ta_delete!", 0);
 380   }
 381   env->SetLongField(this_obj, p_td_ta_delete_ID, (jlong)(uintptr_t) tmpPtr);
 382 
 383   tmpPtr = dlsym(libthread_db_handle, "td_ta_thr_iter");
 384   if (tmpPtr == 0) {
 385      HANDLE_THREADDB_FAILURE_("dlsym failed on td_ta_thr_iter!", 0);
 386   }
 387   env->SetLongField(this_obj, p_td_ta_thr_iter_ID, (jlong)(uintptr_t) tmpPtr);
 388 
 389   tmpPtr = dlsym(libthread_db_handle, "td_thr_get_info");
 390   if (tmpPtr == 0) {
 391      HANDLE_THREADDB_FAILURE_("dlsym failed on td_thr_get_info!", 0);
 392   }
 393   env->SetLongField(this_obj, p_td_thr_get_info_ID, (jlong)(uintptr_t) tmpPtr);
 394 
 395   tmpPtr = dlsym(libthread_db_handle, "td_ta_map_id2thr");
 396   if (tmpPtr == 0) {
 397      HANDLE_THREADDB_FAILURE_("dlsym failed on td_ta_map_id2thr!", 0);
 398   }
 399   env->SetLongField(this_obj, p_td_ta_map_id2thr_ID, (jlong)(uintptr_t) tmpPtr);
 400 
 401   tmpPtr = dlsym(libthread_db_handle, "td_thr_getgregs");
 402   if (tmpPtr == 0) {
 403      HANDLE_THREADDB_FAILURE_("dlsym failed on td_thr_getgregs!", 0);
 404   }
 405   env->SetLongField(this_obj, p_td_thr_getgregs_ID, (jlong)(uintptr_t) tmpPtr);
 406 
 407   return 1;
 408 }
 409 
 410 static int
 411 fill_thread_list(const td_thrhandle_t *p_td_thragent_t, void* cd) {
 412   DebuggerWithObject* dbgo = (DebuggerWithObject*) cd;
 413   JNIEnv* env = dbgo->env;
 414   jobject this_obj = dbgo->this_obj;
 415   jobject list = dbgo->obj;
 416 
 417   td_thrinfo_t thrinfo;
 418   p_td_thr_get_info_t p_td_thr_get_info = (p_td_thr_get_info_t) env->GetLongField(this_obj, p_td_thr_get_info_ID);
 419 
 420   if (p_td_thr_get_info(p_td_thragent_t, &thrinfo) != TD_OK)
 421     return (0);
 422 
 423   jobject threadProxy = env->CallObjectMethod(this_obj, getThreadForThreadId_ID, (jlong)(uintptr_t) thrinfo.ti_tid);
 424   CHECK_EXCEPTION_(1);
 425   env->CallBooleanMethod(list, listAdd_ID, threadProxy);
 426   CHECK_EXCEPTION_(1);
 427   return 0;
 428 }
 429 
 430 static int
 431 fill_load_object_list(void *cd, const prmap_t* pmp, const char* obj_name) {
 432 
 433   if (obj_name) {
 434      DebuggerWithObject* dbgo = (DebuggerWithObject*) cd;
 435      JNIEnv* env = dbgo->env;
 436      jobject this_obj = dbgo->this_obj;
 437      jobject list = dbgo->obj;
 438 
 439      jstring objectName = env->NewStringUTF(obj_name);
 440      CHECK_EXCEPTION_(1);
 441 
 442      jlong mapSize = (jlong) pmp->pr_size;
 443      jobject sharedObject = env->CallObjectMethod(this_obj, createLoadObject_ID,
 444                                   objectName, mapSize, (jlong)(uintptr_t)pmp->pr_vaddr);
 445      CHECK_EXCEPTION_(1);
 446      env->CallBooleanMethod(list, listAdd_ID, sharedObject);
 447      CHECK_EXCEPTION_(1);
 448   }
 449 
 450   return 0;
 451 }
 452 
 453 static int
 454 fill_cframe_list(void *cd, const prgregset_t regs, uint_t argc, const long *argv) {
 455   DebuggerWith2Objects* dbgo2 = (DebuggerWith2Objects*) cd;
 456   JNIEnv* env = dbgo2->env;
 457   jobject this_obj = dbgo2->this_obj;
 458   jobject curFrame = dbgo2->obj2;
 459 
 460   jint pcRegIndex = env->GetIntField(this_obj, pcRegIndex_ID);
 461   jint fpRegIndex = env->GetIntField(this_obj, fpRegIndex_ID);
 462 
 463   jlong pc = (jlong) (uintptr_t) regs[pcRegIndex];
 464   jlong fp = (jlong) (uintptr_t) regs[fpRegIndex];
 465 
 466   dbgo2->obj2 = env->CallObjectMethod(this_obj, createSenderFrame_ID,
 467                                     curFrame, pc, fp);
 468   CHECK_EXCEPTION_(1);
 469   if (dbgo2->obj == 0) {
 470      dbgo2->obj = dbgo2->obj2;
 471   }
 472   return 0;
 473 }
 474 
 475 // part of the class sharing workaround
 476 
 477 // FIXME: !!HACK ALERT!!
 478 
 479 // The format of sharing achive file header is needed to read shared heap
 480 // file mappings. For now, I am hard coding portion of FileMapHeader here.
 481 // Refer to filemap.hpp.
 482 
 483 // FileMapHeader describes the shared space data in the file to be
 484 // mapped.  This structure gets written to a file.  It is not a class, so
 485 // that the compilers don't add any compiler-private data to it.
 486 
 487 const int NUM_SHARED_MAPS = 4;
 488 
 489 // Refer to FileMapInfo::_current_version in filemap.hpp
 490 const int CURRENT_ARCHIVE_VERSION = 1;
 491 
 492 struct FileMapHeader {
 493  int   _magic;              // identify file type.
 494  int   _version;            // (from enum, above.)
 495  size_t _alignment;         // how shared archive should be aligned
 496 
 497 
 498  struct space_info {
 499    int    _file_offset;     // sizeof(this) rounded to vm page size
 500    char*  _base;            // copy-on-write base address
 501    size_t _capacity;        // for validity checking
 502    size_t _used;            // for setting space top on read
 503 
 504    bool   _read_only;       // read only space?
 505    bool   _allow_exec;      // executable code in space?
 506 
 507  } _space[NUM_SHARED_MAPS];
 508 
 509  // Ignore the rest of the FileMapHeader. We don't need those fields here.
 510 };
 511 
 512 static bool
 513 read_jboolean(struct ps_prochandle* ph, psaddr_t addr, jboolean* pvalue) {
 514   jboolean i;
 515   if (ps_pread(ph, addr, &i, sizeof(i)) == PS_OK) {
 516     *pvalue = i;
 517     return true;
 518   } else {
 519     return false;
 520   }
 521 }
 522 
 523 static bool
 524 read_pointer(struct ps_prochandle* ph, psaddr_t addr, uintptr_t* pvalue) {
 525   uintptr_t uip;
 526   if (ps_pread(ph, addr, &uip, sizeof(uip)) == PS_OK) {
 527     *pvalue = uip;
 528     return true;
 529   } else {
 530     return false;
 531   }
 532 }
 533 
 534 static bool
 535 read_string(struct ps_prochandle* ph, psaddr_t addr, char* buf, size_t size) {
 536   char ch = ' ';
 537   size_t i = 0;
 538 
 539   while (ch != '\0') {
 540     if (ps_pread(ph, addr, &ch, sizeof(ch)) != PS_OK)
 541       return false;
 542 
 543     if (i < size - 1) {
 544       buf[i] = ch;
 545     } else { // smaller buffer
 546       return false;
 547     }
 548 
 549     i++; addr++;
 550   }
 551 
 552   buf[i] = '\0';
 553   return true;
 554 }
 555 
 556 #define USE_SHARED_SPACES_SYM   "UseSharedSpaces"
 557 // mangled symbol name for Arguments::SharedArchivePath
 558 #define SHARED_ARCHIVE_PATH_SYM "__1cJArgumentsRSharedArchivePath_"
 559 
 560 static int
 561 init_classsharing_workaround(void *cd, const prmap_t* pmap, const char* obj_name) {
 562   Debugger* dbg = (Debugger*) cd;
 563   JNIEnv*   env = dbg->env;
 564   jobject this_obj = dbg->this_obj;
 565   const char* jvm_name = 0;
 566   if ((jvm_name = strstr(obj_name, "libjvm.so")) != NULL) {
 567     jvm_name = obj_name;
 568   } else {
 569     return 0;
 570   }
 571 
 572   struct ps_prochandle* ph = (struct ps_prochandle*) env->GetLongField(this_obj, p_ps_prochandle_ID);
 573 
 574   // initialize classes.jsa file descriptor field.
 575   dbg->env->SetIntField(this_obj, classes_jsa_fd_ID, -1);
 576 
 577   // check whether class sharing is on by reading variable "UseSharedSpaces"
 578   psaddr_t useSharedSpacesAddr = 0;
 579   ps_pglobal_lookup(ph, jvm_name, USE_SHARED_SPACES_SYM, &useSharedSpacesAddr);
 580   if (useSharedSpacesAddr == 0) {
 581     THROW_NEW_DEBUGGER_EXCEPTION_("can't find 'UseSharedSpaces' flag\n", 1);
 582   }
 583 
 584   // read the value of the flag "UseSharedSpaces"
 585   // Since hotspot types are not available to build this library. So
 586   // equivalent type "jboolean" is used to read the value of "UseSharedSpaces"
 587   // which is same as hotspot type "bool".
 588   jboolean value = 0;
 589   if (read_jboolean(ph, useSharedSpacesAddr, &value) != true) {
 590     THROW_NEW_DEBUGGER_EXCEPTION_("can't read 'UseSharedSpaces' flag", 1);
 591   } else if ((int)value == 0) {
 592     print_debug("UseSharedSpaces is false, assuming -Xshare:off!\n");
 593     return 1;
 594   }
 595 
 596   char classes_jsa[PATH_MAX];
 597   psaddr_t sharedArchivePathAddrAddr = 0;
 598   ps_pglobal_lookup(ph, jvm_name, SHARED_ARCHIVE_PATH_SYM, &sharedArchivePathAddrAddr);
 599   if (sharedArchivePathAddrAddr == 0) {
 600     print_debug("can't find symbol 'Arguments::SharedArchivePath'\n");
 601     THROW_NEW_DEBUGGER_EXCEPTION_("can't get shared archive path from debuggee", 1);
 602   }
 603 
 604   uintptr_t sharedArchivePathAddr = 0;
 605   if (read_pointer(ph, sharedArchivePathAddrAddr, &sharedArchivePathAddr) != true) {
 606     print_debug("can't find read pointer 'Arguments::SharedArchivePath'\n");
 607     THROW_NEW_DEBUGGER_EXCEPTION_("can't get shared archive path from debuggee", 1);
 608   }
 609 
 610   if (read_string(ph, (psaddr_t)sharedArchivePathAddr, classes_jsa, sizeof(classes_jsa)) != true) {
 611     print_debug("can't find read 'Arguments::SharedArchivePath' value\n");
 612     THROW_NEW_DEBUGGER_EXCEPTION_("can't get shared archive path from debuggee", 1);
 613   }
 614 
 615   print_debug("looking for %s\n", classes_jsa);
 616 
 617   // open the classes.jsa
 618   int fd = libsaproc_open(classes_jsa, O_RDONLY);
 619   if (fd < 0) {
 620     char errMsg[ERR_MSG_SIZE];
 621     sprintf(errMsg, "can't open shared archive file %s", classes_jsa);
 622     THROW_NEW_DEBUGGER_EXCEPTION_(errMsg, 1);
 623   } else {
 624     print_debug("opened shared archive file %s\n", classes_jsa);
 625   }
 626 
 627   // parse classes.jsa
 628   struct FileMapHeader* pheader = (struct FileMapHeader*) malloc(sizeof(struct FileMapHeader));
 629   if (pheader == NULL) {
 630     close(fd);
 631     THROW_NEW_DEBUGGER_EXCEPTION_("can't allocate memory for shared file map header", 1);
 632   }
 633 
 634   memset(pheader, 0, sizeof(struct FileMapHeader));
 635   // read FileMapHeader
 636   size_t n = read(fd, pheader, sizeof(struct FileMapHeader));
 637   if (n != sizeof(struct FileMapHeader)) {
 638     char errMsg[ERR_MSG_SIZE];
 639     sprintf(errMsg, "unable to read shared archive file map header from %s", classes_jsa);
 640     close(fd);
 641     free(pheader);
 642     THROW_NEW_DEBUGGER_EXCEPTION_(errMsg, 1);
 643   }
 644 
 645   // check file magic
 646   if (pheader->_magic != 0xf00baba2) {
 647     char errMsg[ERR_MSG_SIZE];
 648     sprintf(errMsg, "%s has bad shared archive magic 0x%x, expecting 0xf00baba2",
 649                    classes_jsa, pheader->_magic);
 650     close(fd);
 651     free(pheader);
 652     THROW_NEW_DEBUGGER_EXCEPTION_(errMsg, 1);
 653   }
 654 
 655   // check version
 656   if (pheader->_version != CURRENT_ARCHIVE_VERSION) {
 657     char errMsg[ERR_MSG_SIZE];
 658     sprintf(errMsg, "%s has wrong shared archive version %d, expecting %d",
 659                    classes_jsa, pheader->_version, CURRENT_ARCHIVE_VERSION);
 660     close(fd);
 661     free(pheader);
 662     THROW_NEW_DEBUGGER_EXCEPTION_(errMsg, 1);
 663   }
 664 
 665   if (_libsaproc_debug) {
 666     for (int m = 0; m < NUM_SHARED_MAPS; m++) {
 667        print_debug("shared file offset %d mapped at 0x%lx, size = %ld, read only? = %d\n",
 668           pheader->_space[m]._file_offset, pheader->_space[m]._base,
 669           pheader->_space[m]._used, pheader->_space[m]._read_only);
 670     }
 671   }
 672 
 673   // FIXME: For now, omitting other checks such as VM version etc.
 674 
 675   // store class archive file fd and map header in debugger object fields
 676   dbg->env->SetIntField(this_obj, classes_jsa_fd_ID, fd);
 677   dbg->env->SetLongField(this_obj, p_file_map_header_ID, (jlong)(uintptr_t) pheader);
 678   return 1;
 679 }
 680 
 681 } // extern "C"
 682 
 683 // error messages for proc_arg_grab failure codes. The messages are
 684 // modified versions of comments against corresponding #defines in
 685 // libproc.h.
 686 static const char* proc_arg_grab_errmsgs[] = {
 687                       "",
 688  /* G_NOPROC */       "No such process",
 689  /* G_NOCORE */       "No such core file",
 690  /* G_NOPROCORCORE */ "No such process or core",
 691  /* G_NOEXEC */       "Cannot locate executable file",
 692  /* G_ZOMB   */       "Zombie processs",
 693  /* G_PERM   */       "No permission to attach",
 694  /* G_BUSY   */       "Another process has already attached",
 695  /* G_SYS    */       "System process - can not attach",
 696  /* G_SELF   */       "Process is self - can't debug myself!",
 697  /* G_INTR   */       "Interrupt received while grabbing",
 698  /* G_LP64   */       "debuggee is 64 bit, use java -d64 for debugger",
 699  /* G_FORMAT */       "File is not an ELF format core file - corrupted core?",
 700  /* G_ELF    */       "Libelf error while parsing an ELF file",
 701  /* G_NOTE   */       "Required PT_NOTE Phdr not present - corrupted core?",
 702 };
 703 
 704 static void attach_internal(JNIEnv* env, jobject this_obj, jstring cmdLine, jboolean isProcess) {
 705   jboolean isCopy;
 706   int gcode;
 707   const char* cmdLine_cstr = env->GetStringUTFChars(cmdLine, &isCopy);
 708   CHECK_EXCEPTION;
 709 
 710   // some older versions of libproc.so crash when trying to attach 32 bit
 711   // debugger to 64 bit core file. check and throw error.
 712 #ifndef _LP64
 713   atoi(cmdLine_cstr);
 714   if (errno) {
 715      // core file
 716      int core_fd;
 717      if ((core_fd = open64(cmdLine_cstr, O_RDONLY)) >= 0) {
 718         Elf32_Ehdr e32;
 719         if (pread64(core_fd, &e32, sizeof (e32), 0) == sizeof (e32) &&
 720             memcmp(&e32.e_ident[EI_MAG0], ELFMAG, SELFMAG) == 0 &&
 721             e32.e_type == ET_CORE && e32.e_ident[EI_CLASS] == ELFCLASS64) {
 722               close(core_fd);
 723               THROW_NEW_DEBUGGER_EXCEPTION("debuggee is 64 bit, use java -d64 for debugger");
 724         }
 725         close(core_fd);
 726      }
 727      // all other conditions are handled by libproc.so.
 728   }
 729 #endif
 730 
 731   // connect to process/core
 732   ps_prochandle_t* ph = proc_arg_grab(cmdLine_cstr, (isProcess? PR_ARG_PIDS : PR_ARG_CORES), PGRAB_FORCE, &gcode, NULL);
 733 
 734   env->ReleaseStringUTFChars(cmdLine, cmdLine_cstr);
 735   if (! ph) {
 736      if (gcode > 0 && gcode < sizeof(proc_arg_grab_errmsgs)/sizeof(const char*)) {
 737         char errMsg[ERR_MSG_SIZE];
 738         sprintf(errMsg, "Attach failed : %s", proc_arg_grab_errmsgs[gcode]);
 739         THROW_NEW_DEBUGGER_EXCEPTION(errMsg);
 740     } else {
 741         if (_libsaproc_debug && gcode == G_STRANGE) {
 742            perror("libsaproc DEBUG: ");
 743         }
 744         if (isProcess) {
 745            THROW_NEW_DEBUGGER_EXCEPTION("Not able to attach to process!");
 746         } else {
 747            THROW_NEW_DEBUGGER_EXCEPTION("Not able to attach to core file!");
 748         }
 749      }
 750   }
 751 
 752   // even though libproc.so supports 64 bit debugger and 32 bit debuggee, we don't
 753   // support such cross-bit-debugging. check for that combination and throw error.
 754 #ifdef _LP64
 755   int data_model;
 756   if (ps_pdmodel(ph, &data_model) != PS_OK) {
 757      Prelease(ph, PRELEASE_CLEAR);
 758      THROW_NEW_DEBUGGER_EXCEPTION("can't determine debuggee data model (ILP32? or LP64?)");
 759   }
 760   if (data_model == PR_MODEL_ILP32) {
 761      Prelease(ph, PRELEASE_CLEAR);
 762      THROW_NEW_DEBUGGER_EXCEPTION("debuggee is 32 bit, use 32 bit java for debugger");
 763   }
 764 #endif
 765 
 766   env->SetLongField(this_obj, p_ps_prochandle_ID, (jlong)(uintptr_t)ph);
 767 
 768   Debugger dbg;
 769   dbg.env = env;
 770   dbg.this_obj = this_obj;
 771   jthrowable exception = 0;
 772   if (! isProcess) {
 773     /*
 774      * With class sharing, shared perm. gen heap is allocated in with MAP_SHARED|PROT_READ.
 775      * These pages are mapped from the file "classes.jsa". MAP_SHARED pages are not dumped
 776      * in Solaris core.To read shared heap pages, we have to read classes.jsa file.
 777      */
 778     Pobject_iter(ph, init_classsharing_workaround, &dbg);
 779     exception = env->ExceptionOccurred();
 780     if (exception) {
 781       env->ExceptionClear();
 782       detach_internal(env, this_obj);
 783       env->Throw(exception);
 784       return;
 785     }
 786   }
 787 
 788   /*
 789    * Iterate over the process mappings looking
 790    * for libthread and then dlopen the appropriate
 791    * libthread_db and get function pointers.
 792    */
 793   Pobject_iter(ph, init_libthread_db_ptrs, &dbg);
 794   exception = env->ExceptionOccurred();
 795   if (exception) {
 796     env->ExceptionClear();
 797     if (!sa_ignore_threaddb) {
 798       detach_internal(env, this_obj);
 799       env->Throw(exception);
 800     }
 801     return;
 802   }
 803 
 804   // init libthread_db and create thread_db agent
 805   p_td_init_t p_td_init = (p_td_init_t) env->GetLongField(this_obj, p_td_init_ID);
 806   if (p_td_init == 0) {
 807     if (!sa_ignore_threaddb) {
 808       detach_internal(env, this_obj);
 809     }
 810     HANDLE_THREADDB_FAILURE("Did not find libthread in target process/core!");
 811   }
 812 
 813   if (p_td_init() != TD_OK) {
 814     if (!sa_ignore_threaddb) {
 815       detach_internal(env, this_obj);
 816     }
 817     HANDLE_THREADDB_FAILURE("Can't initialize thread_db!");
 818   }
 819 
 820   p_td_ta_new_t p_td_ta_new = (p_td_ta_new_t) env->GetLongField(this_obj, p_td_ta_new_ID);
 821 
 822   td_thragent_t *p_td_thragent_t = 0;
 823   if (p_td_ta_new(ph, &p_td_thragent_t) != TD_OK) {
 824     if (!sa_ignore_threaddb) {
 825       detach_internal(env, this_obj);
 826     }
 827     HANDLE_THREADDB_FAILURE("Can't create thread_db agent!");
 828   }
 829   env->SetLongField(this_obj, p_td_thragent_t_ID, (jlong)(uintptr_t) p_td_thragent_t);
 830 
 831 }
 832 
 833 /*
 834  * Class:     sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal
 835  * Method:    attach0
 836  * Signature: (Ljava/lang/String;)V
 837  * Description: process detach
 838  */
 839 JNIEXPORT void JNICALL Java_sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal_attach0__Ljava_lang_String_2
 840   (JNIEnv *env, jobject this_obj, jstring pid) {
 841   attach_internal(env, this_obj, pid, JNI_TRUE);
 842 }
 843 
 844 /*
 845  * Class:     sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal
 846  * Method:    attach0
 847  * Signature: (Ljava/lang/String;Ljava/lang/String;)V
 848  * Description: core file detach
 849  */
 850 JNIEXPORT void JNICALL Java_sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal_attach0__Ljava_lang_String_2Ljava_lang_String_2
 851   (JNIEnv *env, jobject this_obj, jstring executable, jstring corefile) {
 852   // ignore executable file name, libproc.so can detect a.out name anyway.
 853   attach_internal(env, this_obj, corefile, JNI_FALSE);
 854 }
 855 
 856 
 857 /*
 858  * Class:       sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal
 859  * Method:      detach0
 860  * Signature:   ()V
 861  * Description: process/core file detach
 862  */
 863 JNIEXPORT void JNICALL Java_sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal_detach0
 864   (JNIEnv *env, jobject this_obj) {
 865   detach_internal(env, this_obj);
 866 }
 867 
 868 /*
 869  * Class:       sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal
 870  * Method:      getRemoteProcessAddressSize0
 871  * Signature:   ()I
 872  * Description: get process/core address size
 873  */
 874 JNIEXPORT jint JNICALL Java_sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal_getRemoteProcessAddressSize0
 875   (JNIEnv *env, jobject this_obj) {
 876   jlong p_ps_prochandle;
 877   p_ps_prochandle = env->GetLongField(this_obj, p_ps_prochandle_ID);
 878   int data_model = PR_MODEL_ILP32;
 879   ps_pdmodel((struct ps_prochandle*) p_ps_prochandle, &data_model);
 880   print_debug("debuggee is %d bit\n", data_model == PR_MODEL_ILP32? 32 : 64);
 881   return (jint) data_model == PR_MODEL_ILP32? 32 : 64;
 882 }
 883 
 884 /*
 885  * Class:       sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal
 886  * Method:      getPageSize0
 887  * Signature:   ()I
 888  * Description: get process/core page size
 889  */
 890 JNIEXPORT jint JNICALL Java_sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal_getPageSize0
 891   (JNIEnv *env, jobject this_obj) {
 892 
 893 /*
 894   We are not yet attached to a java process or core file. getPageSize is called from
 895   the constructor of ProcDebuggerLocal. The following won't work!
 896 
 897     jlong p_ps_prochandle;
 898     p_ps_prochandle = env->GetLongField(this_obj, p_ps_prochandle_ID);
 899     CHECK_EXCEPTION_(-1);
 900     struct ps_prochandle* prochandle = (struct ps_prochandle*) p_ps_prochandle;
 901     return (Pstate(prochandle) == PS_DEAD) ? Pgetauxval(prochandle, AT_PAGESZ)
 902                                            : getpagesize();
 903 
 904   So even though core may have been generated with a different page size settings, for now
 905   call getpagesize.
 906 */
 907 
 908   return getpagesize();
 909 }
 910 
 911 /*
 912  * Class:       sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal
 913  * Method:      getThreadIntegerRegisterSet0
 914  * Signature:   (J)[J
 915  * Description: get gregset for a given thread specified by thread id
 916  */
 917 JNIEXPORT jlongArray JNICALL Java_sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal_getThreadIntegerRegisterSet0
 918   (JNIEnv *env, jobject this_obj, jlong tid) {
 919   // map the thread id to thread handle
 920   p_td_ta_map_id2thr_t p_td_ta_map_id2thr = (p_td_ta_map_id2thr_t) env->GetLongField(this_obj, p_td_ta_map_id2thr_ID);
 921 
 922   td_thragent_t* p_td_thragent_t = (td_thragent_t*) env->GetLongField(this_obj, p_td_thragent_t_ID);
 923   if (p_td_thragent_t == 0) {
 924      return 0;
 925   }
 926 
 927   td_thrhandle_t thr_handle;
 928   if (p_td_ta_map_id2thr(p_td_thragent_t, (thread_t) tid, &thr_handle) != TD_OK) {
 929      THROW_NEW_DEBUGGER_EXCEPTION_("can't map thread id to thread handle!", 0);
 930   }
 931 
 932   p_td_thr_getgregs_t p_td_thr_getgregs = (p_td_thr_getgregs_t) env->GetLongField(this_obj, p_td_thr_getgregs_ID);
 933   prgregset_t gregs;
 934   p_td_thr_getgregs(&thr_handle, gregs);
 935 
 936   jlongArray res = env->NewLongArray(NPRGREG);
 937   CHECK_EXCEPTION_(0);
 938   jboolean isCopy;
 939   jlong* ptr = env->GetLongArrayElements(res, &isCopy);
 940   for (int i = 0; i < NPRGREG; i++) {
 941     ptr[i] = (jlong) (uintptr_t) gregs[i];
 942   }
 943   env->ReleaseLongArrayElements(res, ptr, JNI_COMMIT);
 944   return res;
 945 }
 946 
 947 /*
 948  * Class:       sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal
 949  * Method:      fillThreadList0
 950  * Signature:   (Ljava/util/List;)V
 951  * Description: fills thread list of the debuggee process/core
 952  */
 953 JNIEXPORT void JNICALL Java_sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal_fillThreadList0
 954   (JNIEnv *env, jobject this_obj, jobject list) {
 955 
 956   td_thragent_t* p_td_thragent_t = (td_thragent_t*) env->GetLongField(this_obj, p_td_thragent_t_ID);
 957   if (p_td_thragent_t == 0) {
 958      return;
 959   }
 960 
 961   p_td_ta_thr_iter_t p_td_ta_thr_iter = (p_td_ta_thr_iter_t) env->GetLongField(this_obj, p_td_ta_thr_iter_ID);
 962 
 963   DebuggerWithObject dbgo;
 964   dbgo.env = env;
 965   dbgo.this_obj = this_obj;
 966   dbgo.obj = list;
 967 
 968   p_td_ta_thr_iter(p_td_thragent_t, fill_thread_list, &dbgo,
 969                    TD_THR_ANY_STATE, TD_THR_LOWEST_PRIORITY, TD_SIGNO_MASK, TD_THR_ANY_USER_FLAGS);
 970 }
 971 
 972 /*
 973  * Class:       sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal
 974  * Method:      fillCFrameList0
 975  * Signature:   ([J)Lsun/jvm/hotspot/debugger/proc/ProcCFrame;
 976  * Description: fills CFrame list for a given thread
 977  */
 978 JNIEXPORT jobject JNICALL Java_sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal_fillCFrameList0
 979   (JNIEnv *env, jobject this_obj, jlongArray regsArray) {
 980   jlong p_ps_prochandle = env->GetLongField(this_obj, p_ps_prochandle_ID);
 981 
 982   DebuggerWith2Objects dbgo2;
 983   dbgo2.env  = env;
 984   dbgo2.this_obj = this_obj;
 985   dbgo2.obj  = NULL;
 986   dbgo2.obj2 = NULL;
 987 
 988   jboolean isCopy;
 989   jlong* ptr = env->GetLongArrayElements(regsArray, &isCopy);
 990   CHECK_EXCEPTION_(0);
 991 
 992   prgregset_t gregs;
 993   for (int i = 0; i < NPRGREG; i++) {
 994      gregs[i] = (uintptr_t) ptr[i];
 995   }
 996 
 997   env->ReleaseLongArrayElements(regsArray, ptr, JNI_ABORT);
 998   CHECK_EXCEPTION_(0);
 999 
1000   Pstack_iter((struct ps_prochandle*) p_ps_prochandle, gregs,
1001               fill_cframe_list, &dbgo2);
1002   return dbgo2.obj;
1003 }
1004 
1005 /*
1006  * Class:       sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal
1007  * Method:      fillLoadObjectList0
1008  * Signature:   (Ljava/util/List;)V
1009  * Description: fills shared objects of the debuggee process/core
1010  */
1011 JNIEXPORT void JNICALL Java_sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal_fillLoadObjectList0
1012   (JNIEnv *env, jobject this_obj, jobject list) {
1013   DebuggerWithObject dbgo;
1014   dbgo.env = env;
1015   dbgo.this_obj = this_obj;
1016   dbgo.obj = list;
1017 
1018   jlong p_ps_prochandle = env->GetLongField(this_obj, p_ps_prochandle_ID);
1019   Pobject_iter((struct ps_prochandle*) p_ps_prochandle, fill_load_object_list, &dbgo);
1020 }
1021 
1022 /*
1023  * Class:       sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal
1024  * Method:      readBytesFromProcess0
1025  * Signature:   (JJ)[B
1026  * Description: read bytes from debuggee process/core
1027  */
1028 JNIEXPORT jbyteArray JNICALL Java_sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal_readBytesFromProcess0
1029   (JNIEnv *env, jobject this_obj, jlong address, jlong numBytes) {
1030 
1031   jbyteArray array = env->NewByteArray(numBytes);
1032   CHECK_EXCEPTION_(0);
1033   jboolean isCopy;
1034   jbyte* bufPtr = env->GetByteArrayElements(array, &isCopy);
1035   CHECK_EXCEPTION_(0);
1036 
1037   jlong p_ps_prochandle = env->GetLongField(this_obj, p_ps_prochandle_ID);
1038   ps_err_e ret = ps_pread((struct ps_prochandle*) p_ps_prochandle,
1039                        (psaddr_t)address, bufPtr, (size_t)numBytes);
1040 
1041   if (ret != PS_OK) {
1042     // part of the class sharing workaround. try shared heap area
1043     int classes_jsa_fd = env->GetIntField(this_obj, classes_jsa_fd_ID);
1044     if (classes_jsa_fd != -1 && address != (jlong)0) {
1045       print_debug("read failed at 0x%lx, attempting shared heap area\n", (long) address);
1046 
1047       struct FileMapHeader* pheader = (struct FileMapHeader*) env->GetLongField(this_obj, p_file_map_header_ID);
1048       // walk through the shared mappings -- we just have 4 of them.
1049       // so, linear walking is okay.
1050       for (int m = 0; m < NUM_SHARED_MAPS; m++) {
1051 
1052         // We can skip the non-read-only maps. These are mapped as MAP_PRIVATE
1053         // and hence will be read by libproc. Besides, the file copy may be
1054         // stale because the process might have modified those pages.
1055         if (pheader->_space[m]._read_only) {
1056           jlong baseAddress = (jlong) (uintptr_t) pheader->_space[m]._base;
1057           size_t usedSize = pheader->_space[m]._used;
1058           if (address >= baseAddress && address < (baseAddress + usedSize)) {
1059             // the given address falls in this shared heap area
1060             print_debug("found shared map at 0x%lx\n", (long) baseAddress);
1061 
1062 
1063             // If more data is asked than actually mapped from file, we need to zero fill
1064             // till the end-of-page boundary. But, java array new does that for us. we just
1065             // need to read as much as data available.
1066 
1067 #define MIN2(x, y) (((x) < (y))? (x) : (y))
1068 
1069             jlong diff = address - baseAddress;
1070             jlong bytesToRead = MIN2(numBytes, usedSize - diff);
1071             off_t offset = pheader->_space[m]._file_offset  + off_t(diff);
1072             ssize_t bytesRead = pread(classes_jsa_fd, bufPtr, bytesToRead, offset);
1073             if (bytesRead != bytesToRead) {
1074               env->ReleaseByteArrayElements(array, bufPtr, JNI_ABORT);
1075               print_debug("shared map read failed\n");
1076               return jbyteArray(0);
1077             } else {
1078               print_debug("shared map read succeeded\n");
1079               env->ReleaseByteArrayElements(array, bufPtr, 0);
1080               return array;
1081             }
1082           } // is in current map
1083         } // is read only map
1084       } // for shared maps
1085     } // classes_jsa_fd != -1
1086     env->ReleaseByteArrayElements(array, bufPtr, JNI_ABORT);
1087     return jbyteArray(0);
1088   } else {
1089     env->ReleaseByteArrayElements(array, bufPtr, 0);
1090     return array;
1091   }
1092 }
1093 
1094 /*
1095  * Class:       sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal
1096  * Method:      writeBytesToProcess0
1097  * Signature:   (JJ[B)V
1098  * Description: write bytes into debugger process
1099  */
1100 JNIEXPORT void JNICALL Java_sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal_writeBytesToProcess0
1101   (JNIEnv *env, jobject this_obj, jlong address, jlong numBytes, jbyteArray data) {
1102   jlong p_ps_prochandle = env->GetLongField(this_obj, p_ps_prochandle_ID);
1103   jboolean isCopy;
1104   jbyte* ptr = env->GetByteArrayElements(data, &isCopy);
1105   CHECK_EXCEPTION;
1106 
1107   if (ps_pwrite((struct ps_prochandle*) p_ps_prochandle, address, ptr, numBytes) != PS_OK) {
1108      env->ReleaseByteArrayElements(data, ptr, JNI_ABORT);
1109      THROW_NEW_DEBUGGER_EXCEPTION("Process write failed!");
1110   }
1111 
1112   env->ReleaseByteArrayElements(data, ptr, JNI_ABORT);
1113 }
1114 
1115 /*
1116  * Class:     sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal
1117  * Method:    suspend0
1118  * Signature: ()V
1119  */
1120 JNIEXPORT void JNICALL Java_sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal_suspend0
1121   (JNIEnv *env, jobject this_obj) {
1122   jlong p_ps_prochandle = env->GetLongField(this_obj, p_ps_prochandle_ID);
1123   // for now don't check return value. revisit this again.
1124   Pstop((struct ps_prochandle*) p_ps_prochandle, 1000);
1125 }
1126 
1127 /*
1128  * Class:     sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal
1129  * Method:    resume0
1130  * Signature: ()V
1131  */
1132 JNIEXPORT void JNICALL Java_sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal_resume0
1133   (JNIEnv *env, jobject this_obj) {
1134   jlong p_ps_prochandle = env->GetLongField(this_obj, p_ps_prochandle_ID);
1135   // for now don't check return value. revisit this again.
1136   Psetrun((struct ps_prochandle*) p_ps_prochandle, 0, PRCFAULT|PRSTOP);
1137 }
1138 
1139 /*
1140   * Class:       sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal
1141   * Method:      lookupByName0
1142   * Signature:   (Ljava/lang/String;Ljava/lang/String;)J
1143   * Description: symbol lookup by name
1144 */
1145 JNIEXPORT jlong JNICALL Java_sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal_lookupByName0
1146    (JNIEnv *env, jobject this_obj, jstring objectName, jstring symbolName) {
1147    jlong p_ps_prochandle;
1148    p_ps_prochandle = env->GetLongField(this_obj, p_ps_prochandle_ID);
1149 
1150    jboolean isCopy;
1151    const char* objectName_cstr = NULL;
1152    if (objectName != NULL) {
1153      objectName_cstr = env->GetStringUTFChars(objectName, &isCopy);
1154      CHECK_EXCEPTION_(0);
1155    } else {
1156      objectName_cstr = PR_OBJ_EVERY;
1157    }
1158 
1159    const char* symbolName_cstr = env->GetStringUTFChars(symbolName, &isCopy);
1160    CHECK_EXCEPTION_(0);
1161 
1162    psaddr_t symbol_addr = (psaddr_t) 0;
1163    ps_pglobal_lookup((struct ps_prochandle*) p_ps_prochandle,  objectName_cstr,
1164                     symbolName_cstr, &symbol_addr);
1165 
1166    if (symbol_addr == 0) {
1167       print_debug("lookup for %s in %s failed\n", symbolName_cstr, objectName_cstr);
1168    }
1169 
1170    if (objectName_cstr != PR_OBJ_EVERY) {
1171      env->ReleaseStringUTFChars(objectName, objectName_cstr);
1172    }
1173    env->ReleaseStringUTFChars(symbolName, symbolName_cstr);
1174    return (jlong) (uintptr_t) symbol_addr;
1175 }
1176 
1177 /*
1178  * Class:       sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal
1179  * Method:      lookupByAddress0
1180  * Signature:   (J)Lsun/jvm/hotspot/debugger/cdbg/ClosestSymbol;
1181  * Description: lookup symbol name for a given address
1182  */
1183 JNIEXPORT jobject JNICALL Java_sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal_lookupByAddress0
1184    (JNIEnv *env, jobject this_obj, jlong address) {
1185    jlong p_ps_prochandle;
1186    p_ps_prochandle = env->GetLongField(this_obj, p_ps_prochandle_ID);
1187 
1188    char nameBuf[SYMBOL_BUF_SIZE + 1];
1189    GElf_Sym sym;
1190    int res = Plookup_by_addr((struct ps_prochandle*) p_ps_prochandle, (uintptr_t) address,
1191                                  nameBuf, sizeof(nameBuf), &sym, NULL);
1192    if (res != 0) { // failed
1193       return 0;
1194    }
1195 
1196    jstring resSym = env->NewStringUTF(nameBuf);
1197    CHECK_EXCEPTION_(0);
1198 
1199    return env->CallObjectMethod(this_obj, createClosestSymbol_ID, resSym, (address - sym.st_value));
1200 }
1201 
1202 /*
1203  * Class:     sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal
1204  * Method:    demangle0
1205  * Signature: (Ljava/lang/String;)Ljava/lang/String;
1206  */
1207 JNIEXPORT jstring JNICALL Java_sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal_demangle0
1208   (JNIEnv *env, jobject this_object, jstring name) {
1209   jboolean isCopy;
1210   const char* ptr = env->GetStringUTFChars(name, &isCopy);
1211   char  buf[2*SYMBOL_BUF_SIZE + 1];
1212   jstring res = 0;
1213   if (cplus_demangle((char*) ptr, buf, sizeof(buf)) != DEMANGLE_ESPACE) {
1214     res = env->NewStringUTF(buf);
1215   } else {
1216     res = name;
1217   }
1218   env->ReleaseStringUTFChars(name, ptr);
1219   return res;
1220 }
1221 
1222 /*
1223  * Class:       sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal
1224  * Method:      initIDs
1225  * Signature:   ()V
1226  * Description: get JNI ids for fields and methods of ProcDebuggerLocal class
1227  */
1228 JNIEXPORT void JNICALL Java_sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal_initIDs
1229   (JNIEnv *env, jclass clazz) {
1230   _libsaproc_debug = getenv("LIBSAPROC_DEBUG") != NULL;
1231   if (_libsaproc_debug) {
1232      // propagate debug mode to libproc.so
1233      static const char* var = "LIBPROC_DEBUG=1";
1234      putenv((char*)var);
1235   }
1236 
1237   void* libproc_handle = dlopen("libproc.so", RTLD_LAZY | RTLD_GLOBAL);
1238   if (libproc_handle == 0)
1239      THROW_NEW_DEBUGGER_EXCEPTION("can't load libproc.so, if you are using Solaris 5.7 or below, copy libproc.so from 5.8!");
1240 
1241   p_ps_prochandle_ID = env->GetFieldID(clazz, "p_ps_prochandle", "J");
1242   CHECK_EXCEPTION;
1243 
1244   libthread_db_handle_ID = env->GetFieldID(clazz, "libthread_db_handle", "J");
1245   CHECK_EXCEPTION;
1246 
1247   p_td_thragent_t_ID = env->GetFieldID(clazz, "p_td_thragent_t", "J");
1248   CHECK_EXCEPTION;
1249 
1250   p_td_init_ID = env->GetFieldID(clazz, "p_td_init", "J");
1251   CHECK_EXCEPTION;
1252 
1253   p_td_ta_new_ID = env->GetFieldID(clazz, "p_td_ta_new", "J");
1254   CHECK_EXCEPTION;
1255 
1256   p_td_ta_delete_ID = env->GetFieldID(clazz, "p_td_ta_delete", "J");
1257   CHECK_EXCEPTION;
1258 
1259   p_td_ta_thr_iter_ID = env->GetFieldID(clazz, "p_td_ta_thr_iter", "J");
1260   CHECK_EXCEPTION;
1261 
1262   p_td_thr_get_info_ID = env->GetFieldID(clazz, "p_td_thr_get_info", "J");
1263   CHECK_EXCEPTION;
1264 
1265   p_td_ta_map_id2thr_ID = env->GetFieldID(clazz, "p_td_ta_map_id2thr", "J");
1266   CHECK_EXCEPTION;
1267 
1268   p_td_thr_getgregs_ID = env->GetFieldID(clazz, "p_td_thr_getgregs", "J");
1269   CHECK_EXCEPTION;
1270 
1271   getThreadForThreadId_ID = env->GetMethodID(clazz,
1272                             "getThreadForThreadId", "(J)Lsun/jvm/hotspot/debugger/ThreadProxy;");
1273   CHECK_EXCEPTION;
1274 
1275   pcRegIndex_ID = env->GetFieldID(clazz, "pcRegIndex", "I");
1276   CHECK_EXCEPTION;
1277 
1278   fpRegIndex_ID = env->GetFieldID(clazz, "fpRegIndex", "I");
1279   CHECK_EXCEPTION;
1280 
1281   createSenderFrame_ID = env->GetMethodID(clazz,
1282                             "createSenderFrame", "(Lsun/jvm/hotspot/debugger/proc/ProcCFrame;JJ)Lsun/jvm/hotspot/debugger/proc/ProcCFrame;");
1283   CHECK_EXCEPTION;
1284 
1285   createLoadObject_ID = env->GetMethodID(clazz,
1286                             "createLoadObject", "(Ljava/lang/String;JJ)Lsun/jvm/hotspot/debugger/cdbg/LoadObject;");
1287   CHECK_EXCEPTION;
1288 
1289   createClosestSymbol_ID = env->GetMethodID(clazz,
1290                             "createClosestSymbol", "(Ljava/lang/String;J)Lsun/jvm/hotspot/debugger/cdbg/ClosestSymbol;");
1291   CHECK_EXCEPTION;
1292 
1293   listAdd_ID = env->GetMethodID(env->FindClass("java/util/List"), "add", "(Ljava/lang/Object;)Z");
1294   CHECK_EXCEPTION;
1295 
1296   // part of the class sharing workaround
1297   classes_jsa_fd_ID = env->GetFieldID(clazz, "classes_jsa_fd", "I");
1298   CHECK_EXCEPTION;
1299   p_file_map_header_ID = env->GetFieldID(clazz, "p_file_map_header", "J");
1300   CHECK_EXCEPTION;
1301 }