1 /*
   2  * Copyright (c) 1998, 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.  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 DEBUG
  36     /* Just to make sure these interfaces are not used here. */
  37     #undef free
  38     #define free(p) Do not use this interface.
  39     #undef malloc
  40     #define malloc(p) Do not use this interface.
  41     #undef calloc
  42     #define calloc(p) Do not use this interface.
  43     #undef realloc
  44     #define realloc(p) Do not use this interface.
  45     #undef strdup
  46     #define strdup(p) Do not use this interface.
  47 #endif
  48 
  49 #include "log_messages.h"
  50 #include "vm_interface.h"
  51 #include "JDWP.h"
  52 #include "util_md.h"
  53 #include "error_messages.h"
  54 #include "debugInit.h"
  55 
  56 /* Definition of a CommonRef tracked by the backend for the frontend */
  57 typedef struct RefNode {
  58     jlong        seqNum;        /* ID of reference, also key for hash table */
  59     jobject      ref;           /* could be strong or weak */
  60     struct RefNode *next;       /* next RefNode* in bucket chain */
  61     jint         count;         /* count of references */
  62     unsigned     isStrong : 1;  /* 1 means this is a string reference */
  63 } RefNode;
  64 
  65 /* Value of a NULL ID */
  66 #define NULL_OBJECT_ID  ((jlong)0)
  67 
  68 /*
  69  * Globals used throughout the back end
  70  */
  71 
  72 typedef jint FrameNumber;
  73 
  74 typedef struct {
  75     jvmtiEnv *jvmti;
  76     JavaVM   *jvm;
  77     volatile jboolean vmDead; /* Once VM is dead it stays that way - don't put in init */
  78     jboolean assertOn;
  79     jboolean assertFatal;
  80     jboolean fibersSupported;      /* If true, debugging support for fibers is enabled.*/
  81     jboolean notifyDebuggerOfAllFibers; /* If true, the debugger will be notified of all known fibers.
  82                                          * If false the debugger is only notified of fibers for which
  83                                          * certain events have been received. */
  84     jboolean doerrorexit;
  85     jboolean modifiedUtf8;
  86     jboolean quiet;
  87 
  88     jboolean ignoreEvents;
  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              fiberClass;
 100     jclass              threadClass;
 101     jclass              threadGroupClass;
 102     jclass              classLoaderClass;
 103     jclass              stringClass;
 104     jclass              systemClass;
 105     jclass              innocuousThreadClass; /* fibers fixme: get rid of once helper threads go away */
 106     jmethodID           fiberToString;
 107     jmethodID           fiberTryMountAndSuspend;
 108     jmethodID           threadConstructor;
 109     jmethodID           threadSetDaemon;
 110     jmethodID           threadResume;
 111     jmethodID           systemGetProperty;
 112     jmethodID           setProperty;
 113     jthreadGroup        systemThreadGroup;
 114     jthreadGroup        fiberThreadGroup;
 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     RefNode     **objectsByID;
 137     int           objectsByIDsize;
 138     int           objectsByIDcount;
 139 
 140      /* Indication that the agent has been loaded */
 141      jboolean isLoaded;
 142 
 143 } BackendGlobalData;
 144 
 145 extern BackendGlobalData * gdata;
 146 
 147 /*
 148  * Event Index for handlers
 149  */
 150 
 151 typedef enum {
 152         EI_min                  =  1,
 153 
 154         EI_SINGLE_STEP          =  1,
 155         EI_BREAKPOINT           =  2,
 156         EI_FRAME_POP            =  3,
 157         EI_EXCEPTION            =  4,
 158         EI_THREAD_START         =  5,
 159         EI_THREAD_END           =  6,
 160         EI_CLASS_PREPARE        =  7,
 161         EI_GC_FINISH            =  8,
 162         EI_CLASS_LOAD           =  9,
 163         EI_FIELD_ACCESS         = 10,
 164         EI_FIELD_MODIFICATION   = 11,
 165         EI_EXCEPTION_CATCH      = 12,
 166         EI_METHOD_ENTRY         = 13,
 167         EI_METHOD_EXIT          = 14,
 168         EI_MONITOR_CONTENDED_ENTER = 15,
 169         EI_MONITOR_CONTENDED_ENTERED = 16,
 170         EI_MONITOR_WAIT         = 17,
 171         EI_MONITOR_WAITED       = 18,
 172         EI_VM_INIT              = 19,
 173         EI_VM_DEATH             = 20,
 174         EI_FIBER_SCHEDULED      = 21,
 175         EI_FIBER_TERMINATED     = 22,
 176         EI_FIBER_MOUNT          = 23,
 177         EI_FIBER_UNMOUNT        = 24,
 178         EI_CONTINUATION_RUN     = 25,
 179         EI_CONTINUATION_YIELD   = 26,
 180 
 181         EI_max                  = 26
 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     jthread     fiber;        /* NULL if not running on a fiber. */
 223     jboolean    matchesFiber; /* true if the matching HandlerNode specified a fiber that matched,
 224                                  or the HandlerNode specified no thread and the event came in on a
 225                                  carrier thread running a fiber. */
 226     jclass      clazz;
 227     jmethodID   method;
 228     jlocation   location;
 229     jobject     object; /* possibly an exception or user object */
 230 
 231     union {
 232 
 233         /* ei = EI_FIELD_ACCESS */
 234         struct {
 235             jclass      field_clazz;
 236             jfieldID    field;
 237         } field_access;
 238 
 239         /* ei = EI_FIELD_MODIFICATION */
 240         struct {
 241             jclass      field_clazz;
 242             jfieldID    field;
 243             char        signature_type;
 244             jvalue      new_value;
 245         } field_modification;
 246 
 247         /* ei = EI_EXCEPTION */
 248         struct {
 249             jclass      catch_clazz;
 250             jmethodID   catch_method;
 251             jlocation   catch_location;
 252         } exception;
 253 
 254         /* ei = EI_METHOD_EXIT */
 255         struct {
 256             jvalue      return_value;
 257         } method_exit;
 258 
 259         /* For monitor wait events */
 260         union {
 261             /* ei = EI_MONITOR_WAIT */
 262             jlong timeout;
 263             /* ei = EI_MONITOR_WAITED */
 264             jboolean timed_out;
 265         } monitor;
 266     } u;
 267 
 268 } EventInfo;
 269 
 270 /* Structure to hold dynamic array of objects */
 271 typedef struct ObjectBatch {
 272     jobject *objects;
 273     jint     count;
 274 } ObjectBatch;
 275 
 276 /*
 277  * JNI signature constants, beyond those defined in JDWP_TAG(*)
 278  */
 279 #define SIGNATURE_BEGIN_ARGS    '('
 280 #define SIGNATURE_END_ARGS      ')'
 281 #define SIGNATURE_END_CLASS     ';'
 282 
 283 /*
 284  * Modifier flags for classes, fields, methods
 285  */
 286 #define MOD_PUBLIC       0x0001     /* visible to everyone */
 287 #define MOD_PRIVATE      0x0002     /* visible only to the defining class */
 288 #define MOD_PROTECTED    0x0004     /* visible to subclasses */
 289 #define MOD_STATIC       0x0008     /* instance variable is static */
 290 #define MOD_FINAL        0x0010     /* no further subclassing, overriding */
 291 #define MOD_SYNCHRONIZED 0x0020     /* wrap method call in monitor lock */
 292 #define MOD_VOLATILE     0x0040     /* can cache in registers */
 293 #define MOD_TRANSIENT    0x0080     /* not persistant */
 294 #define MOD_NATIVE       0x0100     /* implemented in C */
 295 #define MOD_INTERFACE    0x0200     /* class is an interface */
 296 #define MOD_ABSTRACT     0x0400     /* no definition provided */
 297 /*
 298  * Additional modifiers not defined as such in the JVM spec
 299  */
 300 #define MOD_SYNTHETIC    0xf0000000  /* not in source code */
 301 
 302 /*
 303  * util funcs
 304  */
 305 void util_initialize(JNIEnv *env);
 306 void util_reset(void);
 307 
 308 struct PacketInputStream;
 309 struct PacketOutputStream;
 310 
 311 jint uniqueID(void);
 312 jbyte referenceTypeTag(jclass clazz);
 313 jbyte specificTypeKey(JNIEnv *env, jobject object);
 314 jboolean isObjectTag(jbyte tag);
 315 jvmtiError spawnNewThread(jvmtiStartFunction func, void *arg, char *name);
 316 void convertSignatureToClassname(char *convert);
 317 void writeCodeLocation(struct PacketOutputStream *out, jclass clazz,
 318                        jmethodID method, jlocation location);
 319 
 320 jvmtiError classInstances(jclass klass, ObjectBatch *instances, int maxInstances);
 321 jvmtiError classInstanceCounts(jint classCount, jclass *classes, jlong *counts);
 322 jvmtiError objectReferrers(jobject obj, ObjectBatch *referrers, int maxObjects);
 323 
 324 /*
 325  * Command handling helpers shared among multiple command sets
 326  */
 327 int filterDebugThreads(jthread *threads, int count);
 328 
 329 
 330 void sharedGetFieldValues(struct PacketInputStream *in,
 331                           struct PacketOutputStream *out,
 332                           jboolean isStatic);
 333 jboolean sharedInvoke(struct PacketInputStream *in,
 334                       struct PacketOutputStream *out);
 335 
 336 jvmtiError fieldSignature(jclass, jfieldID, char **, char **, char **);
 337 jvmtiError fieldModifiers(jclass, jfieldID, jint *);
 338 jvmtiError methodSignature(jmethodID, char **, char **, char **);
 339 jvmtiError methodReturnType(jmethodID, char *);
 340 jvmtiError methodModifiers(jmethodID, jint *);
 341 jvmtiError methodClass(jmethodID, jclass *);
 342 jvmtiError methodLocation(jmethodID, jlocation*, jlocation*);
 343 jvmtiError classLoader(jclass, jobject *);
 344 
 345 /*
 346  * Thin wrappers on top of JNI
 347  */
 348 JNIEnv *getEnv(void);
 349 jboolean isClass(jobject object);
 350 jboolean isFiber(jobject object);
 351 jboolean isThread(jobject object);
 352 jboolean isThreadGroup(jobject object);
 353 jboolean isString(jobject object);
 354 jboolean isClassLoader(jobject object);
 355 jboolean isArray(jobject object);
 356 
 357 /*
 358  * Thin wrappers on top of JVMTI
 359  */
 360 jvmtiError jvmtiGetCapabilities(jvmtiCapabilities *caps);
 361 jint jvmtiMajorVersion(void);
 362 jint jvmtiMinorVersion(void);
 363 jint jvmtiMicroVersion(void);
 364 jvmtiError getSourceDebugExtension(jclass clazz, char **extensionPtr);
 365 jboolean canSuspendResumeThreadLists(void);
 366 
 367 jrawMonitorID debugMonitorCreate(char *name);
 368 void debugMonitorEnter(jrawMonitorID theLock);
 369 void debugMonitorExit(jrawMonitorID theLock);
 370 void debugMonitorWait(jrawMonitorID theLock);
 371 void debugMonitorTimedWait(jrawMonitorID theLock, jlong millis);
 372 void debugMonitorNotify(jrawMonitorID theLock);
 373 void debugMonitorNotifyAll(jrawMonitorID theLock);
 374 void debugMonitorDestroy(jrawMonitorID theLock);
 375 
 376 jthread *allThreads(jint *count);
 377 
 378 void threadGroupInfo(jthreadGroup, jvmtiThreadGroupInfo *info);
 379 
 380 jclass findClass(JNIEnv *env, const char * name);
 381 jmethodID getMethod(JNIEnv *env, jclass clazz, const char * name, const char *signature);
 382 char *getModuleName(jclass);
 383 char *getClassname(jclass);
 384 jvmtiError classSignature(jclass, char**, char**);
 385 jint classStatus(jclass);
 386 void writeGenericSignature(struct PacketOutputStream *, char *);
 387 jboolean isMethodNative(jmethodID);
 388 jboolean isMethodObsolete(jmethodID);
 389 jvmtiError isMethodSynthetic(jmethodID, jboolean*);
 390 jvmtiError isFieldSynthetic(jclass, jfieldID, jboolean*);
 391 
 392 jboolean isSameObject(JNIEnv *env, jobject o1, jobject o2);
 393 
 394 jthread  getThreadFiber(jthread thread);
 395 jthread  getFiberThread(jthread fiber);
 396 
 397 jint getThreadFrameCount(jthread thread);
 398 
 399 jint objectHashCode(jobject);
 400 
 401 jvmtiError allInterfaces(jclass clazz, jclass **ppinterfaces, jint *count);
 402 jvmtiError allLoadedClasses(jclass **ppclasses, jint *count);
 403 jvmtiError allClassLoaderClasses(jobject loader, jclass **ppclasses, jint *count);
 404 jvmtiError allNestedClasses(jclass clazz, jclass **ppnested, jint *pcount);
 405 
 406 void setAgentPropertyValue(JNIEnv *env, char *propertyName, char* propertyValue);
 407 
 408 void *jvmtiAllocate(jint numBytes);
 409 void jvmtiDeallocate(void *buffer);
 410 
 411 void             eventIndexInit(void);
 412 char*            eventIndex2EventName(EventIndex ei);
 413 jdwpEvent        eventIndex2jdwp(EventIndex i);
 414 jvmtiEvent       eventIndex2jvmti(EventIndex i);
 415 EventIndex       jdwp2EventIndex(jdwpEvent eventType);
 416 EventIndex       jvmti2EventIndex(jvmtiEvent kind);
 417 
 418 jvmtiError       map2jvmtiError(jdwpError);
 419 jdwpError        map2jdwpError(jvmtiError);
 420 jdwpThreadStatus map2jdwpThreadStatus(jint state);
 421 jint             map2jdwpSuspendStatus(jint state);
 422 jint             map2jdwpClassStatus(jint);
 423 
 424 void log_debugee_location(const char *func,
 425                 jthread thread, jmethodID method, jlocation location);
 426 
 427 /*
 428  * Local Reference management. The two macros below are used
 429  * throughout the back end whenever space for JNI local references
 430  * is needed in the current frame.
 431  */
 432 
 433 void createLocalRefSpace(JNIEnv *env, jint capacity);
 434 
 435 #define WITH_LOCAL_REFS(env, number) \
 436     createLocalRefSpace(env, number); \
 437     { /* BEGINNING OF WITH SCOPE */
 438 
 439 #define END_WITH_LOCAL_REFS(env) \
 440         JNI_FUNC_PTR(env,PopLocalFrame)(env, NULL); \
 441     } /* END OF WITH SCOPE */
 442 
 443 void saveGlobalRef(JNIEnv *env, jobject obj, jobject *pobj);
 444 void tossGlobalRef(JNIEnv *env, jobject *pobj);
 445 
 446 #endif