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