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