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