1 /*
   2  * Copyright 2002-2009 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  20  * CA 95054 USA or visit www.sun.com if you need additional information or
  21  * have any questions.
  22  *
  23  */
  24 
  25 #include "salibproc.h"
  26 #include "sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal.h"
  27 #include "sun_jvm_hotspot_asm_Disassembler.h"
  28 #include <thread_db.h>
  29 #include <strings.h>
  30 #include <limits.h>
  31 #include <demangle.h>
  32 #include <stdarg.h>
  33 #include <stdlib.h>
  34 #include <errno.h>
  35 
  36 #define CHECK_EXCEPTION_(value) if(env->ExceptionOccurred()) { return value; }
  37 #define CHECK_EXCEPTION if(env->ExceptionOccurred()) { return;}
  38 #define THROW_NEW_DEBUGGER_EXCEPTION_(str, value) { throwNewDebuggerException(env, str); return value; }
  39 #define THROW_NEW_DEBUGGER_EXCEPTION(str) { throwNewDebuggerException(env, str); return;}
  40 
  41 #define SYMBOL_BUF_SIZE  256
  42 #define ERR_MSG_SIZE     (PATH_MAX + 256)
  43 
  44 // debug mode
  45 static int _libsaproc_debug = 0;
  46 
  47 static void print_debug(const char* format,...) {
  48   if (_libsaproc_debug) {
  49     va_list alist;
  50 
  51     va_start(alist, format);
  52     fputs("libsaproc DEBUG: ", stderr);
  53     vfprintf(stderr, format, alist);
  54     va_end(alist);
  55   }
  56 }
  57 
  58 struct Debugger {
  59     JNIEnv* env;
  60     jobject this_obj;
  61 };
  62 
  63 struct DebuggerWithObject : Debugger {
  64     jobject obj;
  65 };
  66 
  67 struct DebuggerWith2Objects : DebuggerWithObject {
  68     jobject obj2;
  69 };
  70 
  71 /*
  72 * Portions of user thread level detail gathering code is from pstack source
  73 * code. See pstack.c in Solaris 2.8 user commands source code.
  74 */
  75 
  76 static void throwNewDebuggerException(JNIEnv* env, const char* errMsg) {
  77   env->ThrowNew(env->FindClass("sun/jvm/hotspot/debugger/DebuggerException"), errMsg);
  78 }
  79 
  80 // JNI ids for some fields, methods
  81 
  82 // libproc handler pointer
  83 static jfieldID p_ps_prochandle_ID = 0;
  84 
  85 // libthread.so dlopen handle, thread agent ptr and function pointers
  86 static jfieldID libthread_db_handle_ID   = 0;
  87 static jfieldID p_td_thragent_t_ID       = 0;
  88 static jfieldID p_td_init_ID             = 0;
  89 static jfieldID p_td_ta_new_ID           = 0;
  90 static jfieldID p_td_ta_delete_ID        = 0;
  91 static jfieldID p_td_ta_thr_iter_ID      = 0;
  92 static jfieldID p_td_thr_get_info_ID     = 0;
  93 static jfieldID p_td_ta_map_id2thr_ID    = 0;
  94 static jfieldID p_td_thr_getgregs_ID     = 0;
  95 
  96 // reg index fields
  97 static jfieldID pcRegIndex_ID            = 0;
  98 static jfieldID fpRegIndex_ID            = 0;
  99 
 100 // part of the class sharing workaround
 101 static jfieldID classes_jsa_fd_ID        = 0;
 102 static jfieldID p_file_map_header_ID     = 0;
 103 
 104 // method ids
 105 
 106 static jmethodID getThreadForThreadId_ID = 0;
 107 static jmethodID createSenderFrame_ID    = 0;
 108 static jmethodID createLoadObject_ID     = 0;
 109 static jmethodID createClosestSymbol_ID  = 0;
 110 static jmethodID listAdd_ID              = 0;
 111 
 112 /*
 113  * Functions we need from libthread_db
 114  */
 115 typedef td_err_e
 116         (*p_td_init_t)(void);
 117 typedef td_err_e
 118         (*p_td_ta_new_t)(void *, td_thragent_t **);
 119 typedef td_err_e
 120         (*p_td_ta_delete_t)(td_thragent_t *);
 121 typedef td_err_e
 122         (*p_td_ta_thr_iter_t)(const td_thragent_t *, td_thr_iter_f *, void *,
 123                 td_thr_state_e, int, sigset_t *, unsigned);
 124 typedef td_err_e
 125         (*p_td_thr_get_info_t)(const td_thrhandle_t *, td_thrinfo_t *);
 126 typedef td_err_e
 127         (*p_td_ta_map_id2thr_t)(const td_thragent_t *, thread_t,  td_thrhandle_t *);
 128 typedef td_err_e
 129         (*p_td_thr_getgregs_t)(const td_thrhandle_t *, prgregset_t);
 130 
 131 static void
 132 clear_libthread_db_ptrs(JNIEnv* env, jobject this_obj) {
 133   // release libthread_db agent, if we had created
 134   p_td_ta_delete_t p_td_ta_delete = 0;
 135   p_td_ta_delete = (p_td_ta_delete_t) env->GetLongField(this_obj, p_td_ta_delete_ID);
 136 
 137   td_thragent_t *p_td_thragent_t = 0;
 138   p_td_thragent_t = (td_thragent_t*) env->GetLongField(this_obj, p_td_thragent_t_ID);
 139   if (p_td_thragent_t != 0 && p_td_ta_delete != 0) {
 140      p_td_ta_delete(p_td_thragent_t);
 141   }
 142 
 143   // dlclose libthread_db.so
 144   void* libthread_db_handle = (void*) env->GetLongField(this_obj, libthread_db_handle_ID);
 145   if (libthread_db_handle != 0) {
 146     dlclose(libthread_db_handle);
 147   }
 148 
 149   env->SetLongField(this_obj, libthread_db_handle_ID, (jlong)0);
 150   env->SetLongField(this_obj, p_td_init_ID, (jlong)0);
 151   env->SetLongField(this_obj, p_td_ta_new_ID, (jlong)0);
 152   env->SetLongField(this_obj, p_td_ta_delete_ID, (jlong)0);
 153   env->SetLongField(this_obj, p_td_ta_thr_iter_ID, (jlong)0);
 154   env->SetLongField(this_obj, p_td_thr_get_info_ID, (jlong)0);
 155   env->SetLongField(this_obj, p_td_ta_map_id2thr_ID, (jlong)0);
 156   env->SetLongField(this_obj, p_td_thr_getgregs_ID, (jlong)0);
 157 }
 158 
 159 
 160 static void detach_internal(JNIEnv* env, jobject this_obj) {
 161   // clear libthread_db stuff
 162   clear_libthread_db_ptrs(env, this_obj);
 163 
 164   // release ptr to ps_prochandle
 165   jlong p_ps_prochandle;
 166   p_ps_prochandle = env->GetLongField(this_obj, p_ps_prochandle_ID);
 167   if (p_ps_prochandle != 0L) {
 168     Prelease((struct ps_prochandle*) p_ps_prochandle, PRELEASE_CLEAR);
 169   }
 170 
 171   // part of the class sharing workaround
 172   int classes_jsa_fd = env->GetIntField(this_obj, classes_jsa_fd_ID);
 173   if (classes_jsa_fd != -1) {
 174     close(classes_jsa_fd);
 175     struct FileMapHeader* pheader = (struct FileMapHeader*) env->GetLongField(this_obj, p_file_map_header_ID);
 176     if (pheader != NULL) {
 177       free(pheader);
 178     }
 179   }
 180 }
 181 
 182 // Is it okay to ignore libthread_db failure? Set env var to ignore
 183 // libthread_db failure. You can still debug, but will miss threads
 184 // related functionality.
 185 static bool sa_ignore_threaddb = (getenv("SA_IGNORE_THREADDB") != 0);
 186 
 187 #define HANDLE_THREADDB_FAILURE(msg)          \
 188   if (sa_ignore_threaddb) {                   \
 189      printf("libsaproc WARNING: %s\n", msg);  \
 190      return;                                  \
 191   } else {                                    \
 192      THROW_NEW_DEBUGGER_EXCEPTION(msg);       \
 193   }
 194 
 195 #define HANDLE_THREADDB_FAILURE_(msg, ret)    \
 196   if (sa_ignore_threaddb) {                   \
 197      printf("libsaproc WARNING: %s\n", msg);  \
 198      return ret;                              \
 199   } else {                                    \
 200      THROW_NEW_DEBUGGER_EXCEPTION_(msg, ret); \
 201   }
 202 
 203 static const char * alt_root = NULL;
 204 static int alt_root_len = -1;
 205 
 206 #define SA_ALTROOT "SA_ALTROOT"
 207 
 208 static void init_alt_root() {
 209   if (alt_root_len == -1) {
 210     alt_root = getenv(SA_ALTROOT);
 211     if (alt_root)
 212       alt_root_len = strlen(alt_root);
 213     else
 214       alt_root_len = 0;
 215   }
 216 }
 217 
 218 // This function is a complete substitute for the open system call
 219 // since it's also used to override open calls from libproc to
 220 // implement as a pathmap style facility for the SA.  If libproc
 221 // starts using other interfaces then this might have to extended to
 222 // cover other calls.
 223 extern "C" int libsaproc_open(const char * name, int oflag, ...) {
 224   if (oflag == O_RDONLY) {
 225     init_alt_root();
 226 
 227     if (_libsaproc_debug) {
 228       printf("libsaproc DEBUG: libsaproc_open %s\n", name);
 229     }
 230 
 231     if (alt_root_len > 0) {
 232       int fd = -1;
 233       char alt_path[PATH_MAX+1];
 234 
 235       strcpy(alt_path, alt_root);
 236       strcat(alt_path, name);
 237       fd = open(alt_path, O_RDONLY);
 238       if (fd >= 0) {
 239         if (_libsaproc_debug) {
 240           printf("libsaproc DEBUG: libsaproc_open substituted %s\n", alt_path);
 241         }
 242         return fd;
 243       }
 244 
 245       if (strrchr(name, '/')) {
 246         strcpy(alt_path, alt_root);
 247         strcat(alt_path, strrchr(name, '/'));
 248         fd = open(alt_path, O_RDONLY);
 249         if (fd >= 0) {
 250           if (_libsaproc_debug) {
 251             printf("libsaproc DEBUG: libsaproc_open substituted %s\n", alt_path);
 252           }
 253           return fd;
 254         }
 255       }
 256     }
 257   }
 258 
 259   {
 260     mode_t mode;
 261     va_list ap;
 262     va_start(ap, oflag);
 263     mode = va_arg(ap, mode_t);
 264     va_end(ap);
 265 
 266     return open(name, oflag, mode);
 267   }
 268 }
 269 
 270 
 271 static void * pathmap_dlopen(const char * name, int mode) {
 272   init_alt_root();
 273 
 274   if (_libsaproc_debug) {
 275     printf("libsaproc DEBUG: pathmap_dlopen %s\n", name);
 276   }
 277 
 278   void * handle = NULL;
 279   if (alt_root_len > 0) {
 280     char alt_path[PATH_MAX+1];
 281     strcpy(alt_path, alt_root);
 282     strcat(alt_path, name);
 283     handle = dlopen(alt_path, mode);
 284     if (_libsaproc_debug && handle) {
 285       printf("libsaproc DEBUG: pathmap_dlopen substituted %s\n", alt_path);
 286     }
 287 
 288     if (handle == NULL && strrchr(name, '/')) {
 289       strcpy(alt_path, alt_root);
 290       strcat(alt_path, strrchr(name, '/'));
 291       handle = dlopen(alt_path, mode);
 292       if (_libsaproc_debug && handle) {
 293         printf("libsaproc DEBUG: pathmap_dlopen substituted %s\n", alt_path);
 294       }
 295     }
 296   }
 297   if (handle == NULL) {
 298     handle = dlopen(name, mode);
 299   }
 300   if (_libsaproc_debug) {
 301     printf("libsaproc DEBUG: pathmap_dlopen %s return 0x%x\n", name, handle);
 302   }
 303   return handle;
 304 }
 305 
 306 // libproc and libthread_db callback functions
 307 
 308 extern "C" {
 309 
 310 static int
 311 init_libthread_db_ptrs(void *cd, const prmap_t *pmp, const char *object_name) {
 312   Debugger* dbg = (Debugger*) cd;
 313   JNIEnv* env = dbg->env;
 314   jobject this_obj = dbg->this_obj;
 315   struct ps_prochandle* ph = (struct ps_prochandle*) env->GetLongField(this_obj, p_ps_prochandle_ID);
 316 
 317   char *s1 = 0, *s2 = 0;
 318   char libthread_db[PATH_MAX];
 319 
 320   if (strstr(object_name, "/libthread.so.") == NULL)
 321      return (0);
 322 
 323   /*
 324    * We found a libthread.
 325    * dlopen() the matching libthread_db and get the thread agent handle.
 326    */
 327   if (Pstatus(ph)->pr_dmodel == PR_MODEL_NATIVE) {
 328      (void) strcpy(libthread_db, object_name);
 329      s1 = (char*) strstr(object_name, ".so.");
 330      s2 = (char*) strstr(libthread_db, ".so.");
 331      (void) strcpy(s2, "_db");
 332      s2 += 3;
 333      (void) strcpy(s2, s1);
 334   } else {
 335 #ifdef _LP64
 336      /*
 337       * The victim process is 32-bit, we are 64-bit.
 338       * We have to find the 64-bit version of libthread_db
 339       * that matches the victim's 32-bit version of libthread.
 340       */
 341      (void) strcpy(libthread_db, object_name);
 342      s1 = (char*) strstr(object_name, "/libthread.so.");
 343      s2 = (char*) strstr(libthread_db, "/libthread.so.");
 344      (void) strcpy(s2, "/64");
 345      s2 += 3;
 346      (void) strcpy(s2, s1);
 347      s1 = (char*) strstr(s1, ".so.");
 348      s2 = (char*) strstr(s2, ".so.");
 349      (void) strcpy(s2, "_db");
 350      s2 += 3;
 351      (void) strcpy(s2, s1);
 352 #else
 353      return (0);
 354 #endif  /* _LP64 */
 355   }
 356 
 357   void* libthread_db_handle = 0;
 358   if ((libthread_db_handle = pathmap_dlopen(libthread_db, RTLD_LAZY|RTLD_LOCAL)) == NULL) {
 359      char errMsg[PATH_MAX + 256];
 360      sprintf(errMsg, "Can't load %s!", libthread_db);
 361      HANDLE_THREADDB_FAILURE_(errMsg, 0);
 362   }
 363   env->SetLongField(this_obj, libthread_db_handle_ID, (jlong)(uintptr_t)libthread_db_handle);
 364 
 365   void* tmpPtr = 0;
 366   tmpPtr = dlsym(libthread_db_handle, "td_init");
 367   if (tmpPtr == 0) {
 368      HANDLE_THREADDB_FAILURE_("dlsym failed on td_init!", 0);
 369   }
 370   env->SetLongField(this_obj, p_td_init_ID, (jlong)(uintptr_t) tmpPtr);
 371 
 372   tmpPtr =dlsym(libthread_db_handle, "td_ta_new");
 373   if (tmpPtr == 0) {
 374      HANDLE_THREADDB_FAILURE_("dlsym failed on td_ta_new!", 0);
 375   }
 376   env->SetLongField(this_obj, p_td_ta_new_ID, (jlong)(uintptr_t) tmpPtr);
 377 
 378   tmpPtr = dlsym(libthread_db_handle, "td_ta_delete");
 379   if (tmpPtr == 0) {
 380      HANDLE_THREADDB_FAILURE_("dlsym failed on td_ta_delete!", 0);
 381   }
 382   env->SetLongField(this_obj, p_td_ta_delete_ID, (jlong)(uintptr_t) tmpPtr);
 383 
 384   tmpPtr = dlsym(libthread_db_handle, "td_ta_thr_iter");
 385   if (tmpPtr == 0) {
 386      HANDLE_THREADDB_FAILURE_("dlsym failed on td_ta_thr_iter!", 0);
 387   }
 388   env->SetLongField(this_obj, p_td_ta_thr_iter_ID, (jlong)(uintptr_t) tmpPtr);
 389 
 390   tmpPtr = dlsym(libthread_db_handle, "td_thr_get_info");
 391   if (tmpPtr == 0) {
 392      HANDLE_THREADDB_FAILURE_("dlsym failed on td_thr_get_info!", 0);
 393   }
 394   env->SetLongField(this_obj, p_td_thr_get_info_ID, (jlong)(uintptr_t) tmpPtr);
 395 
 396   tmpPtr = dlsym(libthread_db_handle, "td_ta_map_id2thr");
 397   if (tmpPtr == 0) {
 398      HANDLE_THREADDB_FAILURE_("dlsym failed on td_ta_map_id2thr!", 0);
 399   }
 400   env->SetLongField(this_obj, p_td_ta_map_id2thr_ID, (jlong)(uintptr_t) tmpPtr);
 401 
 402   tmpPtr = dlsym(libthread_db_handle, "td_thr_getgregs");
 403   if (tmpPtr == 0) {
 404      HANDLE_THREADDB_FAILURE_("dlsym failed on td_thr_getgregs!", 0);
 405   }
 406   env->SetLongField(this_obj, p_td_thr_getgregs_ID, (jlong)(uintptr_t) tmpPtr);
 407 
 408   return 1;
 409 }
 410 
 411 static int
 412 fill_thread_list(const td_thrhandle_t *p_td_thragent_t, void* cd) {
 413   DebuggerWithObject* dbgo = (DebuggerWithObject*) cd;
 414   JNIEnv* env = dbgo->env;
 415   jobject this_obj = dbgo->this_obj;
 416   jobject list = dbgo->obj;
 417 
 418   td_thrinfo_t thrinfo;
 419   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);
 420 
 421   if (p_td_thr_get_info(p_td_thragent_t, &thrinfo) != TD_OK)
 422     return (0);
 423 
 424   jobject threadProxy = env->CallObjectMethod(this_obj, getThreadForThreadId_ID, (jlong)(uintptr_t) thrinfo.ti_tid);
 425   CHECK_EXCEPTION_(1);
 426   env->CallBooleanMethod(list, listAdd_ID, threadProxy);
 427   CHECK_EXCEPTION_(1);
 428   return 0;
 429 }
 430 
 431 static int
 432 fill_load_object_list(void *cd, const prmap_t* pmp, const char* obj_name) {
 433 
 434   if (obj_name) {
 435      DebuggerWithObject* dbgo = (DebuggerWithObject*) cd;
 436      JNIEnv* env = dbgo->env;
 437      jobject this_obj = dbgo->this_obj;
 438      jobject list = dbgo->obj;
 439 
 440      jstring objectName = env->NewStringUTF(obj_name);
 441      CHECK_EXCEPTION_(1);
 442 
 443      jlong mapSize = (jlong) pmp->pr_size;
 444      jobject sharedObject = env->CallObjectMethod(this_obj, createLoadObject_ID,
 445                                   objectName, mapSize, (jlong)(uintptr_t)pmp->pr_vaddr);
 446      CHECK_EXCEPTION_(1);
 447      env->CallBooleanMethod(list, listAdd_ID, sharedObject);
 448      CHECK_EXCEPTION_(1);
 449   }
 450 
 451   return 0;
 452 }
 453 
 454 static int
 455 fill_cframe_list(void *cd, const prgregset_t regs, uint_t argc, const long *argv) {
 456   DebuggerWith2Objects* dbgo2 = (DebuggerWith2Objects*) cd;
 457   JNIEnv* env = dbgo2->env;
 458   jobject this_obj = dbgo2->this_obj;
 459   jobject curFrame = dbgo2->obj2;
 460 
 461   jint pcRegIndex = env->GetIntField(this_obj, pcRegIndex_ID);
 462   jint fpRegIndex = env->GetIntField(this_obj, fpRegIndex_ID);
 463 
 464   jlong pc = (jlong) (uintptr_t) regs[pcRegIndex];
 465   jlong fp = (jlong) (uintptr_t) regs[fpRegIndex];
 466 
 467   dbgo2->obj2 = env->CallObjectMethod(this_obj, createSenderFrame_ID,
 468                                     curFrame, pc, fp);
 469   CHECK_EXCEPTION_(1);
 470   if (dbgo2->obj == 0) {
 471      dbgo2->obj = dbgo2->obj2;
 472   }
 473   return 0;
 474 }
 475 
 476 // part of the class sharing workaround
 477 
 478 // FIXME: !!HACK ALERT!!
 479 
 480 // The format of sharing achive file header is needed to read shared heap
 481 // file mappings. For now, I am hard coding portion of FileMapHeader here.
 482 // Refer to filemap.hpp.
 483 
 484 // FileMapHeader describes the shared space data in the file to be
 485 // mapped.  This structure gets written to a file.  It is not a class, so
 486 // that the compilers don't add any compiler-private data to it.
 487 
 488 // Refer to CompactingPermGenGen::n_regions in compactingPermGenGen.hpp
 489 const int NUM_SHARED_MAPS = 4;
 490 
 491 // Refer to FileMapInfo::_current_version in filemap.hpp
 492 const int CURRENT_ARCHIVE_VERSION = 1;
 493 
 494 struct FileMapHeader {
 495  int   _magic;              // identify file type.
 496  int   _version;            // (from enum, above.)
 497  size_t _alignment;         // how shared archive should be aligned
 498 
 499 
 500  struct space_info {
 501    int    _file_offset;     // sizeof(this) rounded to vm page size
 502    char*  _base;            // copy-on-write base address
 503    size_t _capacity;        // for validity checking
 504    size_t _used;            // for setting space top on read
 505 
 506    bool   _read_only;       // read only space?
 507    bool   _allow_exec;      // executable code in space?
 508 
 509  } _space[NUM_SHARED_MAPS]; // was _space[CompactingPermGenGen::n_regions];
 510 
 511  // Ignore the rest of the FileMapHeader. We don't need those fields here.
 512 };
 513 
 514 static bool
 515 read_jboolean(struct ps_prochandle* ph, psaddr_t addr, jboolean* pvalue) {
 516   jboolean i;
 517   if (ps_pread(ph, addr, &i, sizeof(i)) == PS_OK) {
 518     *pvalue = i;
 519     return true;
 520   } else {
 521     return false;
 522   }
 523 }
 524 
 525 static bool
 526 read_pointer(struct ps_prochandle* ph, psaddr_t addr, uintptr_t* pvalue) {
 527   uintptr_t uip;
 528   if (ps_pread(ph, addr, &uip, sizeof(uip)) == PS_OK) {
 529     *pvalue = uip;
 530     return true;
 531   } else {
 532     return false;
 533   }
 534 }
 535 
 536 static bool
 537 read_string(struct ps_prochandle* ph, psaddr_t addr, char* buf, size_t size) {
 538   char ch = ' ';
 539   size_t i = 0;
 540 
 541   while (ch != '\0') {
 542     if (ps_pread(ph, addr, &ch, sizeof(ch)) != PS_OK)
 543       return false;
 544 
 545     if (i < size - 1) {
 546       buf[i] = ch;
 547     } else { // smaller buffer
 548       return false;
 549     }
 550 
 551     i++; addr++;
 552   }
 553 
 554   buf[i] = '\0';
 555   return true;
 556 }
 557 
 558 #define USE_SHARED_SPACES_SYM   "UseSharedSpaces"
 559 // mangled symbol name for Arguments::SharedArchivePath
 560 #define SHARED_ARCHIVE_PATH_SYM "__1cJArgumentsRSharedArchivePath_"
 561 
 562 static int
 563 init_classsharing_workaround(void *cd, const prmap_t* pmap, const char* obj_name) {
 564   Debugger* dbg = (Debugger*) cd;
 565   JNIEnv*   env = dbg->env;
 566   jobject this_obj = dbg->this_obj;
 567   const char* jvm_name = 0;
 568   if ((jvm_name = strstr(obj_name, "libjvm.so")) != NULL ||
 569       (jvm_name = strstr(obj_name, "libjvm_g.so")) != NULL) {
 570     jvm_name = obj_name;
 571   } else {
 572     return 0;
 573   }
 574 
 575   struct ps_prochandle* ph = (struct ps_prochandle*) env->GetLongField(this_obj, p_ps_prochandle_ID);
 576 
 577   // initialize classes[_g].jsa file descriptor field.
 578   dbg->env->SetIntField(this_obj, classes_jsa_fd_ID, -1);
 579 
 580   // check whether class sharing is on by reading variable "UseSharedSpaces"
 581   psaddr_t useSharedSpacesAddr = 0;
 582   ps_pglobal_lookup(ph, jvm_name, USE_SHARED_SPACES_SYM, &useSharedSpacesAddr);
 583   if (useSharedSpacesAddr == 0) {
 584     THROW_NEW_DEBUGGER_EXCEPTION_("can't find 'UseSharedSpaces' flag\n", 1);
 585   }
 586 
 587   // read the value of the flag "UseSharedSpaces"
 588   // Since hotspot types are not available to build this library. So
 589   // equivalent type "jboolean" is used to read the value of "UseSharedSpaces"
 590   // which is same as hotspot type "bool".
 591   jboolean value = 0;
 592   if (read_jboolean(ph, useSharedSpacesAddr, &value) != true) {
 593     THROW_NEW_DEBUGGER_EXCEPTION_("can't read 'UseSharedSpaces' flag", 1);
 594   } else if ((int)value == 0) {
 595     print_debug("UseSharedSpaces is false, assuming -Xshare:off!\n");
 596     return 1;
 597   }
 598 
 599   char classes_jsa[PATH_MAX];
 600   psaddr_t sharedArchivePathAddrAddr = 0;
 601   ps_pglobal_lookup(ph, jvm_name, SHARED_ARCHIVE_PATH_SYM, &sharedArchivePathAddrAddr);
 602   if (sharedArchivePathAddrAddr == 0) {
 603     print_debug("can't find symbol 'Arguments::SharedArchivePath'\n");
 604     THROW_NEW_DEBUGGER_EXCEPTION_("can't get shared archive path from debuggee", 1);
 605   }
 606 
 607   uintptr_t sharedArchivePathAddr = 0;
 608   if (read_pointer(ph, sharedArchivePathAddrAddr, &sharedArchivePathAddr) != true) {
 609     print_debug("can't find read pointer 'Arguments::SharedArchivePath'\n");
 610     THROW_NEW_DEBUGGER_EXCEPTION_("can't get shared archive path from debuggee", 1);
 611   }
 612 
 613   if (read_string(ph, (psaddr_t)sharedArchivePathAddr, classes_jsa, sizeof(classes_jsa)) != true) {
 614     print_debug("can't find read 'Arguments::SharedArchivePath' value\n");
 615     THROW_NEW_DEBUGGER_EXCEPTION_("can't get shared archive path from debuggee", 1);
 616   }
 617 
 618   print_debug("looking for %s\n", classes_jsa);
 619 
 620   // open the classes[_g].jsa
 621   int fd = libsaproc_open(classes_jsa, O_RDONLY);
 622   if (fd < 0) {
 623     char errMsg[ERR_MSG_SIZE];
 624     sprintf(errMsg, "can't open shared archive file %s", classes_jsa);
 625     THROW_NEW_DEBUGGER_EXCEPTION_(errMsg, 1);
 626   } else {
 627     print_debug("opened shared archive file %s\n", classes_jsa);
 628   }
 629 
 630   // parse classes[_g].jsa
 631   struct FileMapHeader* pheader = (struct FileMapHeader*) malloc(sizeof(struct FileMapHeader));
 632   if (pheader == NULL) {
 633     close(fd);
 634     THROW_NEW_DEBUGGER_EXCEPTION_("can't allocate memory for shared file map header", 1);
 635   }
 636 
 637   memset(pheader, 0, sizeof(struct FileMapHeader));
 638   // read FileMapHeader
 639   size_t n = read(fd, pheader, sizeof(struct FileMapHeader));
 640   if (n != sizeof(struct FileMapHeader)) {
 641     free(pheader);
 642     close(fd);
 643     char errMsg[ERR_MSG_SIZE];
 644     sprintf(errMsg, "unable to read shared archive file map header from %s", classes_jsa);
 645     THROW_NEW_DEBUGGER_EXCEPTION_(errMsg, 1);
 646   }
 647 
 648   // check file magic
 649   if (pheader->_magic != 0xf00baba2) {
 650     free(pheader);
 651     close(fd);
 652     char errMsg[ERR_MSG_SIZE];
 653     sprintf(errMsg, "%s has bad shared archive magic 0x%x, expecting 0xf00baba2",
 654                    classes_jsa, pheader->_magic);
 655     THROW_NEW_DEBUGGER_EXCEPTION_(errMsg, 1);
 656   }
 657 
 658   // check version
 659   if (pheader->_version != CURRENT_ARCHIVE_VERSION) {
 660     free(pheader);
 661     close(fd);
 662     char errMsg[ERR_MSG_SIZE];
 663     sprintf(errMsg, "%s has wrong shared archive version %d, expecting %d",
 664                    classes_jsa, pheader->_version, CURRENT_ARCHIVE_VERSION);
 665     THROW_NEW_DEBUGGER_EXCEPTION_(errMsg, 1);
 666   }
 667 
 668   if (_libsaproc_debug) {
 669     for (int m = 0; m < NUM_SHARED_MAPS; m++) {
 670        print_debug("shared file offset %d mapped at 0x%lx, size = %ld, read only? = %d\n",
 671           pheader->_space[m]._file_offset, pheader->_space[m]._base,
 672           pheader->_space[m]._used, pheader->_space[m]._read_only);
 673     }
 674   }
 675 
 676   // FIXME: For now, omitting other checks such as VM version etc.
 677 
 678   // store class archive file fd and map header in debugger object fields
 679   dbg->env->SetIntField(this_obj, classes_jsa_fd_ID, fd);
 680   dbg->env->SetLongField(this_obj, p_file_map_header_ID, (jlong)(uintptr_t) pheader);
 681   return 1;
 682 }
 683 
 684 } // extern "C"
 685 
 686 // error messages for proc_arg_grab failure codes. The messages are
 687 // modified versions of comments against corresponding #defines in
 688 // libproc.h.
 689 static const char* proc_arg_grab_errmsgs[] = {
 690                       "",
 691  /* G_NOPROC */       "No such process",
 692  /* G_NOCORE */       "No such core file",
 693  /* G_NOPROCORCORE */ "No such process or core",
 694  /* G_NOEXEC */       "Cannot locate executable file",
 695  /* G_ZOMB   */       "Zombie processs",
 696  /* G_PERM   */       "No permission to attach",
 697  /* G_BUSY   */       "Another process has already attached",
 698  /* G_SYS    */       "System process - can not attach",
 699  /* G_SELF   */       "Process is self - can't debug myself!",
 700  /* G_INTR   */       "Interrupt received while grabbing",
 701  /* G_LP64   */       "debuggee is 64 bit, use java -d64 for debugger",
 702  /* G_FORMAT */       "File is not an ELF format core file - corrupted core?",
 703  /* G_ELF    */       "Libelf error while parsing an ELF file",
 704  /* G_NOTE   */       "Required PT_NOTE Phdr not present - corrupted core?",
 705 };
 706 
 707 static void attach_internal(JNIEnv* env, jobject this_obj, jstring cmdLine, jboolean isProcess) {
 708   jboolean isCopy;
 709   int gcode;
 710   const char* cmdLine_cstr = env->GetStringUTFChars(cmdLine, &isCopy);
 711   CHECK_EXCEPTION;
 712 
 713   // some older versions of libproc.so crash when trying to attach 32 bit
 714   // debugger to 64 bit core file. check and throw error.
 715 #ifndef _LP64
 716   atoi(cmdLine_cstr);
 717   if (errno) {
 718      // core file
 719      int core_fd;
 720      if ((core_fd = open64(cmdLine_cstr, O_RDONLY)) >= 0) {
 721         Elf32_Ehdr e32;
 722         if (pread64(core_fd, &e32, sizeof (e32), 0) == sizeof (e32) &&
 723             memcmp(&e32.e_ident[EI_MAG0], ELFMAG, SELFMAG) == 0 &&
 724             e32.e_type == ET_CORE && e32.e_ident[EI_CLASS] == ELFCLASS64) {
 725               close(core_fd);
 726               THROW_NEW_DEBUGGER_EXCEPTION("debuggee is 64 bit, use java -d64 for debugger");
 727         }
 728         close(core_fd);
 729      }
 730      // all other conditions are handled by libproc.so.
 731   }
 732 #endif
 733 
 734   // connect to process/core
 735   struct ps_prochandle* ph = proc_arg_grab(cmdLine_cstr, (isProcess? PR_ARG_PIDS : PR_ARG_CORES), PGRAB_FORCE, &gcode);
 736   env->ReleaseStringUTFChars(cmdLine, cmdLine_cstr);
 737   if (! ph) {
 738      if (gcode > 0 && gcode < sizeof(proc_arg_grab_errmsgs)/sizeof(const char*)) {
 739         char errMsg[ERR_MSG_SIZE];
 740         sprintf(errMsg, "Attach failed : %s", proc_arg_grab_errmsgs[gcode]);
 741         THROW_NEW_DEBUGGER_EXCEPTION(errMsg);
 742     } else {
 743         if (_libsaproc_debug && gcode == G_STRANGE) {
 744            perror("libsaproc DEBUG: ");
 745         }
 746         if (isProcess) {
 747            THROW_NEW_DEBUGGER_EXCEPTION("Not able to attach to process!");
 748         } else {
 749            THROW_NEW_DEBUGGER_EXCEPTION("Not able to attach to core file!");
 750         }
 751      }
 752   }
 753 
 754   // even though libproc.so supports 64 bit debugger and 32 bit debuggee, we don't
 755   // support such cross-bit-debugging. check for that combination and throw error.
 756 #ifdef _LP64
 757   int data_model;
 758   if (ps_pdmodel(ph, &data_model) != PS_OK) {
 759      Prelease(ph, PRELEASE_CLEAR);
 760      THROW_NEW_DEBUGGER_EXCEPTION("can't determine debuggee data model (ILP32? or LP64?)");
 761   }
 762   if (data_model == PR_MODEL_ILP32) {
 763      Prelease(ph, PRELEASE_CLEAR);
 764      THROW_NEW_DEBUGGER_EXCEPTION("debuggee is 32 bit, use 32 bit java for debugger");
 765   }
 766 #endif
 767 
 768   env->SetLongField(this_obj, p_ps_prochandle_ID, (jlong)(uintptr_t)ph);
 769 
 770   Debugger dbg;
 771   dbg.env = env;
 772   dbg.this_obj = this_obj;
 773   jthrowable exception = 0;
 774   if (! isProcess) {
 775     /*
 776      * With class sharing, shared perm. gen heap is allocated in with MAP_SHARED|PROT_READ.
 777      * These pages are mapped from the file "classes[_g].jsa". MAP_SHARED pages are not dumped
 778      * in Solaris core.To read shared heap pages, we have to read classes[_g].jsa file.
 779      */
 780     Pobject_iter(ph, init_classsharing_workaround, &dbg);
 781     exception = env->ExceptionOccurred();
 782     if (exception) {
 783       env->ExceptionClear();
 784       detach_internal(env, this_obj);
 785       env->Throw(exception);
 786       return;
 787     }
 788   }
 789 
 790   /*
 791    * Iterate over the process mappings looking
 792    * for libthread and then dlopen the appropriate
 793    * libthread_db and get function pointers.
 794    */
 795   Pobject_iter(ph, init_libthread_db_ptrs, &dbg);
 796   exception = env->ExceptionOccurred();
 797   if (exception) {
 798     env->ExceptionClear();
 799     if (!sa_ignore_threaddb) {
 800       detach_internal(env, this_obj);
 801       env->Throw(exception);
 802     }
 803     return;
 804   }
 805 
 806   // init libthread_db and create thread_db agent
 807   p_td_init_t p_td_init = (p_td_init_t) env->GetLongField(this_obj, p_td_init_ID);
 808   if (p_td_init == 0) {
 809     if (!sa_ignore_threaddb) {
 810       detach_internal(env, this_obj);
 811     }
 812     HANDLE_THREADDB_FAILURE("Did not find libthread in target process/core!");
 813   }
 814 
 815   if (p_td_init() != TD_OK) {
 816     if (!sa_ignore_threaddb) {
 817       detach_internal(env, this_obj);
 818     }
 819     HANDLE_THREADDB_FAILURE("Can't initialize thread_db!");
 820   }
 821 
 822   p_td_ta_new_t p_td_ta_new = (p_td_ta_new_t) env->GetLongField(this_obj, p_td_ta_new_ID);
 823 
 824   td_thragent_t *p_td_thragent_t = 0;
 825   if (p_td_ta_new(ph, &p_td_thragent_t) != TD_OK) {
 826     if (!sa_ignore_threaddb) {
 827       detach_internal(env, this_obj);
 828     }
 829     HANDLE_THREADDB_FAILURE("Can't create thread_db agent!");
 830   }
 831   env->SetLongField(this_obj, p_td_thragent_t_ID, (jlong)(uintptr_t) p_td_thragent_t);
 832 
 833 }
 834 
 835 /*
 836  * Class:     sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal
 837  * Method:    attach0
 838  * Signature: (Ljava/lang/String;)V
 839  * Description: process detach
 840  */
 841 JNIEXPORT void JNICALL Java_sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal_attach0__Ljava_lang_String_2
 842   (JNIEnv *env, jobject this_obj, jstring pid) {
 843   attach_internal(env, this_obj, pid, JNI_TRUE);
 844 }
 845 
 846 /*
 847  * Class:     sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal
 848  * Method:    attach0
 849  * Signature: (Ljava/lang/String;Ljava/lang/String;)V
 850  * Description: core file detach
 851  */
 852 JNIEXPORT void JNICALL Java_sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal_attach0__Ljava_lang_String_2Ljava_lang_String_2
 853   (JNIEnv *env, jobject this_obj, jstring executable, jstring corefile) {
 854   // ignore executable file name, libproc.so can detect a.out name anyway.
 855   attach_internal(env, this_obj, corefile, JNI_FALSE);
 856 }
 857 
 858 
 859 /*
 860  * Class:       sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal
 861  * Method:      detach0
 862  * Signature:   ()V
 863  * Description: process/core file detach
 864  */
 865 JNIEXPORT void JNICALL Java_sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal_detach0
 866   (JNIEnv *env, jobject this_obj) {
 867   detach_internal(env, this_obj);
 868 }
 869 
 870 /*
 871  * Class:       sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal
 872  * Method:      getRemoteProcessAddressSize0
 873  * Signature:   ()I
 874  * Description: get process/core address size
 875  */
 876 JNIEXPORT jint JNICALL Java_sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal_getRemoteProcessAddressSize0
 877   (JNIEnv *env, jobject this_obj) {
 878   jlong p_ps_prochandle;
 879   p_ps_prochandle = env->GetLongField(this_obj, p_ps_prochandle_ID);
 880   int data_model = PR_MODEL_ILP32;
 881   ps_pdmodel((struct ps_prochandle*) p_ps_prochandle, &data_model);
 882   print_debug("debuggee is %d bit\n", data_model == PR_MODEL_ILP32? 32 : 64);
 883   return (jint) data_model == PR_MODEL_ILP32? 32 : 64;
 884 }
 885 
 886 /*
 887  * Class:       sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal
 888  * Method:      getPageSize0
 889  * Signature:   ()I
 890  * Description: get process/core page size
 891  */
 892 JNIEXPORT jint JNICALL Java_sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal_getPageSize0
 893   (JNIEnv *env, jobject this_obj) {
 894 
 895 /*
 896   We are not yet attached to a java process or core file. getPageSize is called from
 897   the constructor of ProcDebuggerLocal. The following won't work!
 898 
 899     jlong p_ps_prochandle;
 900     p_ps_prochandle = env->GetLongField(this_obj, p_ps_prochandle_ID);
 901     CHECK_EXCEPTION_(-1);
 902     struct ps_prochandle* prochandle = (struct ps_prochandle*) p_ps_prochandle;
 903     return (Pstate(prochandle) == PS_DEAD) ? Pgetauxval(prochandle, AT_PAGESZ)
 904                                            : getpagesize();
 905 
 906   So even though core may have been generated with a different page size settings, for now
 907   call getpagesize.
 908 */
 909 
 910   return getpagesize();
 911 }
 912 
 913 /*
 914  * Class:       sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal
 915  * Method:      getThreadIntegerRegisterSet0
 916  * Signature:   (J)[J
 917  * Description: get gregset for a given thread specified by thread id
 918  */
 919 JNIEXPORT jlongArray JNICALL Java_sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal_getThreadIntegerRegisterSet0
 920   (JNIEnv *env, jobject this_obj, jlong tid) {
 921   // map the thread id to thread handle
 922   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);
 923 
 924   td_thragent_t* p_td_thragent_t = (td_thragent_t*) env->GetLongField(this_obj, p_td_thragent_t_ID);
 925   if (p_td_thragent_t == 0) {
 926      return 0;
 927   }
 928 
 929   td_thrhandle_t thr_handle;
 930   if (p_td_ta_map_id2thr(p_td_thragent_t, (thread_t) tid, &thr_handle) != TD_OK) {
 931      THROW_NEW_DEBUGGER_EXCEPTION_("can't map thread id to thread handle!", 0);
 932   }
 933 
 934   p_td_thr_getgregs_t p_td_thr_getgregs = (p_td_thr_getgregs_t) env->GetLongField(this_obj, p_td_thr_getgregs_ID);
 935   prgregset_t gregs;
 936   p_td_thr_getgregs(&thr_handle, gregs);
 937 
 938   jlongArray res = env->NewLongArray(NPRGREG);
 939   CHECK_EXCEPTION_(0);
 940   jboolean isCopy;
 941   jlong* ptr = env->GetLongArrayElements(res, &isCopy);
 942   for (int i = 0; i < NPRGREG; i++) {
 943     ptr[i] = (jlong) (uintptr_t) gregs[i];
 944   }
 945   env->ReleaseLongArrayElements(res, ptr, JNI_COMMIT);
 946   return res;
 947 }
 948 
 949 /*
 950  * Class:       sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal
 951  * Method:      fillThreadList0
 952  * Signature:   (Ljava/util/List;)V
 953  * Description: fills thread list of the debuggee process/core
 954  */
 955 JNIEXPORT void JNICALL Java_sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal_fillThreadList0
 956   (JNIEnv *env, jobject this_obj, jobject list) {
 957 
 958   td_thragent_t* p_td_thragent_t = (td_thragent_t*) env->GetLongField(this_obj, p_td_thragent_t_ID);
 959   if (p_td_thragent_t == 0) {
 960      return;
 961   }
 962 
 963   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);
 964 
 965   DebuggerWithObject dbgo;
 966   dbgo.env = env;
 967   dbgo.this_obj = this_obj;
 968   dbgo.obj = list;
 969 
 970   p_td_ta_thr_iter(p_td_thragent_t, fill_thread_list, &dbgo,
 971                    TD_THR_ANY_STATE, TD_THR_LOWEST_PRIORITY, TD_SIGNO_MASK, TD_THR_ANY_USER_FLAGS);
 972 }
 973 
 974 /*
 975  * Class:       sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal
 976  * Method:      fillCFrameList0
 977  * Signature:   ([J)Lsun/jvm/hotspot/debugger/proc/ProcCFrame;
 978  * Description: fills CFrame list for a given thread
 979  */
 980 JNIEXPORT jobject JNICALL Java_sun_jvm_hotspot_debugger_proc_ProcDebuggerLocal_fillCFrameList0
 981   (JNIEnv *env, jobject this_obj, jlongArray regsArray) {
 982   jlong p_ps_prochandle = env->GetLongField(this_obj, p_ps_prochandle_ID);
 983 
 984   DebuggerWith2Objects dbgo2;
 985   dbgo2.env  = env;
 986   dbgo2.this_obj = this_obj;
 987   dbgo2.obj  = NULL;
 988   dbgo2.obj2 = NULL;
 989 
 990   jboolean isCopy;
 991   jlong* ptr = env->GetLongArrayElements(regsArray, &isCopy);
 992   CHECK_EXCEPTION_(0);
 993 
 994   prgregset_t gregs;
 995   for (int i = 0; i < NPRGREG; i++) {
 996      gregs[i] = (uintptr_t) ptr[i];
 997   }
 998 
 999   env->ReleaseLongArrayElements(regsArray, ptr, JNI_ABORT);
1000   CHECK_EXCEPTION_(0);
1001   Pstack_iter((struct ps_prochandle*) p_ps_prochandle, gregs, 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);
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 }
1302 
1303 
1304 /*
1305  * Class:     sun_jvm_hotspot_asm_Disassembler
1306  * Method:    load_library
1307  * Signature: (Ljava/lang/String;)L
1308  */
1309 JNIEXPORT jlong JNICALL Java_sun_jvm_hotspot_asm_Disassembler_load_1library(JNIEnv * env,
1310                                                                            jclass disclass,
1311                                                                            jstring libname_s) {
1312   jboolean isCopy;
1313   const char * libname = env->GetStringUTFChars(libname_s, &isCopy);
1314   char buffer[PATH_MAX+1];
1315   snprintf(buffer, PATH_MAX, "%s.so", libname);
1316   void* hsdis_handle = dlopen(buffer, RTLD_LAZY | RTLD_GLOBAL);
1317   if (hsdis_handle != NULL) {
1318     return (jlong)dlsym(hsdis_handle, "decode_instructions_virtual");
1319   }
1320   return 0;
1321 }
1322 
1323 struct decode_env {
1324   JNIEnv* env;
1325   jobject dis;
1326   jobject visitor;
1327   jmethodID handle_event;
1328   jmethodID raw_print;
1329   char buffer[4096];
1330 };
1331 
1332 typedef void* (*decode_func)(void* start_va,
1333                              void* start, void* end,
1334                              void* (*event_callback)(void*, const char*, void*),
1335                              void* event_stream,
1336                              int (*printf_callback)(void*, const char*, ...),
1337                              void* printf_stream,
1338                              const char* options);
1339 
1340 static void* event_to_env(void* env_pv, const char* event, void* arg) {
1341   decode_env* denv = (decode_env*)env_pv;
1342   JNIEnv* env = denv->env;
1343   jstring event_string = env->NewStringUTF(event);
1344   jlong result = env->CallLongMethod(denv->dis, denv->handle_event, denv->visitor, event_string, (jlong) arg);
1345   jthrowable exception = env->ExceptionOccurred();
1346   if (exception) {
1347     env->ExceptionClear();
1348     result = 0;
1349   }
1350   return (void*)result;
1351 }
1352 
1353 static int printf_to_env(void* env_pv, const char* format, ...) {
1354   decode_env* denv = (decode_env*)env_pv;
1355   JNIEnv* env = denv->env;
1356   size_t flen = strlen(format);
1357   const char* raw = NULL;
1358   if (flen == 0)  return 0;
1359   if (flen < 2 ||
1360       strchr(format, '%') == NULL) {
1361     raw = format;
1362   } else if (format[0] == '%' && format[1] == '%' &&
1363              strchr(format+2, '%') == NULL) {
1364     // happens a lot on machines with names like %foo
1365     flen--;
1366     raw = format+1;
1367   }
1368   if (raw != NULL) {
1369     jstring output = env->NewStringUTF(raw);
1370     env->CallVoidMethod(denv->dis, denv->raw_print, denv->visitor, output);
1371     jthrowable exception = env->ExceptionOccurred();
1372     if (exception) {
1373       env->ExceptionClear();
1374     }
1375     return (int) flen;
1376   }
1377   va_list ap;
1378   va_start(ap, format);
1379   int cnt = vsnprintf(denv->buffer, sizeof(denv->buffer), format, ap);
1380   va_end(ap);
1381 
1382   jstring output = env->NewStringUTF(denv->buffer);
1383   env->CallVoidMethod(denv->dis, denv->raw_print, denv->visitor, output);
1384   jthrowable exception = env->ExceptionOccurred();
1385   if (exception) {
1386     env->ExceptionClear();
1387   }
1388   return cnt;
1389 }
1390 
1391 
1392 /*
1393  * Class:     sun_jvm_hotspot_asm_Disassembler
1394  * Method:    decode
1395  * Signature: (Lsun/jvm/hotspot/asm/InstructionVisitor;J[BLjava/lang/String;J)V
1396  */
1397 JNIEXPORT void JNICALL Java_sun_jvm_hotspot_asm_Disassembler_decode(JNIEnv * env,
1398                                                                     jobject dis,
1399                                                                     jobject visitor,
1400                                                                     jlong startPc,
1401                                                                     jbyteArray code,
1402                                                                     jstring options_s,
1403                                                                     jlong decode_instructions_virtual) {
1404   jboolean isCopy;
1405   jbyte* start = env->GetByteArrayElements(code, &isCopy);
1406   jbyte* end = start + env->GetArrayLength(code);
1407   const char * options = env->GetStringUTFChars(options_s, &isCopy);
1408 
1409   decode_env denv;
1410   denv.env = env;
1411   denv.dis = dis;
1412   denv.visitor = visitor;
1413   jclass disclass = env->GetObjectClass(dis);
1414   denv.handle_event = env->GetMethodID(disclass, "handle_event", "(Lsun/jvm/hotspot/asm/InstructionVisitor;Ljava/lang/String;J)J");
1415   CHECK_EXCEPTION;
1416 
1417   denv.raw_print = env->GetMethodID(disclass, "raw_print", "(Lsun/jvm/hotspot/asm/InstructionVisitor;Ljava/lang/String;)V");
1418   CHECK_EXCEPTION;
1419 
1420   
1421   (*(decode_func)decode_instructions_virtual)((void*)startPc, start, end,
1422                                               &event_to_env,  (void*) &denv,
1423                                               &printf_to_env, (void*) &denv,
1424                                               options);
1425 }