1 /*
  2  * Copyright (c) 1998, 2021, 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.  Oracle designates this
  8  * particular file as subject to the "Classpath" exception as provided
  9  * by Oracle in the LICENSE file that accompanied this code.
 10  *
 11  * This code is distributed in the hope that it will be useful, but WITHOUT
 12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 14  * version 2 for more details (a copy is included in the LICENSE file that
 15  * accompanied this code).
 16  *
 17  * You should have received a copy of the GNU General Public License version
 18  * 2 along with this work; if not, write to the Free Software Foundation,
 19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 20  *
 21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 22  * or visit www.oracle.com if you need additional information or have any
 23  * questions.
 24  */
 25 
 26 #ifndef JDWP_UTIL_H
 27 #define JDWP_UTIL_H
 28 
 29 #include <stddef.h>
 30 #include <stdio.h>
 31 #include <string.h>
 32 #include <stdlib.h>
 33 #include <stdarg.h>
 34 
 35 #ifdef LINUX
 36 // Note. On Alpine Linux pthread.h includes calloc/malloc functions declaration.
 37 // We need to include pthread.h before the following stdlib names poisoning.
 38 #include <pthread.h>
 39 #endif
 40 
 41 #ifdef DEBUG
 42     /* Just to make sure these interfaces are not used here. */
 43     #undef free
 44     #define free(p) Do not use this interface.
 45     #undef malloc
 46     #define malloc(p) Do not use this interface.
 47     #undef calloc
 48     #define calloc(p) Do not use this interface.
 49     #undef realloc
 50     #define realloc(p) Do not use this interface.
 51     #undef strdup
 52     #define strdup(p) Do not use this interface.
 53 #endif
 54 
 55 #include "log_messages.h"
 56 #include "vm_interface.h"
 57 #include "JDWP.h"
 58 #include "util_md.h"
 59 #include "error_messages.h"
 60 #include "debugInit.h"
 61 
 62 /* Definition of a CommonRef tracked by the backend for the frontend */
 63 typedef struct RefNode {
 64     jlong        seqNum;        /* ID of reference, also key for hash table */
 65     jobject      ref;           /* could be strong or weak */
 66     struct RefNode *next;       /* next RefNode* in bucket chain */
 67     jint         count;         /* count of references */
 68     unsigned     strongCount;   /* count of strong reference */
 69 } RefNode;
 70 
 71 /* Value of a NULL ID */
 72 #define NULL_OBJECT_ID  ((jlong)0)
 73 
 74 /*
 75  * Globals used throughout the back end
 76  */
 77 
 78 typedef jint FrameNumber;
 79 
 80 typedef struct {
 81     jvmtiEnv *jvmti;
 82     JavaVM   *jvm;
 83     volatile jboolean vmDead; /* Once VM is dead it stays that way - don't put in init */
 84     jboolean assertOn;
 85     jboolean assertFatal;
 86     jboolean vthreadsSupported; /* If true, debugging support for vthreads is enabled.*/
 87     jboolean enumerateVThreads; /* If true, JDWP APIs returns vthreads in thread lists. */
 88     jboolean notifyVThreads;    /* If true, all vthread START and DEATH events are sent, subject to filtering. */
 89     jboolean trackAllVThreads;  /* If true, track all vthreads. Otherwise just track ones we need to track. */
 90     jboolean doerrorexit;
 91     jboolean modifiedUtf8;
 92     jboolean quiet;
 93 
 94     /* Debug flags (bit mask) */
 95     int      debugflags;
 96 
 97     /* Possible debug flags */
 98     #define USE_ITERATE_THROUGH_HEAP 0X001
 99 
100     char * options;
101 
102     jclass              classClass;
103     jclass              threadClass;
104     jclass              threadGroupClass;
105     jclass              classLoaderClass;
106     jclass              stringClass;
107     jclass              systemClass;
108     jmethodID           threadConstructor;
109     jmethodID           threadSetDaemon;
110     jmethodID           threadResume;
111     jmethodID           systemGetProperty;
112     jmethodID           setProperty;
113     jthreadGroup        systemThreadGroup;
114     jthreadGroup        vthreadThreadGroup;
115     jobject             agent_properties;
116 
117     jint                cachedJvmtiVersion;
118     jvmtiCapabilities   cachedJvmtiCapabilities;
119     jboolean            haveCachedJvmtiCapabilities;
120     jvmtiEventCallbacks callbacks;
121 
122     /* Various property values we should grab on initialization */
123     char* property_java_version;          /* UTF8 java.version */
124     char* property_java_vm_name;          /* UTF8 java.vm.name */
125     char* property_java_vm_info;          /* UTF8 java.vm.info */
126     char* property_java_class_path;       /* UTF8 java.class.path */
127     char* property_sun_boot_library_path; /* UTF8 sun.boot.library.path */
128     char* property_path_separator;        /* UTF8 path.separator */
129     char* property_user_dir;              /* UTF8 user.dir */
130 
131     unsigned log_flags;
132 
133     /* Common References static data */
134     jrawMonitorID refLock;
135     jlong         nextSeqNum;
136     unsigned      pinAllCount;
137     RefNode     **objectsByID;
138     int           objectsByIDsize;
139     int           objectsByIDcount;
140 
141     /* Indication that the agent has been loaded */
142     jboolean isLoaded;
143 
144     /* Indication that VM_DEATH has been recieved and the JVMTI callbacks have been cleared. */
145     volatile jboolean jvmtiCallBacksCleared;
146 
147 } BackendGlobalData;
148 
149 extern BackendGlobalData * gdata;
150 
151 /*
152  * Event Index for handlers
153  */
154 
155 typedef enum {
156         EI_min                  =  1,
157 
158         EI_SINGLE_STEP          =  1,
159         EI_BREAKPOINT           =  2,
160         EI_FRAME_POP            =  3,
161         EI_EXCEPTION            =  4,
162         EI_THREAD_START         =  5,
163         EI_THREAD_END           =  6,
164         EI_CLASS_PREPARE        =  7,
165         EI_GC_FINISH            =  8,
166         EI_CLASS_LOAD           =  9,
167         EI_FIELD_ACCESS         = 10,
168         EI_FIELD_MODIFICATION   = 11,
169         EI_EXCEPTION_CATCH      = 12,
170         EI_METHOD_ENTRY         = 13,
171         EI_METHOD_EXIT          = 14,
172         EI_MONITOR_CONTENDED_ENTER = 15,
173         EI_MONITOR_CONTENDED_ENTERED = 16,
174         EI_MONITOR_WAIT         = 17,
175         EI_MONITOR_WAITED       = 18,
176         EI_VM_INIT              = 19,
177         EI_VM_DEATH             = 20,
178         EI_VIRTUAL_THREAD_START = 21,
179         EI_VIRTUAL_THREAD_END   = 22,
180 
181         EI_max                  = 22
182 } EventIndex;
183 
184 /* Agent errors that might be in a jvmtiError for JDWP or internal.
185  *    (Done this way so that compiler allows it's use as a jvmtiError)
186  */
187 #define _AGENT_ERROR(x)                 ((jvmtiError)(JVMTI_ERROR_MAX+64+x))
188 #define AGENT_ERROR_INTERNAL                    _AGENT_ERROR(1)
189 #define AGENT_ERROR_VM_DEAD                     _AGENT_ERROR(2)
190 #define AGENT_ERROR_NO_JNI_ENV                  _AGENT_ERROR(3)
191 #define AGENT_ERROR_JNI_EXCEPTION               _AGENT_ERROR(4)
192 #define AGENT_ERROR_JVMTI_INTERNAL              _AGENT_ERROR(5)
193 #define AGENT_ERROR_JDWP_INTERNAL               _AGENT_ERROR(6)
194 #define AGENT_ERROR_NOT_CURRENT_FRAME           _AGENT_ERROR(7)
195 #define AGENT_ERROR_OUT_OF_MEMORY               _AGENT_ERROR(8)
196 #define AGENT_ERROR_INVALID_TAG                 _AGENT_ERROR(9)
197 #define AGENT_ERROR_ALREADY_INVOKING            _AGENT_ERROR(10)
198 #define AGENT_ERROR_INVALID_INDEX               _AGENT_ERROR(11)
199 #define AGENT_ERROR_INVALID_LENGTH              _AGENT_ERROR(12)
200 #define AGENT_ERROR_INVALID_STRING              _AGENT_ERROR(13)
201 #define AGENT_ERROR_INVALID_CLASS_LOADER        _AGENT_ERROR(14)
202 #define AGENT_ERROR_INVALID_ARRAY               _AGENT_ERROR(15)
203 #define AGENT_ERROR_TRANSPORT_LOAD              _AGENT_ERROR(16)
204 #define AGENT_ERROR_TRANSPORT_INIT              _AGENT_ERROR(17)
205 #define AGENT_ERROR_NATIVE_METHOD               _AGENT_ERROR(18)
206 #define AGENT_ERROR_INVALID_COUNT               _AGENT_ERROR(19)
207 #define AGENT_ERROR_INVALID_FRAMEID             _AGENT_ERROR(20)
208 #define AGENT_ERROR_NULL_POINTER                _AGENT_ERROR(21)
209 #define AGENT_ERROR_ILLEGAL_ARGUMENT            _AGENT_ERROR(22)
210 #define AGENT_ERROR_INVALID_THREAD              _AGENT_ERROR(23)
211 #define AGENT_ERROR_INVALID_EVENT_TYPE          _AGENT_ERROR(24)
212 #define AGENT_ERROR_INVALID_OBJECT              _AGENT_ERROR(25)
213 #define AGENT_ERROR_NO_MORE_FRAMES              _AGENT_ERROR(26)
214 #define AGENT_ERROR_INVALID_MODULE              _AGENT_ERROR(27)
215 
216 /* Combined event information */
217 
218 typedef struct {
219 
220     EventIndex  ei;
221     jthread     thread;
222     jboolean    is_vthread;
223     jclass      clazz;
224     jmethodID   method;
225     jlocation   location;
226     jobject     object; /* possibly an exception or user object */
227 
228     union {
229 
230         /* ei = EI_FIELD_ACCESS */
231         struct {
232             jclass      field_clazz;
233             jfieldID    field;
234         } field_access;
235 
236         /* ei = EI_FIELD_MODIFICATION */
237         struct {
238             jclass      field_clazz;
239             jfieldID    field;
240             char        signature_type;
241             jvalue      new_value;
242         } field_modification;
243 
244         /* ei = EI_EXCEPTION */
245         struct {
246             jclass      catch_clazz;
247             jmethodID   catch_method;
248             jlocation   catch_location;
249         } exception;
250 
251         /* ei = EI_METHOD_EXIT */
252         struct {
253             jvalue      return_value;
254         } method_exit;
255 
256         /* For monitor wait events */
257         union {
258             /* ei = EI_MONITOR_WAIT */
259             jlong timeout;
260             /* ei = EI_MONITOR_WAITED */
261             jboolean timed_out;
262         } monitor;
263     } u;
264 
265 } EventInfo;
266 
267 /* Structure to hold dynamic array of objects */
268 typedef struct ObjectBatch {
269     jobject *objects;
270     jint     count;
271 } ObjectBatch;
272 
273 /*
274  * Modifier flags for classes, fields, methods
275  */
276 #define MOD_PUBLIC       0x0001     /* visible to everyone */
277 #define MOD_PRIVATE      0x0002     /* visible only to the defining class */
278 #define MOD_PROTECTED    0x0004     /* visible to subclasses */
279 #define MOD_STATIC       0x0008     /* instance variable is static */
280 #define MOD_FINAL        0x0010     /* no further subclassing, overriding */
281 #define MOD_SYNCHRONIZED 0x0020     /* wrap method call in monitor lock */
282 #define MOD_VOLATILE     0x0040     /* can cache in registers */
283 #define MOD_TRANSIENT    0x0080     /* not persistant */
284 #define MOD_NATIVE       0x0100     /* implemented in C */
285 #define MOD_INTERFACE    0x0200     /* class is an interface */
286 #define MOD_ABSTRACT     0x0400     /* no definition provided */
287 /*
288  * Additional modifiers not defined as such in the JVM spec
289  */
290 #define MOD_SYNTHETIC    0xf0000000  /* not in source code */
291 
292 /*
293  * util funcs
294  */
295 void util_initialize(JNIEnv *env);
296 void util_reset(void);
297 
298 struct PacketInputStream;
299 struct PacketOutputStream;
300 
301 jint uniqueID(void);
302 jbyte referenceTypeTag(jclass clazz);
303 jbyte specificTypeKey(JNIEnv *env, jobject object);
304 jboolean isObjectTag(jbyte tag);
305 jvmtiError spawnNewThread(jvmtiStartFunction func, void *arg, char *name);
306 void writeCodeLocation(struct PacketOutputStream *out, jclass clazz,
307                        jmethodID method, jlocation location);
308 
309 jvmtiError classInstances(jclass klass, ObjectBatch *instances, int maxInstances);
310 jvmtiError classInstanceCounts(jint classCount, jclass *classes, jlong *counts);
311 jvmtiError objectReferrers(jobject obj, ObjectBatch *referrers, int maxObjects);
312 
313 /*
314  * Command handling helpers shared among multiple command sets
315  */
316 int filterDebugThreads(jthread *threads, int count);
317 
318 
319 void sharedGetFieldValues(struct PacketInputStream *in,
320                           struct PacketOutputStream *out,
321                           jboolean isStatic);
322 jboolean sharedInvoke(struct PacketInputStream *in,
323                       struct PacketOutputStream *out);
324 
325 jvmtiError fieldSignature(jclass, jfieldID, char **, char **, char **);
326 jvmtiError fieldModifiers(jclass, jfieldID, jint *);
327 jvmtiError methodSignature(jmethodID, char **, char **, char **);
328 jvmtiError methodReturnType(jmethodID, char *);
329 jvmtiError methodModifiers(jmethodID, jint *);
330 jvmtiError methodClass(jmethodID, jclass *);
331 jvmtiError methodLocation(jmethodID, jlocation*, jlocation*);
332 jvmtiError classLoader(jclass, jobject *);
333 
334 /*
335  * Thin wrappers on top of JNI
336  */
337 JNIEnv *getEnv(void);
338 jboolean isClass(jobject object);
339 jboolean isVThread(jobject object);
340 jboolean isThread(jobject object);
341 jboolean isThreadGroup(jobject object);
342 jboolean isString(jobject object);
343 jboolean isClassLoader(jobject object);
344 jboolean isArray(jobject object);
345 
346 /*
347  * Thin wrappers on top of JVMTI
348  */
349 jvmtiError jvmtiGetCapabilities(jvmtiCapabilities *caps);
350 jint jvmtiMajorVersion(void);
351 jint jvmtiMinorVersion(void);
352 jint jvmtiMicroVersion(void);
353 jvmtiError getSourceDebugExtension(jclass clazz, char **extensionPtr);
354 
355 jrawMonitorID debugMonitorCreate(char *name);
356 void debugMonitorEnter(jrawMonitorID theLock);
357 void debugMonitorExit(jrawMonitorID theLock);
358 void debugMonitorWait(jrawMonitorID theLock);
359 void debugMonitorTimedWait(jrawMonitorID theLock, jlong millis);
360 void debugMonitorNotify(jrawMonitorID theLock);
361 void debugMonitorNotifyAll(jrawMonitorID theLock);
362 void debugMonitorDestroy(jrawMonitorID theLock);
363 
364 jthread *allThreads(jint *count);
365 
366 void threadGroupInfo(jthreadGroup, jvmtiThreadGroupInfo *info);
367 
368 jclass findClass(JNIEnv *env, const char * name);
369 jmethodID getMethod(JNIEnv *env, jclass clazz, const char * name, const char *signature);
370 char *getModuleName(jclass);
371 char *getClassname(jclass);
372 jvmtiError classSignature(jclass, char**, char**);
373 jint classStatus(jclass);
374 void writeGenericSignature(struct PacketOutputStream *, char *);
375 jboolean isMethodNative(jmethodID);
376 jboolean isMethodObsolete(jmethodID);
377 jvmtiError isMethodSynthetic(jmethodID, jboolean*);
378 jvmtiError isFieldSynthetic(jclass, jfieldID, jboolean*);
379 
380 jboolean isSameObject(JNIEnv *env, jobject o1, jobject o2);
381 
382 jint objectHashCode(jobject);
383 
384 jvmtiError allInterfaces(jclass clazz, jclass **ppinterfaces, jint *count);
385 jvmtiError allLoadedClasses(jclass **ppclasses, jint *count);
386 jvmtiError allClassLoaderClasses(jobject loader, jclass **ppclasses, jint *count);
387 jvmtiError allNestedClasses(jclass clazz, jclass **ppnested, jint *pcount);
388 
389 void setAgentPropertyValue(JNIEnv *env, char *propertyName, char* propertyValue);
390 
391 void *jvmtiAllocate(jint numBytes);
392 void jvmtiDeallocate(void *buffer);
393 
394 void             eventIndexInit(void);
395 #ifdef DEBUG
396 char*            eventIndex2EventName(EventIndex ei);
397 #endif
398 jdwpEvent        eventIndex2jdwp(EventIndex i);
399 jvmtiEvent       eventIndex2jvmti(EventIndex i);
400 EventIndex       jdwp2EventIndex(jdwpEvent eventType);
401 EventIndex       jvmti2EventIndex(jvmtiEvent kind);
402 
403 jvmtiError       map2jvmtiError(jdwpError);
404 jdwpError        map2jdwpError(jvmtiError);
405 jdwpThreadStatus map2jdwpThreadStatus(jint state);
406 jint             map2jdwpSuspendStatus(jint state);
407 jint             map2jdwpClassStatus(jint);
408 
409 void log_debugee_location(const char *func,
410                 jthread thread, jmethodID method, jlocation location);
411 
412 /*
413  * Local Reference management. The two macros below are used
414  * throughout the back end whenever space for JNI local references
415  * is needed in the current frame.
416  */
417 
418 void createLocalRefSpace(JNIEnv *env, jint capacity);
419 
420 #define WITH_LOCAL_REFS(env, number) \
421     createLocalRefSpace(env, number); \
422     { /* BEGINNING OF WITH SCOPE */
423 
424 #define END_WITH_LOCAL_REFS(env) \
425         JNI_FUNC_PTR(env,PopLocalFrame)(env, NULL); \
426     } /* END OF WITH SCOPE */
427 
428 void saveGlobalRef(JNIEnv *env, jobject obj, jobject *pobj);
429 void tossGlobalRef(JNIEnv *env, jobject *pobj);
430 
431 jvmtiEnv* getSpecialJvmti(void);
432 
433 #endif