Path: blob/jdk8u272-b10-aarch32-20201026/hotspot/agent/src/os/bsd/MacosxDebuggerLocal.m
48792 views
/*1* Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include <objc/objc-runtime.h>25#import <Foundation/Foundation.h>26#import <JavaNativeFoundation/JavaNativeFoundation.h>2728#include <jni.h>2930#import <mach/mach.h>31#import <mach/mach_types.h>32#import <sys/sysctl.h>33#import <stdio.h>34#import <stdarg.h>35#import <stdlib.h>36#import <strings.h>37#import <dlfcn.h>38#import <limits.h>39#import <errno.h>40#import <sys/types.h>41#import <sys/ptrace.h>42#include "libproc_impl.h"4344#define UNSUPPORTED_ARCH "Unsupported architecture!"4546#if defined(x86_64) && !defined(amd64)47#define amd64 148#endif4950#if amd6451#include "sun_jvm_hotspot_debugger_amd64_AMD64ThreadContext.h"52#else53#error UNSUPPORTED_ARCH54#endif5556static jfieldID symbolicatorID = 0; // set in _init057static jfieldID taskID = 0; // set in _init05859static jfieldID p_ps_prochandle_ID = 0;60static jfieldID loadObjectList_ID = 0;61static jmethodID listAdd_ID = 0;6263static jmethodID createClosestSymbol_ID = 0;64static jmethodID createLoadObject_ID = 0;65static jmethodID getJavaThreadsInfo_ID = 0;6667// indicator if thread id (lwpid_t) was set68static bool _threads_filled = false;6970static void putSymbolicator(JNIEnv *env, jobject this_obj, id symbolicator) {71(*env)->SetLongField(env, this_obj, symbolicatorID, (jlong)(intptr_t)symbolicator);72}7374static id getSymbolicator(JNIEnv *env, jobject this_obj) {75jlong ptr = (*env)->GetLongField(env, this_obj, symbolicatorID);76return (id)(intptr_t)ptr;77}7879static void putTask(JNIEnv *env, jobject this_obj, task_t task) {80(*env)->SetLongField(env, this_obj, taskID, (jlong)task);81}8283static task_t getTask(JNIEnv *env, jobject this_obj) {84jlong ptr = (*env)->GetLongField(env, this_obj, taskID);85return (task_t)ptr;86}8788#define CHECK_EXCEPTION_(value) if ((*env)->ExceptionOccurred(env)) { return value; }89#define CHECK_EXCEPTION if ((*env)->ExceptionOccurred(env)) { return;}90#define THROW_NEW_DEBUGGER_EXCEPTION_(str, value) { throw_new_debugger_exception(env, str); return value; }91#define THROW_NEW_DEBUGGER_EXCEPTION(str) { throw_new_debugger_exception(env, str); return;}92#define CHECK_EXCEPTION_CLEAR if ((*env)->ExceptionOccurred(env)) { (*env)->ExceptionClear(env); }93#define CHECK_EXCEPTION_CLEAR_VOID if ((*env)->ExceptionOccurred(env)) { (*env)->ExceptionClear(env); return; }94#define CHECK_EXCEPTION_CLEAR_(value) if ((*env)->ExceptionOccurred(env)) { (*env)->ExceptionClear(env); return value; }9596static void throw_new_debugger_exception(JNIEnv* env, const char* errMsg) {97jclass exceptionClass = (*env)->FindClass(env, "sun/jvm/hotspot/debugger/DebuggerException");98CHECK_EXCEPTION;99(*env)->ThrowNew(env, exceptionClass, errMsg);100}101102static struct ps_prochandle* get_proc_handle(JNIEnv* env, jobject this_obj) {103jlong ptr = (*env)->GetLongField(env, this_obj, p_ps_prochandle_ID);104return (struct ps_prochandle*)(intptr_t)ptr;105}106107#if defined(__i386__)108#define hsdb_thread_state_t x86_thread_state32_t109#define hsdb_float_state_t x86_float_state32_t110#define HSDB_THREAD_STATE x86_THREAD_STATE32111#define HSDB_FLOAT_STATE x86_FLOAT_STATE32112#define HSDB_THREAD_STATE_COUNT x86_THREAD_STATE32_COUNT113#define HSDB_FLOAT_STATE_COUNT x86_FLOAT_STATE32_COUNT114#elif defined(__x86_64__)115#define hsdb_thread_state_t x86_thread_state64_t116#define hsdb_float_state_t x86_float_state64_t117#define HSDB_THREAD_STATE x86_THREAD_STATE64118#define HSDB_FLOAT_STATE x86_FLOAT_STATE64119#define HSDB_THREAD_STATE_COUNT x86_THREAD_STATE64_COUNT120#define HSDB_FLOAT_STATE_COUNT x86_FLOAT_STATE64_COUNT121#else122#error UNSUPPORTED_ARCH123#endif124125/*126* Class: sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal127* Method: init0128* Signature: ()V129*/130JNIEXPORT void JNICALL131Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_init0(JNIEnv *env, jclass cls) {132symbolicatorID = (*env)->GetFieldID(env, cls, "symbolicator", "J");133CHECK_EXCEPTION;134taskID = (*env)->GetFieldID(env, cls, "task", "J");135CHECK_EXCEPTION;136137// for core file138p_ps_prochandle_ID = (*env)->GetFieldID(env, cls, "p_ps_prochandle", "J");139CHECK_EXCEPTION;140loadObjectList_ID = (*env)->GetFieldID(env, cls, "loadObjectList", "Ljava/util/List;");141CHECK_EXCEPTION;142143// methods we use144createClosestSymbol_ID = (*env)->GetMethodID(env, cls, "createClosestSymbol",145"(Ljava/lang/String;J)Lsun/jvm/hotspot/debugger/cdbg/ClosestSymbol;");146CHECK_EXCEPTION;147createLoadObject_ID = (*env)->GetMethodID(env, cls, "createLoadObject",148"(Ljava/lang/String;JJ)Lsun/jvm/hotspot/debugger/cdbg/LoadObject;");149CHECK_EXCEPTION;150151// java.util.List method we call152jclass listClass = (*env)->FindClass(env, "java/util/List");153CHECK_EXCEPTION;154listAdd_ID = (*env)->GetMethodID(env, listClass, "add", "(Ljava/lang/Object;)Z");155CHECK_EXCEPTION;156getJavaThreadsInfo_ID = (*env)->GetMethodID(env, cls, "getJavaThreadsInfo",157"()[J");158CHECK_EXCEPTION;159160init_libproc(getenv("LIBSAPROC_DEBUG") != NULL);161}162163JNIEXPORT jint JNICALL Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_getAddressSize164(JNIEnv *env, jclass cls)165{166#ifdef _LP64167return 8;168#else169#error UNSUPPORTED_ARCH170#endif171}172173/** called by Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_lookupByName0 */174jlong lookupByNameIncore(175JNIEnv *env, struct ps_prochandle *ph, jobject this_obj, jstring objectName, jstring symbolName)176{177const char *objectName_cstr, *symbolName_cstr;178jlong addr;179jboolean isCopy;180objectName_cstr = NULL;181if (objectName != NULL) {182objectName_cstr = (*env)->GetStringUTFChars(env, objectName, &isCopy);183CHECK_EXCEPTION_(0);184}185symbolName_cstr = (*env)->GetStringUTFChars(env, symbolName, &isCopy);186CHECK_EXCEPTION_(0);187188print_debug("look for %s \n", symbolName_cstr);189addr = (jlong) lookup_symbol(ph, objectName_cstr, symbolName_cstr);190191if (objectName_cstr != NULL) {192(*env)->ReleaseStringUTFChars(env, objectName, objectName_cstr);193}194(*env)->ReleaseStringUTFChars(env, symbolName, symbolName_cstr);195return addr;196}197198/*199* Class: sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal200* Method: lookupByName0201* Signature: (Ljava/lang/String;Ljava/lang/String;)J202*/203JNIEXPORT jlong JNICALL204Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_lookupByName0(205JNIEnv *env, jobject this_obj,206jstring objectName, jstring symbolName)207{208struct ps_prochandle* ph = get_proc_handle(env, this_obj);209if (ph != NULL && ph->core != NULL) {210return lookupByNameIncore(env, ph, this_obj, objectName, symbolName);211}212213jlong address = 0;214215JNF_COCOA_ENTER(env);216NSString *symbolNameString = JNFJavaToNSString(env, symbolName);217218print_debug("lookupInProcess called for %s\n", [symbolNameString UTF8String]);219220id symbolicator = getSymbolicator(env, this_obj);221if (symbolicator != nil) {222uint64_t (*dynamicCall)(id, SEL, NSString *) = (uint64_t (*)(id, SEL, NSString *))&objc_msgSend;223address = (jlong) dynamicCall(symbolicator, @selector(addressForSymbol:), symbolNameString);224}225226print_debug("address of symbol %s = %llx\n", [symbolNameString UTF8String], address);227JNF_COCOA_EXIT(env);228229return address;230}231232/*233* Class: sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal234* Method: lookupByAddress0235* Signature: (J)Lsun/jvm/hotspot/debugger/cdbg/ClosestSymbol;236*/237JNIEXPORT jobject JNICALL Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_lookupByAddress0238(JNIEnv *env, jobject this_obj, jlong addr) {239uintptr_t offset;240const char* sym = NULL;241jstring sym_string;242243struct ps_prochandle* ph = get_proc_handle(env, this_obj);244if (ph != NULL && ph->core != NULL) {245sym = symbol_for_pc(ph, (uintptr_t) addr, &offset);246if (sym == NULL) return 0;247sym_string = (*env)->NewStringUTF(env, sym);248CHECK_EXCEPTION_(0);249return (*env)->CallObjectMethod(env, this_obj, createClosestSymbol_ID,250sym_string, (jlong)offset);251}252return 0;253}254255/** called from Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_readBytesFromProcess0 */256jbyteArray readBytesFromCore(257JNIEnv *env, struct ps_prochandle *ph, jobject this_obj, jlong addr, jlong numBytes)258{259jboolean isCopy;260jbyteArray array;261jbyte *bufPtr;262ps_err_e err;263264array = (*env)->NewByteArray(env, numBytes);265CHECK_EXCEPTION_(0);266bufPtr = (*env)->GetByteArrayElements(env, array, &isCopy);267CHECK_EXCEPTION_(0);268269err = ps_pread(ph, (psaddr_t) (uintptr_t)addr, bufPtr, numBytes);270(*env)->ReleaseByteArrayElements(env, array, bufPtr, 0);271return (err == PS_OK)? array : 0;272}273274/*275* Class: sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal276* Method: readBytesFromProcess0277* Signature: (JJ)Lsun/jvm/hotspot/debugger/ReadResult;278*/279JNIEXPORT jbyteArray JNICALL280Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_readBytesFromProcess0(281JNIEnv *env, jobject this_obj,282jlong addr, jlong numBytes)283{284print_debug("readBytesFromProcess called. addr = %llx numBytes = %lld\n", addr, numBytes);285286// must allocate storage instead of using former parameter buf287jbyteArray array;288289struct ps_prochandle* ph = get_proc_handle(env, this_obj);290if (ph != NULL && ph->core != NULL) {291return readBytesFromCore(env, ph, this_obj, addr, numBytes);292}293294array = (*env)->NewByteArray(env, numBytes);295CHECK_EXCEPTION_(0);296297unsigned long alignedAddress;298unsigned long alignedLength = 0;299kern_return_t result;300vm_offset_t *pages;301int *mapped;302long pageCount;303uint byteCount;304int i;305unsigned long remaining;306307alignedAddress = trunc_page(addr);308if (addr != alignedAddress) {309alignedLength += addr - alignedAddress;310}311alignedLength = round_page(numBytes);312pageCount = alignedLength/vm_page_size;313314// Allocate storage for pages and flags.315pages = malloc(pageCount * sizeof(vm_offset_t));316mapped = calloc(pageCount, sizeof(int));317318task_t gTask = getTask(env, this_obj);319// Try to read each of the pages.320for (i = 0; i < pageCount; i++) {321result = vm_read(gTask, alignedAddress + i*vm_page_size, vm_page_size,322&pages[i], &byteCount);323mapped[i] = (result == KERN_SUCCESS);324// assume all failures are unmapped pages325}326327print_debug("%ld pages\n", pageCount);328329remaining = numBytes;330331for (i = 0; i < pageCount; i++) {332unsigned long len = vm_page_size;333unsigned long start = 0;334335if (i == 0) {336start = addr - alignedAddress;337len = vm_page_size - start;338}339340if (i == (pageCount - 1)) {341len = remaining;342}343344if (mapped[i]) {345print_debug("page %d mapped (len %ld start %ld)\n", i, len, start);346(*env)->SetByteArrayRegion(env, array, 0, len, ((jbyte *) pages[i] + start));347vm_deallocate(mach_task_self(), pages[i], vm_page_size);348}349350remaining -= len;351}352353free (pages);354free (mapped);355return array;356}357358/** Only used for core file reading, set thread_id for threads which is got after core file parsed.359* Thread context is available in Mach-O core file but thread id is not. We can get thread id360* from Threads which store all java threads information when they are created. Here we can identify361* them as java threads by checking if a thread's rsp or rbp within a java thread's stack.362* Note Macosx uses unique_thread_id which is different from other platforms though printed ids363* are still pthread id. Function BsdDebuggerLocal.getJavaThreadsInfo returns an array of long364* integers to host all java threads' id, stack_start, stack_end as:365* [uid0, stack_start0, stack_end0, uid1, stack_start1, stack_end1, ...]366*367* The work cannot be done at init0 since Threads is not available yet(VM not initialized yet).368* This function should be called only once if succeeded369*/370bool fill_java_threads(JNIEnv* env, jobject this_obj, struct ps_prochandle* ph) {371int n = 0, i = 0, j;372struct reg regs;373374jlongArray thrinfos = (*env)->CallObjectMethod(env, this_obj, getJavaThreadsInfo_ID);375CHECK_EXCEPTION_(false);376int len = (int)(*env)->GetArrayLength(env, thrinfos);377uint64_t* cinfos = (uint64_t *)(*env)->GetLongArrayElements(env, thrinfos, NULL);378CHECK_EXCEPTION_(false);379n = get_num_threads(ph);380print_debug("fill_java_threads called, num_of_thread = %d\n", n);381for (i = 0; i < n; i++) {382if (!get_nth_lwp_regs(ph, i, ®s)) {383print_debug("Could not get regs of thread %d, already set!\n", i);384return false;385}386for (j = 0; j < len; j += 3) {387lwpid_t uid = cinfos[j];388uint64_t beg = cinfos[j + 1];389uint64_t end = cinfos[j + 2];390if ((regs.r_rsp < end && regs.r_rsp >= beg) ||391(regs.r_rbp < end && regs.r_rbp >= beg)) {392set_lwp_id(ph, i, uid);393break;394}395}396}397(*env)->ReleaseLongArrayElements(env, thrinfos, (jlong*)cinfos, 0);398CHECK_EXCEPTION_(false);399return true;400}401402/* For core file only, called from403* Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_getThreadIntegerRegisterSet0404*/405jlongArray getThreadIntegerRegisterSetFromCore(JNIEnv *env, jobject this_obj, long lwp_id, struct ps_prochandle* ph) {406if (!_threads_filled) {407if (!fill_java_threads(env, this_obj, ph)) {408throw_new_debugger_exception(env, "Failed to fill in threads");409return 0;410} else {411_threads_filled = true;412}413}414415struct reg gregs;416jboolean isCopy;417jlongArray array;418jlong *regs;419420if (get_lwp_regs(ph, lwp_id, &gregs) != true) {421THROW_NEW_DEBUGGER_EXCEPTION_("get_thread_regs failed for a lwp", 0);422}423424#undef NPRGREG425#undef REG_INDEX426#if amd64427#define NPRGREG sun_jvm_hotspot_debugger_amd64_AMD64ThreadContext_NPRGREG428#define REG_INDEX(reg) sun_jvm_hotspot_debugger_amd64_AMD64ThreadContext_##reg429430array = (*env)->NewLongArray(env, NPRGREG);431CHECK_EXCEPTION_(0);432regs = (*env)->GetLongArrayElements(env, array, &isCopy);433434regs[REG_INDEX(R15)] = gregs.r_r15;435regs[REG_INDEX(R14)] = gregs.r_r14;436regs[REG_INDEX(R13)] = gregs.r_r13;437regs[REG_INDEX(R12)] = gregs.r_r12;438regs[REG_INDEX(RBP)] = gregs.r_rbp;439regs[REG_INDEX(RBX)] = gregs.r_rbx;440regs[REG_INDEX(R11)] = gregs.r_r11;441regs[REG_INDEX(R10)] = gregs.r_r10;442regs[REG_INDEX(R9)] = gregs.r_r9;443regs[REG_INDEX(R8)] = gregs.r_r8;444regs[REG_INDEX(RAX)] = gregs.r_rax;445regs[REG_INDEX(RCX)] = gregs.r_rcx;446regs[REG_INDEX(RDX)] = gregs.r_rdx;447regs[REG_INDEX(RSI)] = gregs.r_rsi;448regs[REG_INDEX(RDI)] = gregs.r_rdi;449regs[REG_INDEX(RIP)] = gregs.r_rip;450regs[REG_INDEX(CS)] = gregs.r_cs;451regs[REG_INDEX(RSP)] = gregs.r_rsp;452regs[REG_INDEX(SS)] = gregs.r_ss;453regs[REG_INDEX(FSBASE)] = 0;454regs[REG_INDEX(GSBASE)] = 0;455regs[REG_INDEX(DS)] = gregs.r_ds;456regs[REG_INDEX(ES)] = gregs.r_es;457regs[REG_INDEX(FS)] = gregs.r_fs;458regs[REG_INDEX(GS)] = gregs.r_gs;459regs[REG_INDEX(TRAPNO)] = gregs.r_trapno;460regs[REG_INDEX(RFL)] = gregs.r_rflags;461462#endif /* amd64 */463(*env)->ReleaseLongArrayElements(env, array, regs, JNI_COMMIT);464return array;465}466467/*468* Lookup the thread_t that corresponds to the given thread_id.469* The thread_id should be the result from calling thread_info() with THREAD_IDENTIFIER_INFO470* and reading the m_ident_info.thread_id returned.471* The returned thread_t is the mach send right to the kernel port for the corresponding thread.472*473* We cannot simply use the OSThread._thread_id field in the JVM. This is set to ::mach_thread_self()474* in the VM, but that thread port is not valid for a remote debugger to access the thread.475*/476thread_t477lookupThreadFromThreadId(task_t task, jlong thread_id) {478print_debug("lookupThreadFromThreadId thread_id=0x%llx\n", thread_id);479480thread_array_t thread_list = NULL;481mach_msg_type_number_t thread_list_count = 0;482thread_t result_thread = 0;483int i;484485// get the list of all the send rights486kern_return_t result = task_threads(task, &thread_list, &thread_list_count);487if (result != KERN_SUCCESS) {488print_debug("task_threads returned 0x%x\n", result);489return 0;490}491492for(i = 0 ; i < thread_list_count; i++) {493thread_identifier_info_data_t m_ident_info;494mach_msg_type_number_t count = THREAD_IDENTIFIER_INFO_COUNT;495496// get the THREAD_IDENTIFIER_INFO for the send right497result = thread_info(thread_list[i], THREAD_IDENTIFIER_INFO, (thread_info_t) &m_ident_info, &count);498if (result != KERN_SUCCESS) {499print_debug("thread_info returned 0x%x\n", result);500break;501}502503// if this is the one we're looking for, return the send right504if (thread_id == m_ident_info.thread_id)505{506result_thread = thread_list[i];507break;508}509}510511vm_size_t thread_list_size = (vm_size_t) (thread_list_count * sizeof (thread_t));512vm_deallocate(mach_task_self(), (vm_address_t) thread_list, thread_list_count);513514return result_thread;515}516517518/*519* Class: sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal520* Method: getThreadIntegerRegisterSet0521* Signature: (J)[J522*/523JNIEXPORT jlongArray JNICALL524Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_getThreadIntegerRegisterSet0(525JNIEnv *env, jobject this_obj,526jlong thread_id)527{528print_debug("getThreadRegisterSet0 called\n");529530struct ps_prochandle* ph = get_proc_handle(env, this_obj);531if (ph != NULL && ph->core != NULL) {532return getThreadIntegerRegisterSetFromCore(env, this_obj, thread_id, ph);533}534535kern_return_t result;536thread_t tid;537mach_msg_type_number_t count = HSDB_THREAD_STATE_COUNT;538hsdb_thread_state_t state;539jlongArray registerArray;540jlong *primitiveArray;541task_t gTask = getTask(env, this_obj);542543tid = lookupThreadFromThreadId(gTask, thread_id);544545result = thread_get_state(tid, HSDB_THREAD_STATE, (thread_state_t)&state, &count);546547if (result != KERN_SUCCESS) {548print_error("getregs: thread_get_state(%d) failed (%d)\n", tid, result);549return NULL;550}551552#if amd64553#define NPRGREG sun_jvm_hotspot_debugger_amd64_AMD64ThreadContext_NPRGREG554#undef REG_INDEX555#define REG_INDEX(reg) sun_jvm_hotspot_debugger_amd64_AMD64ThreadContext_##reg556557// 64 bit558print_debug("Getting threads for a 64-bit process\n");559registerArray = (*env)->NewLongArray(env, NPRGREG);560CHECK_EXCEPTION_(0);561primitiveArray = (*env)->GetLongArrayElements(env, registerArray, NULL);562563primitiveArray[REG_INDEX(R15)] = state.__r15;564primitiveArray[REG_INDEX(R14)] = state.__r14;565primitiveArray[REG_INDEX(R13)] = state.__r13;566primitiveArray[REG_INDEX(R12)] = state.__r12;567primitiveArray[REG_INDEX(R11)] = state.__r11;568primitiveArray[REG_INDEX(R10)] = state.__r10;569primitiveArray[REG_INDEX(R9)] = state.__r9;570primitiveArray[REG_INDEX(R8)] = state.__r8;571primitiveArray[REG_INDEX(RDI)] = state.__rdi;572primitiveArray[REG_INDEX(RSI)] = state.__rsi;573primitiveArray[REG_INDEX(RBP)] = state.__rbp;574primitiveArray[REG_INDEX(RBX)] = state.__rbx;575primitiveArray[REG_INDEX(RDX)] = state.__rdx;576primitiveArray[REG_INDEX(RCX)] = state.__rcx;577primitiveArray[REG_INDEX(RAX)] = state.__rax;578primitiveArray[REG_INDEX(TRAPNO)] = 0; // trapno, not used579primitiveArray[REG_INDEX(ERR)] = 0; // err, not used580primitiveArray[REG_INDEX(RIP)] = state.__rip;581primitiveArray[REG_INDEX(CS)] = state.__cs;582primitiveArray[REG_INDEX(RFL)] = state.__rflags;583primitiveArray[REG_INDEX(RSP)] = state.__rsp;584primitiveArray[REG_INDEX(SS)] = 0; // We don't have SS585primitiveArray[REG_INDEX(FS)] = state.__fs;586primitiveArray[REG_INDEX(GS)] = state.__gs;587primitiveArray[REG_INDEX(ES)] = 0;588primitiveArray[REG_INDEX(DS)] = 0;589primitiveArray[REG_INDEX(FSBASE)] = 0;590primitiveArray[REG_INDEX(GSBASE)] = 0;591print_debug("set registers\n");592593(*env)->ReleaseLongArrayElements(env, registerArray, primitiveArray, 0);594595#else596#error UNSUPPORTED_ARCH597#endif /* amd64 */598599return registerArray;600}601602/*603* Class: sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal604* Method: translateTID0605* Signature: (I)I606*/607JNIEXPORT jint JNICALL608Java_sun_jvm_hotspot_debugger_macosx_MacOSXDebuggerLocal_translateTID0(609JNIEnv *env, jobject this_obj, jint tid)610{611print_debug("translateTID0 called on tid = 0x%x\n", (int)tid);612613kern_return_t result;614thread_t foreign_tid, usable_tid;615mach_msg_type_name_t type;616617foreign_tid = tid;618619task_t gTask = getTask(env, this_obj);620result = mach_port_extract_right(gTask, foreign_tid,621MACH_MSG_TYPE_COPY_SEND,622&usable_tid, &type);623if (result != KERN_SUCCESS)624return -1;625626print_debug("translateTID0: 0x%x -> 0x%x\n", foreign_tid, usable_tid);627628return (jint) usable_tid;629}630631632static bool ptrace_continue(pid_t pid, int signal) {633// pass the signal to the process so we don't swallow it634int res;635if ((res = ptrace(PT_CONTINUE, pid, (caddr_t)1, signal)) < 0) {636print_error("attach: ptrace(PT_CONTINUE, %d) failed with %d\n", pid, res);637return false;638}639return true;640}641642// waits until the ATTACH has stopped the process643// by signal SIGSTOP644static bool ptrace_waitpid(pid_t pid) {645int ret;646int status;647while (true) {648// Wait for debuggee to stop.649ret = waitpid(pid, &status, 0);650if (ret >= 0) {651if (WIFSTOPPED(status)) {652// Any signal will stop the thread, make sure it is SIGSTOP. Otherwise SIGSTOP653// will still be pending and delivered when the process is DETACHED and the process654// will go to sleep.655if (WSTOPSIG(status) == SIGSTOP) {656// Debuggee stopped by SIGSTOP.657return true;658}659if (!ptrace_continue(pid, WSTOPSIG(status))) {660print_error("attach: Failed to correctly attach to VM. VM might HANG! [PTRACE_CONT failed, stopped by %d]\n", WSTOPSIG(status));661return false;662}663} else {664print_error("attach: waitpid(): Child process exited/terminated (status = 0x%x)\n", status);665return false;666}667} else {668switch (errno) {669case EINTR:670continue;671break;672case ECHILD:673print_error("attach: waitpid() failed. Child process pid (%d) does not exist \n", pid);674break;675case EINVAL:676print_error("attach: waitpid() failed. Invalid options argument.\n");677break;678default:679print_error("attach: waitpid() failed. Unexpected error %d\n",errno);680break;681}682return false;683}684}685}686687// attach to a process/thread specified by "pid"688static bool ptrace_attach(pid_t pid) {689int res;690if ((res = ptrace(PT_ATTACH, pid, 0, 0)) < 0) {691print_error("ptrace(PT_ATTACH, %d) failed with %d\n", pid, res);692return false;693} else {694return ptrace_waitpid(pid);695}696}697698/*699* Class: sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal700* Method: attach0701* Signature: (I)V702*/703JNIEXPORT void JNICALL704Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_attach0__I(705JNIEnv *env, jobject this_obj, jint jpid)706{707print_debug("attach0 called for jpid=%d\n", (int)jpid);708709JNF_COCOA_ENTER(env);710711kern_return_t result;712task_t gTask = 0;713result = task_for_pid(mach_task_self(), jpid, &gTask);714if (result != KERN_SUCCESS) {715print_error("attach: task_for_pid(%d) failed: '%s' (%d)\n", (int)jpid, mach_error_string(result), result);716THROW_NEW_DEBUGGER_EXCEPTION("Can't attach to the process. Could be caused by an incorrect pid or lack of privileges.");717}718putTask(env, this_obj, gTask);719720// use ptrace to stop the process721// on os x, ptrace only needs to be called on the process, not the individual threads722if (ptrace_attach(jpid) != true) {723mach_port_deallocate(mach_task_self(), gTask);724THROW_NEW_DEBUGGER_EXCEPTION("Can't attach to the process");725}726727id symbolicator = nil;728id jrsSymbolicator = objc_lookUpClass("JRSSymbolicator");729if (jrsSymbolicator != nil) {730id (*dynamicCall)(id, SEL, pid_t) = (id (*)(id, SEL, pid_t))&objc_msgSend;731symbolicator = dynamicCall(jrsSymbolicator, @selector(symbolicatorForPid:), (pid_t)jpid);732}733if (symbolicator != nil) {734CFRetain(symbolicator); // pin symbolicator while in java heap735}736737putSymbolicator(env, this_obj, symbolicator);738if (symbolicator == nil) {739THROW_NEW_DEBUGGER_EXCEPTION("Can't attach symbolicator to the process");740}741742JNF_COCOA_EXIT(env);743}744745/** For core file,746called from Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_attach0__Ljava_lang_String_2Ljava_lang_String_2 */747static void fillLoadObjects(JNIEnv* env, jobject this_obj, struct ps_prochandle* ph) {748int n = 0, i = 0;749750// add load objects751n = get_num_libs(ph);752for (i = 0; i < n; i++) {753uintptr_t base;754const char* name;755jobject loadObject;756jobject loadObjectList;757jstring nameString;758759base = get_lib_base(ph, i);760name = get_lib_name(ph, i);761nameString = (*env)->NewStringUTF(env, name);762CHECK_EXCEPTION;763loadObject = (*env)->CallObjectMethod(env, this_obj, createLoadObject_ID,764nameString, (jlong)0, (jlong)base);765CHECK_EXCEPTION;766loadObjectList = (*env)->GetObjectField(env, this_obj, loadObjectList_ID);767CHECK_EXCEPTION;768(*env)->CallBooleanMethod(env, loadObjectList, listAdd_ID, loadObject);769CHECK_EXCEPTION;770}771}772773/*774* Class: sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal775* Method: attach0776* Signature: (Ljava/lang/String;Ljava/lang/String;)V777*/778JNIEXPORT void JNICALL779Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_attach0__Ljava_lang_String_2Ljava_lang_String_2(780JNIEnv *env, jobject this_obj, jstring execName, jstring coreName)781{782const char *execName_cstr;783const char *coreName_cstr;784jboolean isCopy;785struct ps_prochandle* ph;786787execName_cstr = (*env)->GetStringUTFChars(env, execName, &isCopy);788CHECK_EXCEPTION;789coreName_cstr = (*env)->GetStringUTFChars(env, coreName, &isCopy);790CHECK_EXCEPTION;791792print_debug("attach: %s %s\n", execName_cstr, coreName_cstr);793794if ( (ph = Pgrab_core(execName_cstr, coreName_cstr)) == NULL) {795(*env)->ReleaseStringUTFChars(env, execName, execName_cstr);796(*env)->ReleaseStringUTFChars(env, coreName, coreName_cstr);797THROW_NEW_DEBUGGER_EXCEPTION("Can't attach to the core file");798}799(*env)->SetLongField(env, this_obj, p_ps_prochandle_ID, (jlong)(intptr_t)ph);800(*env)->ReleaseStringUTFChars(env, execName, execName_cstr);801(*env)->ReleaseStringUTFChars(env, coreName, coreName_cstr);802fillLoadObjects(env, this_obj, ph);803}804805/*806* Class: sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal807* Method: detach0808* Signature: ()V809*/810JNIEXPORT void JNICALL811Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_detach0(812JNIEnv *env, jobject this_obj)813{814print_debug("detach0 called\n");815struct ps_prochandle* ph = get_proc_handle(env, this_obj);816if (ph != NULL && ph->core != NULL) {817Prelease(ph);818return;819}820JNF_COCOA_ENTER(env);821task_t gTask = getTask(env, this_obj);822823// detach from the ptraced process causing it to resume execution824int pid;825kern_return_t k_res;826k_res = pid_for_task(gTask, &pid);827if (k_res != KERN_SUCCESS) {828print_error("detach: pid_for_task(%d) failed (%d)\n", pid, k_res);829}830else {831int res = ptrace(PT_DETACH, pid, 0, 0);832if (res < 0) {833print_error("detach: ptrace(PT_DETACH, %d) failed (%d)\n", pid, res);834}835}836837mach_port_deallocate(mach_task_self(), gTask);838id symbolicator = getSymbolicator(env, this_obj);839if (symbolicator != nil) {840CFRelease(symbolicator);841}842JNF_COCOA_EXIT(env);843}844845846