1 /*
   2  * Copyright (c) 2002, 2013, 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 <objc/objc-runtime.h>
  26 #import <Foundation/Foundation.h>
  27 #import <JavaNativeFoundation/JavaNativeFoundation.h>
  28 
  29 #include <JavaVM/jni.h>
  30 
  31 #import <mach/mach.h>
  32 #import <mach/mach_types.h>
  33 #import <sys/sysctl.h>
  34 #import <stdio.h>
  35 #import <stdarg.h>
  36 #import <stdlib.h>
  37 #import <strings.h>
  38 #import <dlfcn.h>
  39 #import <limits.h>
  40 #import <errno.h>
  41 #import <sys/types.h>
  42 #import <sys/ptrace.h>
  43 #include "libproc_impl.h"
  44 
  45 #define UNSUPPORTED_ARCH "Unsupported architecture!"
  46 
  47 #if defined(x86_64) && !defined(amd64)
  48 #define amd64 1
  49 #endif
  50 
  51 #if amd64
  52 #include "sun_jvm_hotspot_debugger_amd64_AMD64ThreadContext.h"
  53 #else
  54 #error UNSUPPORTED_ARCH
  55 #endif
  56 
  57 static jfieldID symbolicatorID = 0; // set in _init0
  58 static jfieldID taskID = 0; // set in _init0
  59 
  60 static jfieldID p_ps_prochandle_ID = 0;
  61 static jfieldID loadObjectList_ID = 0;
  62 static jmethodID listAdd_ID = 0;
  63 
  64 static jmethodID createClosestSymbol_ID = 0;
  65 static jmethodID createLoadObject_ID = 0;
  66 static jmethodID getJavaThreadsInfo_ID = 0;
  67 
  68 // indicator if thread id (lwpid_t) was set
  69 static bool _threads_filled = false;
  70 
  71 static void putSymbolicator(JNIEnv *env, jobject this_obj, id symbolicator) {
  72   (*env)->SetLongField(env, this_obj, symbolicatorID, (jlong)(intptr_t)symbolicator);
  73 }
  74 
  75 static id getSymbolicator(JNIEnv *env, jobject this_obj) {
  76   jlong ptr = (*env)->GetLongField(env, this_obj, symbolicatorID);
  77   return (id)(intptr_t)ptr;
  78 }
  79 
  80 static void putTask(JNIEnv *env, jobject this_obj, task_t task) {
  81   (*env)->SetLongField(env, this_obj, taskID, (jlong)task);
  82 }
  83 
  84 static task_t getTask(JNIEnv *env, jobject this_obj) {
  85   jlong ptr = (*env)->GetLongField(env, this_obj, taskID);
  86   return (task_t)ptr;
  87 }
  88 
  89 #define CHECK_EXCEPTION_(value) if ((*env)->ExceptionOccurred(env)) { return value; }
  90 #define CHECK_EXCEPTION if ((*env)->ExceptionOccurred(env)) { return;}
  91 #define THROW_NEW_DEBUGGER_EXCEPTION_(str, value) { throw_new_debugger_exception(env, str); return value; }
  92 #define THROW_NEW_DEBUGGER_EXCEPTION(str) { throw_new_debugger_exception(env, str); return;}
  93 #define CHECK_EXCEPTION_CLEAR if ((*env)->ExceptionOccurred(env)) { (*env)->ExceptionClear(env); } 
  94 #define CHECK_EXCEPTION_CLEAR_VOID if ((*env)->ExceptionOccurred(env)) { (*env)->ExceptionClear(env); return; } 
  95 #define CHECK_EXCEPTION_CLEAR_(value) if ((*env)->ExceptionOccurred(env)) { (*env)->ExceptionClear(env); return value; } 
  96 
  97 static void throw_new_debugger_exception(JNIEnv* env, const char* errMsg) {
  98   (*env)->ThrowNew(env, (*env)->FindClass(env, "sun/jvm/hotspot/debugger/DebuggerException"), errMsg);
  99 }
 100 
 101 static struct ps_prochandle* get_proc_handle(JNIEnv* env, jobject this_obj) {
 102   jlong ptr = (*env)->GetLongField(env, this_obj, p_ps_prochandle_ID);
 103   return (struct ps_prochandle*)(intptr_t)ptr;
 104 }
 105 
 106 #if defined(__i386__)
 107     #define hsdb_thread_state_t     x86_thread_state32_t
 108     #define hsdb_float_state_t      x86_float_state32_t
 109     #define HSDB_THREAD_STATE       x86_THREAD_STATE32
 110     #define HSDB_FLOAT_STATE        x86_FLOAT_STATE32
 111     #define HSDB_THREAD_STATE_COUNT x86_THREAD_STATE32_COUNT
 112     #define HSDB_FLOAT_STATE_COUNT  x86_FLOAT_STATE32_COUNT
 113 #elif defined(__x86_64__)
 114     #define hsdb_thread_state_t     x86_thread_state64_t
 115     #define hsdb_float_state_t      x86_float_state64_t
 116     #define HSDB_THREAD_STATE       x86_THREAD_STATE64
 117     #define HSDB_FLOAT_STATE        x86_FLOAT_STATE64
 118     #define HSDB_THREAD_STATE_COUNT x86_THREAD_STATE64_COUNT
 119     #define HSDB_FLOAT_STATE_COUNT  x86_FLOAT_STATE64_COUNT
 120 #else
 121     #error UNSUPPORTED_ARCH
 122 #endif
 123 
 124 /*
 125  * Class:     sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal
 126  * Method:    init0
 127  * Signature: ()V
 128  */
 129 JNIEXPORT void JNICALL 
 130 Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_init0(JNIEnv *env, jclass cls) {
 131   symbolicatorID = (*env)->GetFieldID(env, cls, "symbolicator", "J");
 132   taskID = (*env)->GetFieldID(env, cls, "task", "J");
 133   CHECK_EXCEPTION;
 134 
 135   // for core file
 136   p_ps_prochandle_ID = (*env)->GetFieldID(env, cls, "p_ps_prochandle", "J");
 137   CHECK_EXCEPTION;
 138   loadObjectList_ID = (*env)->GetFieldID(env, cls, "loadObjectList", "Ljava/util/List;");
 139   CHECK_EXCEPTION;
 140 
 141   // methods we use
 142   createClosestSymbol_ID = (*env)->GetMethodID(env, cls, "createClosestSymbol",
 143                     "(Ljava/lang/String;J)Lsun/jvm/hotspot/debugger/cdbg/ClosestSymbol;");
 144   CHECK_EXCEPTION;
 145   createLoadObject_ID = (*env)->GetMethodID(env, cls, "createLoadObject",
 146                     "(Ljava/lang/String;JJ)Lsun/jvm/hotspot/debugger/cdbg/LoadObject;");
 147   CHECK_EXCEPTION;
 148 
 149   // java.util.List method we call
 150   jclass listClass = (*env)->FindClass(env, "java/util/List");
 151   CHECK_EXCEPTION;
 152   listAdd_ID = (*env)->GetMethodID(env, listClass, "add", "(Ljava/lang/Object;)Z");
 153   CHECK_EXCEPTION;
 154   getJavaThreadsInfo_ID = (*env)->GetMethodID(env, cls, "getJavaThreadsInfo",
 155                                                      "()[J");
 156   CHECK_EXCEPTION;
 157 
 158   init_libproc(getenv("LIBSAPROC_DEBUG") != NULL);
 159 }
 160 
 161 JNIEXPORT jint JNICALL Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_getAddressSize
 162   (JNIEnv *env, jclass cls)
 163 {
 164 #ifdef _LP64
 165   return 8;
 166 #else
 167   #error UNSUPPORTED_ARCH
 168 #endif
 169 }
 170 
 171 /** called by Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_lookupByName0 */
 172 jlong lookupByNameIncore(
 173   JNIEnv *env, struct ps_prochandle *ph, jobject this_obj, jstring objectName, jstring symbolName)
 174 {
 175   const char *objectName_cstr, *symbolName_cstr;
 176   jlong addr;
 177   jboolean isCopy;
 178   objectName_cstr = NULL;
 179   if (objectName != NULL) {
 180     objectName_cstr = (*env)->GetStringUTFChars(env, objectName, &isCopy);
 181     CHECK_EXCEPTION_(0);
 182   }
 183   symbolName_cstr = (*env)->GetStringUTFChars(env, symbolName, &isCopy);
 184   CHECK_EXCEPTION_(0);
 185 
 186   print_debug("look for %s \n", symbolName_cstr);
 187   addr = (jlong) lookup_symbol(ph, objectName_cstr, symbolName_cstr);
 188 
 189   if (objectName_cstr != NULL) {
 190     (*env)->ReleaseStringUTFChars(env, objectName, objectName_cstr);
 191   }
 192   (*env)->ReleaseStringUTFChars(env, symbolName, symbolName_cstr);
 193   return addr;
 194 }
 195 
 196 /*
 197  * Class:     sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal
 198  * Method:    lookupByName0
 199  * Signature: (Ljava/lang/String;Ljava/lang/String;)J
 200  */
 201 JNIEXPORT jlong JNICALL 
 202 Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_lookupByName0(
 203   JNIEnv *env, jobject this_obj, 
 204   jstring objectName, jstring symbolName) 
 205 {
 206   struct ps_prochandle* ph = get_proc_handle(env, this_obj);
 207   if (ph->core != NULL) {
 208     return lookupByNameIncore(env, ph, this_obj, objectName, symbolName);
 209   }
 210 
 211   jlong address = 0;
 212 
 213 JNF_COCOA_ENTER(env);
 214   NSString *symbolNameString = JNFJavaToNSString(env, symbolName);
 215 
 216   print_debug("lookupInProcess called for %s\n", [symbolNameString UTF8String]);
 217 
 218   id symbolicator = getSymbolicator(env, this_obj);
 219   if (symbolicator != nil) {
 220     uint64_t (*dynamicCall)(id, SEL, NSString *) = (uint64_t (*)(id, SEL, NSString *))&objc_msgSend;
 221     address = (jlong) dynamicCall(symbolicator, @selector(addressForSymbol:), symbolNameString);
 222   }
 223 
 224   print_debug("address of symbol %s = %llx\n", [symbolNameString UTF8String], address);
 225 JNF_COCOA_EXIT(env);
 226 
 227   return address;
 228 }
 229 
 230 /*
 231  * Class:     sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal
 232  * Method:    lookupByAddress0
 233  * Signature: (J)Lsun/jvm/hotspot/debugger/cdbg/ClosestSymbol;
 234  */
 235 JNIEXPORT jobject JNICALL Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_lookupByAddress0
 236   (JNIEnv *env, jobject this_obj, jlong addr) {
 237   uintptr_t offset;
 238   const char* sym = NULL;
 239 
 240   struct ps_prochandle* ph = get_proc_handle(env, this_obj);
 241   sym = symbol_for_pc(ph, (uintptr_t) addr, &offset);
 242   if (sym == NULL) return 0;
 243   return (*env)->CallObjectMethod(env, this_obj, createClosestSymbol_ID,
 244                           (*env)->NewStringUTF(env, sym), (jlong)offset);
 245 }
 246 
 247 /** called from Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_readBytesFromProcess0 */
 248 jbyteArray readBytesFromCore(
 249   JNIEnv *env, struct ps_prochandle *ph, jobject this_obj, jlong addr, jlong numBytes)
 250 {
 251   jboolean isCopy;
 252   jbyteArray array;
 253   jbyte *bufPtr;
 254   ps_err_e err;
 255 
 256   array = (*env)->NewByteArray(env, numBytes);
 257   CHECK_EXCEPTION_(0);
 258   bufPtr = (*env)->GetByteArrayElements(env, array, &isCopy);
 259   CHECK_EXCEPTION_(0);
 260 
 261   err = ps_pread(ph, (psaddr_t) (uintptr_t)addr, bufPtr, numBytes);
 262   (*env)->ReleaseByteArrayElements(env, array, bufPtr, 0);
 263   return (err == PS_OK)? array : 0;
 264 }
 265 
 266 /*
 267  * Class:     sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal
 268  * Method:    readBytesFromProcess0
 269  * Signature: (JJ)Lsun/jvm/hotspot/debugger/ReadResult;
 270  */
 271 JNIEXPORT jbyteArray JNICALL
 272 Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_readBytesFromProcess0(
 273   JNIEnv *env, jobject this_obj, 
 274   jlong addr, jlong numBytes) 
 275 {
 276   print_debug("readBytesFromProcess called. addr = %llx numBytes = %lld\n", addr, numBytes);
 277 
 278   // must allocate storage instead of using former parameter buf
 279   jbyteArray array;
 280 
 281   struct ps_prochandle* ph = get_proc_handle(env, this_obj);
 282   if (ph->core != NULL) {
 283     return readBytesFromCore(env, ph, this_obj, addr, numBytes);
 284   }
 285 
 286   array = (*env)->NewByteArray(env, numBytes);
 287   CHECK_EXCEPTION_(0);
 288 
 289   unsigned long alignedAddress;
 290   unsigned long alignedLength = 0;
 291   kern_return_t result;
 292   vm_offset_t *pages;
 293   int *mapped;
 294   long pageCount;
 295   uint byteCount;
 296   int i;
 297   unsigned long remaining;
 298 
 299   alignedAddress = trunc_page(addr);
 300   if (addr != alignedAddress) {
 301     alignedLength += addr - alignedAddress;
 302   }
 303   alignedLength = round_page(numBytes);
 304   pageCount = alignedLength/vm_page_size;
 305 
 306   // Allocate storage for pages and flags.
 307   pages = malloc(pageCount * sizeof(vm_offset_t));
 308   mapped = calloc(pageCount, sizeof(int));
 309 
 310   task_t gTask = getTask(env, this_obj);
 311   // Try to read each of the pages.
 312   for (i = 0; i < pageCount; i++) {
 313     result = vm_read(gTask, alignedAddress + i*vm_page_size, vm_page_size, 
 314                      &pages[i], &byteCount);
 315     mapped[i] = (result == KERN_SUCCESS); 
 316     // assume all failures are unmapped pages
 317   }
 318 
 319   print_debug("%ld pages\n", pageCount);
 320         
 321   remaining = numBytes;
 322         
 323   for (i = 0; i < pageCount; i++) {
 324     unsigned long len = vm_page_size;
 325     unsigned long start = 0;
 326 
 327     if (i == 0) {
 328       start = addr - alignedAddress;
 329       len = vm_page_size - start;
 330     }
 331 
 332     if (i == (pageCount - 1)) {
 333       len = remaining;
 334     }
 335 
 336     if (mapped[i]) {
 337       print_debug("page %d mapped (len %ld start %ld)\n", i, len, start);
 338       (*env)->SetByteArrayRegion(env, array, 0, len, ((jbyte *) pages[i] + start));
 339       vm_deallocate(mach_task_self(), pages[i], vm_page_size);
 340     }
 341 
 342     remaining -= len;
 343   }
 344 
 345   free (pages);
 346   free (mapped);
 347   return array;
 348 }
 349 
 350 /** Only used for core file reading, set thread_id for threads which is got after core file parsed.
 351   * Thread context is available in Mach-O core file but thread id is not. We can get thread id
 352   * from Threads which store all java threads information when they are created. Here we can identify
 353   * them as java threads by checking if a thread's rsp or rbp within a java thread's stack.
 354   * Note Macosx uses unique_thread_id which is different from other platforms though printed ids
 355   * are still pthread id. Function BsdDebuggerLocal.getJavaThreadsInfo returns an array of long
 356   * integers to host all java threads' id, stack_start, stack_end as:
 357   * [uid0, stack_start0, stack_end0, uid1, stack_start1, stack_end1, ...]
 358   *
 359   * The work cannot be done at init0 since Threads is not available yet(VM not initialized yet). 
 360   * This function should be called only once if succeeded
 361   */ 
 362 bool fill_java_threads(JNIEnv* env, jobject this_obj, struct ps_prochandle* ph) {
 363   int n = 0, i = 0, j;
 364   struct reg regs;
 365   
 366   jlongArray thrinfos = (*env)->CallObjectMethod(env, this_obj, getJavaThreadsInfo_ID);
 367   CHECK_EXCEPTION_(false);
 368   int len = (int)(*env)->GetArrayLength(env, thrinfos);
 369   uint64_t* cinfos = (uint64_t *)(*env)->GetLongArrayElements(env, thrinfos, NULL);
 370   CHECK_EXCEPTION_(false); 
 371   n = get_num_threads(ph);
 372   print_debug("fill_java_threads called, num_of_thread = %d\n", n);
 373   for (i = 0; i < n; i++) {
 374     if (!get_nth_lwp_regs(ph, i, &regs)) {
 375       print_debug("Could not get regs of thread %d, already set!\n", i);
 376       return false;
 377     }
 378     for (j = 0; j < len; j += 3) {
 379       lwpid_t  uid = cinfos[j];
 380       uint64_t beg = cinfos[j + 1];
 381       uint64_t end = cinfos[j + 2]; 
 382       if ((regs.r_rsp < end && regs.r_rsp >= beg) ||
 383           (regs.r_rbp < end && regs.r_rbp >= beg)) {
 384         set_lwp_id(ph, i, uid);
 385         break;
 386       }
 387     }
 388   }
 389   (*env)->ReleaseLongArrayElements(env, thrinfos, (jlong*)cinfos, 0);
 390   CHECK_EXCEPTION_(false);
 391   return true;
 392 }
 393 
 394 /* For core file only, called from
 395  * Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_getThreadIntegerRegisterSet0
 396  */
 397 jlongArray getThreadIntegerRegisterSetFromCore(JNIEnv *env, jobject this_obj, long lwp_id) {
 398   if (!_threads_filled)  {
 399     if (!fill_java_threads(env, this_obj, get_proc_handle(env, this_obj))) {
 400       throw_new_debugger_exception(env, "Failed to fill in threads");
 401       return 0;
 402     } else {
 403       _threads_filled = true;
 404     }
 405   }
 406 
 407   struct reg gregs;
 408   jboolean isCopy;
 409   jlongArray array;
 410   jlong *regs;
 411 
 412   struct ps_prochandle* ph = get_proc_handle(env, this_obj);
 413   if (get_lwp_regs(ph, lwp_id, &gregs) != true) {
 414     THROW_NEW_DEBUGGER_EXCEPTION_("get_thread_regs failed for a lwp", 0);
 415   }
 416 
 417 #undef NPRGREG
 418 #undef REG_INDEX
 419 #if amd64
 420 #define NPRGREG sun_jvm_hotspot_debugger_amd64_AMD64ThreadContext_NPRGREG
 421 #define REG_INDEX(reg) sun_jvm_hotspot_debugger_amd64_AMD64ThreadContext_##reg
 422 
 423   array = (*env)->NewLongArray(env, NPRGREG);
 424   CHECK_EXCEPTION_(0);
 425   regs = (*env)->GetLongArrayElements(env, array, &isCopy);
 426 
 427   regs[REG_INDEX(R15)] = gregs.r_r15;
 428   regs[REG_INDEX(R14)] = gregs.r_r14;
 429   regs[REG_INDEX(R13)] = gregs.r_r13;
 430   regs[REG_INDEX(R12)] = gregs.r_r12;
 431   regs[REG_INDEX(RBP)] = gregs.r_rbp;
 432   regs[REG_INDEX(RBX)] = gregs.r_rbx;
 433   regs[REG_INDEX(R11)] = gregs.r_r11;
 434   regs[REG_INDEX(R10)] = gregs.r_r10;
 435   regs[REG_INDEX(R9)]  = gregs.r_r9;
 436   regs[REG_INDEX(R8)]  = gregs.r_r8;
 437   regs[REG_INDEX(RAX)] = gregs.r_rax;
 438   regs[REG_INDEX(RCX)] = gregs.r_rcx;
 439   regs[REG_INDEX(RDX)] = gregs.r_rdx;
 440   regs[REG_INDEX(RSI)] = gregs.r_rsi;
 441   regs[REG_INDEX(RDI)] = gregs.r_rdi;
 442   regs[REG_INDEX(RIP)] = gregs.r_rip;
 443   regs[REG_INDEX(CS)]  = gregs.r_cs;
 444   regs[REG_INDEX(RSP)] = gregs.r_rsp;
 445   regs[REG_INDEX(SS)]  = gregs.r_ss;
 446   regs[REG_INDEX(FSBASE)] = 0;
 447   regs[REG_INDEX(GSBASE)] = 0;
 448   regs[REG_INDEX(DS)] = gregs.r_ds;
 449   regs[REG_INDEX(ES)] = gregs.r_es;
 450   regs[REG_INDEX(FS)] = gregs.r_fs;
 451   regs[REG_INDEX(GS)] = gregs.r_gs;
 452   regs[REG_INDEX(TRAPNO)] = gregs.r_trapno;
 453   regs[REG_INDEX(RFL)]    = gregs.r_rflags;
 454 
 455 #endif /* amd64 */
 456   (*env)->ReleaseLongArrayElements(env, array, regs, JNI_COMMIT);
 457   return array;
 458 }
 459 
 460 /*
 461  * Lookup the thread_t that corresponds to the given thread_id.
 462  * The thread_id should be the result from calling thread_info() with THREAD_IDENTIFIER_INFO
 463  * and reading the m_ident_info.thread_id returned.
 464  * The returned thread_t is the mach send right to the kernel port for the corresponding thread.
 465  *
 466  * We cannot simply use the OSThread._thread_id field in the JVM. This is set to ::mach_thread_self()
 467  * in the VM, but that thread port is not valid for a remote debugger to access the thread.
 468  */
 469 thread_t
 470 lookupThreadFromThreadId(task_t task, jlong thread_id) {
 471   print_debug("lookupThreadFromThreadId thread_id=0x%llx\n", thread_id);
 472   
 473   thread_array_t thread_list = NULL;
 474   mach_msg_type_number_t thread_list_count = 0;
 475   thread_t result_thread = 0;
 476   int i;
 477   
 478   // get the list of all the send rights
 479   kern_return_t result = task_threads(task, &thread_list, &thread_list_count);
 480   if (result != KERN_SUCCESS) {
 481     print_debug("task_threads returned 0x%x\n", result);
 482     return 0;
 483   }
 484   
 485   for(i = 0 ; i < thread_list_count; i++) {
 486     thread_identifier_info_data_t m_ident_info;
 487     mach_msg_type_number_t count = THREAD_IDENTIFIER_INFO_COUNT;
 488 
 489     // get the THREAD_IDENTIFIER_INFO for the send right
 490     result = thread_info(thread_list[i], THREAD_IDENTIFIER_INFO, (thread_info_t) &m_ident_info, &count);
 491     if (result != KERN_SUCCESS) {
 492       print_debug("thread_info returned 0x%x\n", result);
 493       break;
 494     }
 495     
 496     // if this is the one we're looking for, return the send right
 497     if (thread_id == m_ident_info.thread_id)
 498     {
 499       result_thread = thread_list[i];
 500       break;
 501     }
 502   }
 503   
 504   vm_size_t thread_list_size = (vm_size_t) (thread_list_count * sizeof (thread_t));
 505   vm_deallocate(mach_task_self(), (vm_address_t) thread_list, thread_list_count);
 506   
 507   return result_thread;
 508 }
 509 
 510 
 511 /*
 512  * Class:     sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal
 513  * Method:    getThreadIntegerRegisterSet0
 514  * Signature: (J)[J
 515  */
 516 JNIEXPORT jlongArray JNICALL 
 517 Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_getThreadIntegerRegisterSet0(
 518   JNIEnv *env, jobject this_obj, 
 519   jlong thread_id) 
 520 {
 521   print_debug("getThreadRegisterSet0 called\n");
 522 
 523   struct ps_prochandle* ph = get_proc_handle(env, this_obj);
 524   if (ph->core != NULL) {
 525     return getThreadIntegerRegisterSetFromCore(env, this_obj, thread_id);
 526   }
 527 
 528   kern_return_t result;
 529   thread_t tid;
 530   mach_msg_type_number_t count = HSDB_THREAD_STATE_COUNT;
 531   hsdb_thread_state_t state;
 532   jlongArray registerArray;
 533   jlong *primitiveArray;
 534   task_t gTask = getTask(env, this_obj);
 535 
 536   tid = lookupThreadFromThreadId(gTask, thread_id);
 537 
 538   result = thread_get_state(tid, HSDB_THREAD_STATE, (thread_state_t)&state, &count);
 539 
 540   if (result != KERN_SUCCESS) {
 541     print_error("getregs: thread_get_state(%d) failed (%d)\n", tid, result);
 542     return NULL;
 543   }
 544 
 545 #if amd64
 546 #define NPRGREG sun_jvm_hotspot_debugger_amd64_AMD64ThreadContext_NPRGREG
 547 #undef REG_INDEX
 548 #define REG_INDEX(reg) sun_jvm_hotspot_debugger_amd64_AMD64ThreadContext_##reg
 549 
 550   // 64 bit
 551   print_debug("Getting threads for a 64-bit process\n");
 552   registerArray = (*env)->NewLongArray(env, NPRGREG);
 553   CHECK_EXCEPTION_(0);
 554   primitiveArray = (*env)->GetLongArrayElements(env, registerArray, NULL);
 555 
 556   primitiveArray[REG_INDEX(R15)] = state.__r15;
 557   primitiveArray[REG_INDEX(R14)] = state.__r14;
 558   primitiveArray[REG_INDEX(R13)] = state.__r13;
 559   primitiveArray[REG_INDEX(R12)] = state.__r12;
 560   primitiveArray[REG_INDEX(R11)] = state.__r11;
 561   primitiveArray[REG_INDEX(R10)] = state.__r10;
 562   primitiveArray[REG_INDEX(R9)]  = state.__r9;
 563   primitiveArray[REG_INDEX(R8)]  = state.__r8;
 564   primitiveArray[REG_INDEX(RDI)] = state.__rdi;
 565   primitiveArray[REG_INDEX(RSI)] = state.__rsi;
 566   primitiveArray[REG_INDEX(RBP)] = state.__rbp;
 567   primitiveArray[REG_INDEX(RBX)] = state.__rbx;
 568   primitiveArray[REG_INDEX(RDX)] = state.__rdx;
 569   primitiveArray[REG_INDEX(RCX)] = state.__rcx;
 570   primitiveArray[REG_INDEX(RAX)] = state.__rax;
 571   primitiveArray[REG_INDEX(TRAPNO)] = 0;            // trapno, not used
 572   primitiveArray[REG_INDEX(ERR)]    = 0;            // err, not used 
 573   primitiveArray[REG_INDEX(RIP)] = state.__rip;
 574   primitiveArray[REG_INDEX(CS)]  = state.__cs;
 575   primitiveArray[REG_INDEX(RFL)] = state.__rflags;
 576   primitiveArray[REG_INDEX(RSP)] = state.__rsp;
 577   primitiveArray[REG_INDEX(SS)] = 0;                // We don't have SS
 578   primitiveArray[REG_INDEX(FS)] = state.__fs;
 579   primitiveArray[REG_INDEX(GS)] = state.__gs;
 580   primitiveArray[REG_INDEX(ES)] = 0;
 581   primitiveArray[REG_INDEX(DS)] = 0;
 582   primitiveArray[REG_INDEX(FSBASE)] = 0;
 583   primitiveArray[REG_INDEX(GSBASE)] = 0;
 584   print_debug("set registers\n");
 585 
 586   (*env)->ReleaseLongArrayElements(env, registerArray, primitiveArray, 0);
 587 
 588 #else
 589 #error UNSUPPORTED_ARCH
 590 #endif /* amd64 */
 591 
 592   return registerArray;
 593 }
 594 
 595 /*
 596  * Class:     sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal
 597  * Method:    translateTID0
 598  * Signature: (I)I
 599  */
 600 JNIEXPORT jint JNICALL
 601 Java_sun_jvm_hotspot_debugger_macosx_MacOSXDebuggerLocal_translateTID0(
 602   JNIEnv *env, jobject this_obj, jint tid) 
 603 {
 604   print_debug("translateTID0 called on tid = 0x%x\n", (int)tid);
 605 
 606   kern_return_t result;
 607   thread_t foreign_tid, usable_tid;
 608   mach_msg_type_name_t type;
 609   
 610   foreign_tid = tid;
 611     
 612   task_t gTask = getTask(env, this_obj);
 613   result = mach_port_extract_right(gTask, foreign_tid, 
 614                                    MACH_MSG_TYPE_COPY_SEND, 
 615                                    &usable_tid, &type);
 616   if (result != KERN_SUCCESS)
 617     return -1;
 618     
 619   print_debug("translateTID0: 0x%x -> 0x%x\n", foreign_tid, usable_tid);
 620     
 621   return (jint) usable_tid;
 622 }
 623 
 624 
 625 static bool ptrace_continue(pid_t pid, int signal) {
 626   // pass the signal to the process so we don't swallow it
 627   int res;
 628   if ((res = ptrace(PT_CONTINUE, pid, (caddr_t)1, signal)) < 0) {
 629     print_error("attach: ptrace(PT_CONTINUE, %d) failed with %d\n", pid, res);
 630     return false;
 631   }
 632   return true;
 633 }
 634 
 635 // waits until the ATTACH has stopped the process
 636 // by signal SIGSTOP
 637 static bool ptrace_waitpid(pid_t pid) {
 638   int ret;
 639   int status;
 640   while (true) {
 641     // Wait for debuggee to stop.
 642     ret = waitpid(pid, &status, 0);
 643     if (ret >= 0) {
 644       if (WIFSTOPPED(status)) {
 645         // Any signal will stop the thread, make sure it is SIGSTOP. Otherwise SIGSTOP
 646         // will still be pending and delivered when the process is DETACHED and the process
 647         // will go to sleep.
 648         if (WSTOPSIG(status) == SIGSTOP) {
 649           // Debuggee stopped by SIGSTOP.
 650           return true;
 651         }
 652         if (!ptrace_continue(pid, WSTOPSIG(status))) {
 653           print_error("attach: Failed to correctly attach to VM. VM might HANG! [PTRACE_CONT failed, stopped by %d]\n", WSTOPSIG(status));
 654           return false;
 655         }
 656       } else {
 657         print_error("attach: waitpid(): Child process exited/terminated (status = 0x%x)\n", status);
 658         return false;
 659       }
 660     } else {
 661       switch (errno) {
 662         case EINTR:
 663           continue;
 664           break;
 665         case ECHILD:
 666           print_error("attach: waitpid() failed. Child process pid (%d) does not exist \n", pid);
 667           break;
 668         case EINVAL:
 669           print_error("attach: waitpid() failed. Invalid options argument.\n");
 670           break;
 671         default:
 672           print_error("attach: waitpid() failed. Unexpected error %d\n",errno);
 673           break;
 674       }
 675       return false;
 676     }
 677   }
 678 }
 679 
 680 // attach to a process/thread specified by "pid"
 681 static bool ptrace_attach(pid_t pid) {
 682   int res;
 683   if ((res = ptrace(PT_ATTACH, pid, 0, 0)) < 0) {
 684     print_error("ptrace(PT_ATTACH, %d) failed with %d\n", pid, res);
 685     return false;
 686   } else {
 687     return ptrace_waitpid(pid);
 688   }
 689 }
 690 
 691 /*
 692  * Class:     sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal
 693  * Method:    attach0
 694  * Signature: (I)V
 695  */
 696 JNIEXPORT void JNICALL
 697 Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_attach0__I(
 698   JNIEnv *env, jobject this_obj, jint jpid)
 699 {
 700   print_debug("attach0 called for jpid=%d\n", (int)jpid);
 701 
 702 JNF_COCOA_ENTER(env);
 703 
 704   kern_return_t result;
 705   task_t gTask = 0;
 706   result = task_for_pid(mach_task_self(), jpid, &gTask);
 707   if (result != KERN_SUCCESS) {
 708     print_error("attach: task_for_pid(%d) failed (%d)\n", (int)jpid, result);
 709     THROW_NEW_DEBUGGER_EXCEPTION("Can't attach to the process");
 710   }
 711   putTask(env, this_obj, gTask);
 712 
 713   // use ptrace to stop the process
 714   // on os x, ptrace only needs to be called on the process, not the individual threads
 715   if (ptrace_attach(jpid) != true) {
 716     mach_port_deallocate(mach_task_self(), gTask);
 717     THROW_NEW_DEBUGGER_EXCEPTION("Can't attach to the process");
 718   }
 719 
 720   id symbolicator = nil;
 721   id jrsSymbolicator = objc_lookUpClass("JRSSymbolicator");
 722   if (jrsSymbolicator != nil) {
 723     id (*dynamicCall)(id, SEL, pid_t) = (id (*)(id, SEL, pid_t))&objc_msgSend;
 724     symbolicator = dynamicCall(jrsSymbolicator, @selector(symbolicatorForPid:), (pid_t)jpid);
 725   }
 726   if (symbolicator != nil) {
 727     CFRetain(symbolicator); // pin symbolicator while in java heap
 728   }
 729 
 730   putSymbolicator(env, this_obj, symbolicator);
 731   if (symbolicator == nil) {
 732     THROW_NEW_DEBUGGER_EXCEPTION("Can't attach symbolicator to the process");
 733   }
 734 
 735 JNF_COCOA_EXIT(env);
 736 }
 737 
 738 /** For core file, 
 739     called from Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_attach0__Ljava_lang_String_2Ljava_lang_String_2 */
 740 static void fillLoadObjects(JNIEnv* env, jobject this_obj, struct ps_prochandle* ph) {
 741   int n = 0, i = 0;
 742 
 743   // add load objects
 744   n = get_num_libs(ph);
 745   for (i = 0; i < n; i++) {
 746      uintptr_t base;
 747      const char* name;
 748      jobject loadObject;
 749      jobject loadObjectList;
 750 
 751      base = get_lib_base(ph, i);
 752      name = get_lib_name(ph, i);
 753      loadObject = (*env)->CallObjectMethod(env, this_obj, createLoadObject_ID,
 754                                    (*env)->NewStringUTF(env, name), (jlong)0, (jlong)base);
 755      CHECK_EXCEPTION;
 756      loadObjectList = (*env)->GetObjectField(env, this_obj, loadObjectList_ID);
 757      CHECK_EXCEPTION;
 758      (*env)->CallBooleanMethod(env, loadObjectList, listAdd_ID, loadObject);
 759      CHECK_EXCEPTION;
 760   }
 761 }
 762 
 763 /*
 764  * Class:     sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal
 765  * Method:    attach0
 766  * Signature: (Ljava/lang/String;Ljava/lang/String;)V
 767  */
 768 JNIEXPORT void JNICALL
 769 Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_attach0__Ljava_lang_String_2Ljava_lang_String_2(
 770   JNIEnv *env, jobject this_obj, jstring execName, jstring coreName)
 771 {
 772   const char *execName_cstr;
 773   const char *coreName_cstr;
 774   jboolean isCopy;
 775   struct ps_prochandle* ph;
 776 
 777   execName_cstr = (*env)->GetStringUTFChars(env, execName, &isCopy);
 778   CHECK_EXCEPTION;
 779   coreName_cstr = (*env)->GetStringUTFChars(env, coreName, &isCopy);
 780   CHECK_EXCEPTION;
 781 
 782   print_debug("attach: %s %s\n", execName_cstr, coreName_cstr);
 783 
 784   if ( (ph = Pgrab_core(execName_cstr, coreName_cstr)) == NULL) {
 785     (*env)->ReleaseStringUTFChars(env, execName, execName_cstr);
 786     (*env)->ReleaseStringUTFChars(env, coreName, coreName_cstr);
 787     THROW_NEW_DEBUGGER_EXCEPTION("Can't attach to the core file");
 788   }
 789   (*env)->SetLongField(env, this_obj, p_ps_prochandle_ID, (jlong)(intptr_t)ph);
 790   (*env)->ReleaseStringUTFChars(env, execName, execName_cstr);
 791   (*env)->ReleaseStringUTFChars(env, coreName, coreName_cstr);
 792   fillLoadObjects(env, this_obj, ph);
 793 }
 794 
 795 /*
 796  * Class:     sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal
 797  * Method:    detach0
 798  * Signature: ()V
 799  */
 800 JNIEXPORT void JNICALL
 801 Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_detach0(
 802   JNIEnv *env, jobject this_obj)
 803 {
 804   print_debug("detach0 called\n");
 805   struct ps_prochandle* ph = get_proc_handle(env, this_obj);
 806   if (ph != NULL && ph->core != NULL) {
 807      Prelease(ph);
 808      return;
 809   }
 810 JNF_COCOA_ENTER(env);
 811   task_t gTask = getTask(env, this_obj);
 812 
 813   // detach from the ptraced process causing it to resume execution
 814   int pid;
 815   kern_return_t k_res;
 816   k_res = pid_for_task(gTask, &pid);
 817   if (k_res != KERN_SUCCESS) {
 818     print_error("detach: pid_for_task(%d) failed (%d)\n", pid, k_res);
 819   }
 820   else {
 821     int res = ptrace(PT_DETACH, pid, 0, 0);
 822     if (res < 0) {
 823       print_error("detach: ptrace(PT_DETACH, %d) failed (%d)\n", pid, res);
 824     }
 825   }
 826 
 827   mach_port_deallocate(mach_task_self(), gTask);
 828   id symbolicator = getSymbolicator(env, this_obj);
 829   if (symbolicator != nil) {
 830     CFRelease(symbolicator);
 831   }
 832 JNF_COCOA_EXIT(env);
 833 }