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