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