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