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 #include <ctype.h>
  27 
  28 #include "util.h"
  29 #include "commonRef.h"
  30 #include "debugDispatch.h"
  31 #include "eventHandler.h"
  32 #include "eventHelper.h"
  33 #include "threadControl.h"
  34 #include "stepControl.h"
  35 #include "transport.h"
  36 #include "classTrack.h"
  37 #include "debugLoop.h"
  38 #include "bag.h"
  39 #include "invoker.h"
  40 #include "sys.h"
  41 
  42 /* How the options get to OnLoad: */
  43 #define XDEBUG "-Xdebug"
  44 #define XRUN "-Xrunjdwp"
  45 #define AGENTLIB "-agentlib:jdwp"
  46 
  47 /* Debug version defaults */
  48 #ifdef DEBUG
  49     #define DEFAULT_ASSERT_ON           JNI_TRUE
  50     #define DEFAULT_ASSERT_FATAL        JNI_TRUE
  51     #define DEFAULT_LOGFILE             "jdwp.log"
  52 #else
  53     #define DEFAULT_ASSERT_ON           JNI_FALSE
  54     #define DEFAULT_ASSERT_FATAL        JNI_FALSE
  55     #define DEFAULT_LOGFILE             NULL
  56 #endif
  57 
  58 static jboolean vmInitialized;
  59 static jrawMonitorID initMonitor;
  60 static jboolean initComplete;
  61 static jbyte currentSessionID;
  62 
  63 /*
  64  * Options set through the OnLoad options string. All of these values
  65  * are set once at VM startup and never reset.
  66  */
  67 static jboolean isServer = JNI_FALSE;     /* Listens for connecting debuggers? */
  68 static jboolean isStrict = JNI_FALSE;     /* Unused */
  69 static jboolean useStandardAlloc = JNI_FALSE;  /* Use standard malloc/free? */
  70 static struct bag *transports;            /* of TransportSpec */
  71 
  72 static jboolean initOnStartup = JNI_TRUE;   /* init immediately */
  73 static char *initOnException = NULL;        /* init when this exception thrown */
  74 static jboolean initOnUncaught = JNI_FALSE; /* init when uncaught exc thrown */
  75 
  76 static char *launchOnInit = NULL;           /* launch this app during init */
  77 static jboolean suspendOnInit = JNI_TRUE;   /* suspend all app threads after init */
  78 static jboolean dopause = JNI_FALSE;        /* pause for debugger attach */
  79 static jboolean docoredump = JNI_FALSE;     /* core dump on exit */
  80 static char *logfile = NULL;                /* Name of logfile (if logging) */
  81 static unsigned logflags = 0;               /* Log flags */
  82 
  83 static char *names;                         /* strings derived from OnLoad options */
  84 
  85 static jboolean allowStartViaJcmd = JNI_FALSE;  /* if true we allow the debugging to be started via a jcmd */
  86 static jboolean startedViaJcmd = JNI_FALSE;     /* if false, we have not yet started debugging via a jcmd */
  87 
  88 /*
  89  * Elements of the transports bag
  90  */
  91 typedef struct TransportSpec {
  92     char *name;
  93     char *address;
  94     long timeout;
  95     char *allow;
  96 } TransportSpec;
  97 
  98 /*
  99  * Forward Refs
 100  */
 101 static void JNICALL cbEarlyVMInit(jvmtiEnv*, JNIEnv *, jthread);
 102 static void JNICALL cbEarlyVMDeath(jvmtiEnv*, JNIEnv *);
 103 static void JNICALL cbEarlyException(jvmtiEnv*, JNIEnv *,
 104             jthread, jmethodID, jlocation, jobject, jmethodID, jlocation);
 105 
 106 static void initialize(JNIEnv *env, jthread thread, EventIndex triggering_ei);
 107 static jboolean parseOptions(char *str);
 108 
 109 /*
 110  * Phase 1: Initial load.
 111  *
 112  * OnLoad is called by the VM immediately after the back-end
 113  * library is loaded. We can do very little in this function since
 114  * the VM has not completed initialization. So, we parse the JDWP
 115  * options and set up a simple initial event callbacks for JVMTI events.
 116  * When a triggering event occurs, that callback will begin debugger initialization.
 117  */
 118 
 119 /* Get a static area to hold the Global Data */
 120 static BackendGlobalData *
 121 get_gdata(void)
 122 {
 123     static BackendGlobalData s;
 124     (void)memset(&s, 0, sizeof(BackendGlobalData));
 125     return &s;
 126 }
 127 
 128 static jvmtiError
 129 set_event_notification(jvmtiEventMode mode, EventIndex ei)
 130 {
 131     jvmtiError error;
 132     error = JVMTI_FUNC_PTR(gdata->jvmti,SetEventNotificationMode)
 133                 (gdata->jvmti, mode, eventIndex2jvmti(ei), NULL);
 134     if (error != JVMTI_ERROR_NONE) {
 135         ERROR_MESSAGE(("JDWP unable to configure initial JVMTI event %s: %s(%d)",
 136                     eventText(ei), jvmtiErrorText(error), error));
 137     }
 138     return error;
 139 }
 140 
 141 typedef struct {
 142     int major;
 143     int minor;
 144 } version_type;
 145 
 146 typedef struct {
 147     version_type runtime;
 148     version_type compiletime;
 149 } compatible_versions_type;
 150 
 151 /*
 152  * List of explicitly compatible JVMTI versions, specified as
 153  * { runtime version, compile-time version } pairs. -1 is a wildcard.
 154  */
 155 static int nof_compatible_versions = 3;
 156 static compatible_versions_type compatible_versions_list[] = {
 157     /*
 158      * FIXUP: Allow version 0 to be compatible with anything
 159      * Special check for FCS of 1.0.
 160      */
 161     { {  0, -1 }, { -1, -1 } },
 162     { { -1, -1 }, {  0, -1 } },
 163     /*
 164      * 1.2 is runtime compatible with 1.1 -- just make sure to check the
 165      * version before using any new 1.2 features
 166      */
 167     { {  1,  1 }, {  1,  2 } }
 168 };
 169 
 170 
 171 /* Logic to determine JVMTI version compatibility */
 172 static jboolean
 173 compatible_versions(jint major_runtime,     jint minor_runtime,
 174                     jint major_compiletime, jint minor_compiletime)
 175 {
 176     /*
 177      * First check to see if versions are explicitly compatible via the
 178      * list specified above.
 179      */
 180     int i;
 181     for (i = 0; i < nof_compatible_versions; ++i) {
 182         version_type runtime = compatible_versions_list[i].runtime;
 183         version_type comptime = compatible_versions_list[i].compiletime;
 184 
 185         if ((major_runtime     == runtime.major  || runtime.major  == -1) &&
 186             (minor_runtime     == runtime.minor  || runtime.minor  == -1) &&
 187             (major_compiletime == comptime.major || comptime.major == -1) &&
 188             (minor_compiletime == comptime.minor || comptime.minor == -1)) {
 189             return JNI_TRUE;
 190         }
 191     }
 192 
 193     return major_runtime == major_compiletime &&
 194            minor_runtime >= minor_compiletime;
 195 }
 196 
 197 /* OnLoad startup:
 198  *   Returning JNI_ERR will cause the java_g VM to core dump, be careful.
 199  */
 200 JNIEXPORT jint JNICALL
 201 DEF_Agent_OnLoad(JavaVM *vm, char *options, void *reserved)
 202 {
 203     jvmtiError error;
 204     jvmtiCapabilities needed_capabilities;
 205     jvmtiCapabilities potential_capabilities;
 206     jint              jvmtiCompileTimeMajorVersion;
 207     jint              jvmtiCompileTimeMinorVersion;
 208     jint              jvmtiCompileTimeMicroVersion;
 209 
 210     /* See if it's already loaded */
 211     if ( gdata!=NULL && gdata->isLoaded==JNI_TRUE ) {
 212         ERROR_MESSAGE(("Cannot load this JVM TI agent twice, check your java command line for duplicate jdwp options."));
 213         return JNI_ERR;
 214     }
 215 
 216     /* If gdata is defined and the VM died, why are we here? */
 217     if ( gdata!=NULL && gdata->vmDead ) {
 218         ERROR_MESSAGE(("JDWP unable to load, VM died"));
 219         return JNI_ERR;
 220     }
 221 
 222     /* Get global data area */
 223     gdata = get_gdata();
 224     if (gdata == NULL) {
 225         ERROR_MESSAGE(("JDWP unable to allocate memory"));
 226         return JNI_ERR;
 227     }
 228     gdata->isLoaded = JNI_TRUE;
 229 
 230     /* Start filling in gdata */
 231     gdata->jvm = vm;
 232     vmInitialized = JNI_FALSE;
 233     gdata->vmDead = JNI_FALSE;
 234 
 235     /* Get the JVMTI Env, IMPORTANT: Do this first! For jvmtiAllocate(). */
 236     error = JVM_FUNC_PTR(vm,GetEnv)
 237                 (vm, (void **)&(gdata->jvmti), JVMTI_VERSION_1);
 238     if (error != JNI_OK) {
 239         ERROR_MESSAGE(("JDWP unable to access JVMTI Version 1 (0x%x),"
 240                          " is your J2SE a 1.5 or newer version?"
 241                          " JNIEnv's GetEnv() returned %d",
 242                          JVMTI_VERSION_1, error));
 243         forceExit(1); /* Kill entire process, no core dump */
 244     }
 245 
 246     /* Check to make sure the version of jvmti.h we compiled with
 247      *      matches the runtime version we are using.
 248      */
 249     jvmtiCompileTimeMajorVersion  = ( JVMTI_VERSION & JVMTI_VERSION_MASK_MAJOR )
 250                                         >> JVMTI_VERSION_SHIFT_MAJOR;
 251     jvmtiCompileTimeMinorVersion  = ( JVMTI_VERSION & JVMTI_VERSION_MASK_MINOR )
 252                                         >> JVMTI_VERSION_SHIFT_MINOR;
 253     jvmtiCompileTimeMicroVersion  = ( JVMTI_VERSION & JVMTI_VERSION_MASK_MICRO )
 254                                         >> JVMTI_VERSION_SHIFT_MICRO;
 255 
 256     /* Check for compatibility */
 257     if ( !compatible_versions(jvmtiMajorVersion(), jvmtiMinorVersion(),
 258                 jvmtiCompileTimeMajorVersion, jvmtiCompileTimeMinorVersion) ) {
 259 
 260         ERROR_MESSAGE(("This jdwp native library will not work with this VM's "
 261                        "version of JVMTI (%d.%d.%d), it needs JVMTI %d.%d[.%d].",
 262                        jvmtiMajorVersion(),
 263                        jvmtiMinorVersion(),
 264                        jvmtiMicroVersion(),
 265                        jvmtiCompileTimeMajorVersion,
 266                        jvmtiCompileTimeMinorVersion,
 267                        jvmtiCompileTimeMicroVersion));
 268 
 269         /* Do not let VM get a fatal error, we don't want a core dump here. */
 270         forceExit(1); /* Kill entire process, no core dump wanted */
 271     }
 272 
 273     /* Parse input options */
 274     if (!parseOptions(options)) {
 275         /* No message necessary, should have been printed out already */
 276         /* Do not let VM get a fatal error, we don't want a core dump here. */
 277         forceExit(1); /* Kill entire process, no core dump wanted */
 278     }
 279 
 280     LOG_MISC(("Onload: %s", options));
 281 
 282     /* Get potential capabilities */
 283     (void)memset(&potential_capabilities,0,sizeof(potential_capabilities));
 284     error = JVMTI_FUNC_PTR(gdata->jvmti,GetPotentialCapabilities)
 285                 (gdata->jvmti, &potential_capabilities);
 286     if (error != JVMTI_ERROR_NONE) {
 287         ERROR_MESSAGE(("JDWP unable to get potential JVMTI capabilities: %s(%d)",
 288                         jvmtiErrorText(error), error));
 289         return JNI_ERR;
 290     }
 291 
 292     /* Fill in ones that we must have */
 293     (void)memset(&needed_capabilities,0,sizeof(needed_capabilities));
 294     needed_capabilities.can_access_local_variables              = 1;
 295     needed_capabilities.can_generate_single_step_events         = 1;
 296     needed_capabilities.can_generate_exception_events           = 1;
 297     needed_capabilities.can_generate_frame_pop_events           = 1;
 298     needed_capabilities.can_generate_breakpoint_events          = 1;
 299     needed_capabilities.can_suspend                             = 1;
 300     needed_capabilities.can_generate_method_entry_events        = 1;
 301     needed_capabilities.can_generate_method_exit_events         = 1;
 302     needed_capabilities.can_generate_garbage_collection_events  = 1;
 303     needed_capabilities.can_maintain_original_method_order      = 1;
 304     needed_capabilities.can_generate_monitor_events             = 1;
 305     needed_capabilities.can_tag_objects                         = 1;
 306     needed_capabilities.can_support_fibers                      = 1;
 307     needed_capabilities.can_support_continuations               = 1;
 308 
 309     /* And what potential ones that would be nice to have */
 310     needed_capabilities.can_force_early_return
 311                 = potential_capabilities.can_force_early_return;
 312     needed_capabilities.can_generate_field_modification_events
 313                 = potential_capabilities.can_generate_field_modification_events;
 314     needed_capabilities.can_generate_field_access_events
 315                 = potential_capabilities.can_generate_field_access_events;
 316     needed_capabilities.can_get_bytecodes
 317                 = potential_capabilities.can_get_bytecodes;
 318     needed_capabilities.can_get_synthetic_attribute
 319                 = potential_capabilities.can_get_synthetic_attribute;
 320     needed_capabilities.can_get_owned_monitor_info
 321                 = potential_capabilities.can_get_owned_monitor_info;
 322     needed_capabilities.can_get_current_contended_monitor
 323                 = potential_capabilities.can_get_current_contended_monitor;
 324     needed_capabilities.can_get_monitor_info
 325                 = potential_capabilities.can_get_monitor_info;
 326     needed_capabilities.can_pop_frame
 327                 = potential_capabilities.can_pop_frame;
 328     needed_capabilities.can_redefine_classes
 329                 = potential_capabilities.can_redefine_classes;
 330     needed_capabilities.can_redefine_any_class
 331                 = potential_capabilities.can_redefine_any_class;
 332     needed_capabilities.can_get_owned_monitor_stack_depth_info
 333         = potential_capabilities.can_get_owned_monitor_stack_depth_info;
 334     needed_capabilities.can_get_constant_pool
 335                 = potential_capabilities.can_get_constant_pool;
 336     {
 337         needed_capabilities.can_get_source_debug_extension      = 1;
 338         needed_capabilities.can_get_source_file_name            = 1;
 339         needed_capabilities.can_get_line_numbers                = 1;
 340         needed_capabilities.can_signal_thread
 341                 = potential_capabilities.can_signal_thread;
 342     }
 343 
 344     /* Add the capabilities */
 345     error = JVMTI_FUNC_PTR(gdata->jvmti,AddCapabilities)
 346                 (gdata->jvmti, &needed_capabilities);
 347     if (error != JVMTI_ERROR_NONE) {
 348         ERROR_MESSAGE(("JDWP unable to get necessary JVMTI capabilities."));
 349         forceExit(1); /* Kill entire process, no core dump wanted */
 350     }
 351 
 352     /* Initialize event number mapping tables */
 353     eventIndexInit();
 354 
 355     /* Set the initial JVMTI event notifications */
 356     error = set_event_notification(JVMTI_ENABLE, EI_VM_DEATH);
 357     if (error != JVMTI_ERROR_NONE) {
 358         return JNI_ERR;
 359     }
 360     error = set_event_notification(JVMTI_ENABLE, EI_VM_INIT);
 361     if (error != JVMTI_ERROR_NONE) {
 362         return JNI_ERR;
 363     }
 364     if (initOnUncaught || (initOnException != NULL)) {
 365         error = set_event_notification(JVMTI_ENABLE, EI_EXCEPTION);
 366         if (error != JVMTI_ERROR_NONE) {
 367             return JNI_ERR;
 368         }
 369     }
 370 
 371     /* Set callbacks just for 3 functions */
 372     (void)memset(&(gdata->callbacks),0,sizeof(gdata->callbacks));
 373     gdata->callbacks.VMInit             = &cbEarlyVMInit;
 374     gdata->callbacks.VMDeath            = &cbEarlyVMDeath;
 375     gdata->callbacks.Exception  = &cbEarlyException;
 376     error = JVMTI_FUNC_PTR(gdata->jvmti,SetEventCallbacks)
 377                 (gdata->jvmti, &(gdata->callbacks), sizeof(gdata->callbacks));
 378     if (error != JVMTI_ERROR_NONE) {
 379         ERROR_MESSAGE(("JDWP unable to set JVMTI event callbacks: %s(%d)",
 380                         jvmtiErrorText(error), error));
 381         return JNI_ERR;
 382     }
 383 
 384     LOG_MISC(("OnLoad: DONE"));
 385     return JNI_OK;
 386 }
 387 
 388 JNIEXPORT void JNICALL
 389 DEF_Agent_OnUnload(JavaVM *vm)
 390 {
 391 
 392     gdata->isLoaded = JNI_FALSE;
 393 
 394     /* Cleanup, but make sure VM is alive before using JNI, and
 395      *   make sure JVMTI environment is ok before deallocating
 396      *   memory allocated through JVMTI, which all of it is.
 397      */
 398 
 399     /*
 400      * Close transport before exit
 401      */
 402     if (transport_is_open()) {
 403         transport_close();
 404     }
 405 }
 406 
 407 /*
 408  * Phase 2: Initial events. Phase 2 consists of waiting for the
 409  * event that triggers full initialization. Under normal circumstances
 410  * (initOnStartup == TRUE) this is the JVMTI_EVENT_VM_INIT event.
 411  * Otherwise, we delay initialization until the app throws a
 412  * particular exception. The triggering event invokes
 413  * the bulk of the initialization, including creation of threads and
 414  * monitors, transport setup, and installation of a new event callback which
 415  * handles the complete set of events.
 416  *
 417  * Since the triggering event comes in on an application thread, some of the
 418  * initialization is difficult to do here. Specifically, this thread along
 419  * with all other app threads may need to be suspended until a debugger
 420  * connects. These kinds of tasks are left to the third phase which is
 421  * invoked by one of the spawned debugger threads, the event handler.
 422  */
 423 
 424 /*
 425  * Wait for a triggering event; then kick off debugger
 426  * initialization. A different event callback will be installed by
 427  * debugger initialization, and this function will not be called
 428  * again.
 429  */
 430 
 431     /*
 432      * TO DO: Decide whether we need to protect this code with
 433      * a lock. It might be too early to create a monitor safely (?).
 434      */
 435 
 436 static void JNICALL
 437 cbEarlyVMInit(jvmtiEnv *jvmti_env, JNIEnv *env, jthread thread)
 438 {
 439     LOG_CB(("cbEarlyVMInit"));
 440     if ( gdata->vmDead ) {
 441         EXIT_ERROR(AGENT_ERROR_INTERNAL,"VM dead at VM_INIT time");
 442     }
 443     if (initOnStartup)
 444         initialize(env, thread, EI_VM_INIT);
 445     vmInitialized = JNI_TRUE;
 446     LOG_MISC(("END cbEarlyVMInit"));
 447 }
 448 
 449 static void
 450 disposeEnvironment(jvmtiEnv *jvmti_env)
 451 {
 452     jvmtiError error;
 453 
 454     error = JVMTI_FUNC_PTR(jvmti_env,DisposeEnvironment)(jvmti_env);
 455     if ( error == JVMTI_ERROR_MUST_POSSESS_CAPABILITY )
 456         error = JVMTI_ERROR_NONE;  /* Hack!  FIXUP when JVMTI has disposeEnv */
 457     /* What should error return say? */
 458     if (error != JVMTI_ERROR_NONE) {
 459         ERROR_MESSAGE(("JDWP unable to dispose of JVMTI environment: %s(%d)",
 460                         jvmtiErrorText(error), error));
 461     }
 462     gdata->jvmti = NULL;
 463 }
 464 
 465 static void JNICALL
 466 cbEarlyVMDeath(jvmtiEnv *jvmti_env, JNIEnv *env)
 467 {
 468     LOG_CB(("cbEarlyVMDeath"));
 469     if ( gdata->vmDead ) {
 470         EXIT_ERROR(AGENT_ERROR_INTERNAL,"VM died more than once");
 471     }
 472     disposeEnvironment(jvmti_env);
 473     gdata->jvmti = NULL;
 474     gdata->jvm = NULL;
 475     gdata->vmDead = JNI_TRUE;
 476     LOG_MISC(("END cbEarlyVMDeath"));
 477 }
 478 
 479 static void JNICALL
 480 cbEarlyException(jvmtiEnv *jvmti_env, JNIEnv *env,
 481         jthread thread, jmethodID method, jlocation location,
 482         jobject exception,
 483         jmethodID catch_method, jlocation catch_location)
 484 {
 485     jvmtiError error;
 486     jthrowable currentException;
 487 
 488     LOG_CB(("cbEarlyException: thread=%p", thread));
 489 
 490     if ( gdata->vmDead ) {
 491         EXIT_ERROR(AGENT_ERROR_INTERNAL,"VM dead at initial Exception event");
 492     }
 493     if (!vmInitialized)  {
 494         LOG_MISC(("VM is not initialized yet"));
 495         return;
 496     }
 497 
 498     /*
 499      * We want to preserve any current exception that might get wiped
 500      * out during event handling (e.g. JNI calls). We have to rely on
 501      * space for the local reference on the current frame because
 502      * doing a PushLocalFrame here might itself generate an exception.
 503      */
 504 
 505     currentException = JNI_FUNC_PTR(env,ExceptionOccurred)(env);
 506     JNI_FUNC_PTR(env,ExceptionClear)(env);
 507 
 508     if (initOnUncaught && catch_method == NULL) {
 509 
 510         LOG_MISC(("Initializing on uncaught exception"));
 511         initialize(env, thread, EI_EXCEPTION);
 512 
 513     } else if (initOnException != NULL) {
 514 
 515         jclass clazz;
 516 
 517         /* Get class of exception thrown */
 518         clazz = JNI_FUNC_PTR(env,GetObjectClass)(env, exception);
 519         if ( clazz != NULL ) {
 520             char *signature = NULL;
 521             /* initing on throw, check */
 522             error = classSignature(clazz, &signature, NULL);
 523             LOG_MISC(("Checking specific exception: looking for %s, got %s",
 524                         initOnException, signature));
 525             if ( (error==JVMTI_ERROR_NONE) &&
 526                 (strcmp(signature, initOnException) == 0)) {
 527                 LOG_MISC(("Initializing on specific exception"));
 528                 initialize(env, thread, EI_EXCEPTION);
 529             } else {
 530                 error = AGENT_ERROR_INTERNAL; /* Just to cause restore */
 531             }
 532             if ( signature != NULL ) {
 533                 jvmtiDeallocate(signature);
 534             }
 535         } else {
 536             error = AGENT_ERROR_INTERNAL; /* Just to cause restore */
 537         }
 538 
 539         /* If initialize didn't happen, we need to restore things */
 540         if ( error != JVMTI_ERROR_NONE ) {
 541             /*
 542              * Restore exception state from before callback call
 543              */
 544             LOG_MISC(("No initialization, didn't find right exception"));
 545             if (currentException != NULL) {
 546                 JNI_FUNC_PTR(env,Throw)(env, currentException);
 547             } else {
 548                 JNI_FUNC_PTR(env,ExceptionClear)(env);
 549             }
 550         }
 551 
 552     }
 553 
 554     LOG_MISC(("END cbEarlyException"));
 555 
 556 }
 557 
 558 typedef struct EnumerateArg {
 559     jboolean isServer;
 560     jdwpError error;
 561     jint startCount;
 562 } EnumerateArg;
 563 
 564 static jboolean
 565 startTransport(void *item, void *arg)
 566 {
 567     TransportSpec *transport = item;
 568     EnumerateArg *enumArg = arg;
 569     jdwpError serror;
 570 
 571     LOG_MISC(("Begin startTransport"));
 572     serror = transport_startTransport(enumArg->isServer, transport->name,
 573                                       transport->address, transport->timeout,
 574                                       transport->allow);
 575     if (serror != JDWP_ERROR(NONE)) {
 576         ERROR_MESSAGE(("JDWP Transport %s failed to initialize, %s(%d)",
 577                 transport->name, jdwpErrorText(serror), serror));
 578         enumArg->error = serror;
 579     } else {
 580         /* (Don't overwrite any previous error) */
 581 
 582         enumArg->startCount++;
 583     }
 584 
 585     LOG_MISC(("End startTransport"));
 586 
 587     return JNI_TRUE;   /* Always continue, even if there was an error */
 588 }
 589 
 590 static void
 591 signalInitComplete(void)
 592 {
 593     /*
 594      * Initialization is complete
 595      */
 596     LOG_MISC(("signal initialization complete"));
 597     debugMonitorEnter(initMonitor);
 598     initComplete = JNI_TRUE;
 599     debugMonitorNotifyAll(initMonitor);
 600     debugMonitorExit(initMonitor);
 601 }
 602 
 603 /*
 604  * Determine if  initialization is complete.
 605  */
 606 jboolean
 607 debugInit_isInitComplete(void)
 608 {
 609     return initComplete;
 610 }
 611 
 612 /*
 613  * Wait for all initialization to complete.
 614  */
 615 void
 616 debugInit_waitInitComplete(void)
 617 {
 618     debugMonitorEnter(initMonitor);
 619     while (!initComplete) {
 620         debugMonitorWait(initMonitor);
 621     }
 622     debugMonitorExit(initMonitor);
 623 }
 624 
 625 /* All process exit() calls come from here */
 626 void
 627 forceExit(int exit_code)
 628 {
 629     /* make sure the transport is closed down before we exit() */
 630     transport_close();
 631     exit(exit_code);
 632 }
 633 
 634 /* All JVM fatal error exits lead here (e.g. we need to kill the VM). */
 635 static void
 636 jniFatalError(JNIEnv *env, const char *msg, jvmtiError error, int exit_code)
 637 {
 638     JavaVM *vm;
 639     char buf[512];
 640 
 641     gdata->vmDead = JNI_TRUE;
 642     if ( msg==NULL )
 643         msg = "UNKNOWN REASON";
 644     vm = gdata->jvm;
 645     if ( env==NULL && vm!=NULL ) {
 646         jint rc = (*((*vm)->GetEnv))(vm, (void **)&env, JNI_VERSION_1_2);
 647         if (rc != JNI_OK ) {
 648             env = NULL;
 649         }
 650     }
 651     if ( error != JVMTI_ERROR_NONE ) {
 652         (void)snprintf(buf, sizeof(buf), "JDWP %s, jvmtiError=%s(%d)",
 653                     msg, jvmtiErrorText(error), error);
 654     } else {
 655         (void)snprintf(buf, sizeof(buf), "JDWP %s", msg);
 656     }
 657     if (env != NULL) {
 658         (*((*env)->FatalError))(env, buf);
 659     } else {
 660         /* Should rarely ever reach here, means VM is really dead */
 661         print_message(stderr, "ERROR: JDWP: ", "\n",
 662                 "Can't call JNI FatalError(NULL, \"%s\")", buf);
 663     }
 664     forceExit(exit_code);
 665 }
 666 
 667 /*
 668  * Initialize debugger back end modules
 669  */
 670 static void
 671 initialize(JNIEnv *env, jthread thread, EventIndex triggering_ei)
 672 {
 673     jvmtiError error;
 674     EnumerateArg arg;
 675     jbyte suspendPolicy;
 676 
 677     LOG_MISC(("Begin initialize()"));
 678     currentSessionID = 0;
 679     initComplete = JNI_FALSE;
 680 
 681     if ( gdata->vmDead ) {
 682         EXIT_ERROR(AGENT_ERROR_INTERNAL,"VM dead at initialize() time");
 683     }
 684 
 685     /* Turn off the initial JVMTI event notifications */
 686     error = set_event_notification(JVMTI_DISABLE, EI_EXCEPTION);
 687     if (error != JVMTI_ERROR_NONE) {
 688         EXIT_ERROR(error, "unable to disable JVMTI event notification");
 689     }
 690     error = set_event_notification(JVMTI_DISABLE, EI_VM_INIT);
 691     if (error != JVMTI_ERROR_NONE) {
 692         EXIT_ERROR(error, "unable to disable JVMTI event notification");
 693     }
 694     error = set_event_notification(JVMTI_DISABLE, EI_VM_DEATH);
 695     if (error != JVMTI_ERROR_NONE) {
 696         EXIT_ERROR(error, "unable to disable JVMTI event notification");
 697     }
 698 
 699     /* Remove initial event callbacks */
 700     (void)memset(&(gdata->callbacks),0,sizeof(gdata->callbacks));
 701     error = JVMTI_FUNC_PTR(gdata->jvmti,SetEventCallbacks)
 702                 (gdata->jvmti, &(gdata->callbacks), sizeof(gdata->callbacks));
 703     if (error != JVMTI_ERROR_NONE) {
 704         EXIT_ERROR(error, "unable to clear JVMTI callbacks");
 705     }
 706 
 707     commonRef_initialize();
 708     util_initialize(env);
 709     threadControl_initialize();
 710     stepControl_initialize();
 711     invoker_initialize();
 712     debugDispatch_initialize();
 713     classTrack_initialize(env);
 714     debugLoop_initialize();
 715 
 716     initMonitor = debugMonitorCreate("JDWP Initialization Monitor");
 717 
 718 
 719     /*
 720      * Initialize transports
 721      */
 722     arg.isServer = isServer;
 723     arg.error = JDWP_ERROR(NONE);
 724     arg.startCount = 0;
 725 
 726     transport_initialize();
 727     (void)bagEnumerateOver(transports, startTransport, &arg);
 728 
 729     /*
 730      * Exit with an error only if
 731      * 1) none of the transports was successfully started, and
 732      * 2) the application has not yet started running
 733      */
 734     if ((arg.error != JDWP_ERROR(NONE)) &&
 735         (arg.startCount == 0) &&
 736         initOnStartup) {
 737         EXIT_ERROR(map2jvmtiError(arg.error), "No transports initialized");
 738     }
 739 
 740     eventHandler_initialize(currentSessionID);
 741 
 742     signalInitComplete();
 743 
 744     transport_waitForConnection();
 745 
 746     suspendPolicy = suspendOnInit ? JDWP_SUSPEND_POLICY(ALL)
 747                                   : JDWP_SUSPEND_POLICY(NONE);
 748     if (triggering_ei == EI_VM_INIT) {
 749         LOG_MISC(("triggering_ei == EI_VM_INIT"));
 750         eventHelper_reportVMInit(env, currentSessionID, thread, suspendPolicy);
 751     } else {
 752         /*
 753          * TO DO: Kludgy way of getting the triggering event to the
 754          * just-attached debugger. It would be nice to make this a little
 755          * cleaner. There is also a race condition where other events
 756          * can get in the queue (from other not-yet-suspended threads)
 757          * before this one does. (Also need to handle allocation error below?)
 758          */
 759         EventInfo info;
 760         struct bag *initEventBag;
 761         LOG_MISC(("triggering_ei != EI_VM_INIT"));
 762         initEventBag = eventHelper_createEventBag();
 763         (void)memset(&info,0,sizeof(info));
 764         info.ei = triggering_ei;
 765         eventHelper_recordEvent(&info, 0, suspendPolicy, initEventBag);
 766         (void)eventHelper_reportEvents(currentSessionID, initEventBag);
 767         bagDestroyBag(initEventBag);
 768     }
 769 
 770     if ( gdata->vmDead ) {
 771         EXIT_ERROR(AGENT_ERROR_INTERNAL,"VM dead before initialize() completes");
 772     }
 773     LOG_MISC(("End initialize()"));
 774 }
 775 
 776 /*
 777  * Restore all static data to the initialized state so that another
 778  * debugger can connect properly later.
 779  */
 780 void
 781 debugInit_reset(JNIEnv *env)
 782 {
 783     EnumerateArg arg;
 784 
 785     LOG_MISC(("debugInit_reset() beginning"));
 786 
 787     currentSessionID++;
 788     initComplete = JNI_FALSE;
 789 
 790     eventHandler_reset(currentSessionID);
 791     transport_reset();
 792     debugDispatch_reset();
 793     invoker_reset();
 794     stepControl_reset();
 795     threadControl_reset();
 796     util_reset();
 797     commonRef_reset(env);
 798     classTrack_reset();
 799 
 800     /*
 801      * If this is a server, we are now ready to accept another connection.
 802      * If it's a client, then we've cleaned up some (more should be added
 803      * later) and we're done.
 804      */
 805     if (isServer) {
 806         arg.isServer = JNI_TRUE;
 807         arg.error = JDWP_ERROR(NONE);
 808         arg.startCount = 0;
 809         (void)bagEnumerateOver(transports, startTransport, &arg);
 810 
 811         signalInitComplete();
 812 
 813         transport_waitForConnection();
 814     } else {
 815         signalInitComplete(); /* Why? */
 816     }
 817 
 818     LOG_MISC(("debugInit_reset() completed."));
 819 }
 820 
 821 
 822 char *
 823 debugInit_launchOnInit(void)
 824 {
 825     return launchOnInit;
 826 }
 827 
 828 jboolean
 829 debugInit_suspendOnInit(void)
 830 {
 831     return suspendOnInit;
 832 }
 833 
 834 /*
 835  * code below is shamelessly swiped from hprof.
 836  */
 837 
 838 static int
 839 get_tok(char **src, char *buf, int buflen, char sep)
 840 {
 841     int i;
 842     char *p = *src;
 843     for (i = 0; i < buflen; i++) {
 844         if (p[i] == 0 || p[i] == sep) {
 845             buf[i] = 0;
 846             if (p[i] == sep) {
 847                 i++;
 848             }
 849             *src += i;
 850             return i;
 851         }
 852         buf[i] = p[i];
 853     }
 854     /* overflow */
 855     return 0;
 856 }
 857 
 858 static void
 859 printUsage(void)
 860 {
 861      TTY_MESSAGE((
 862  "               Java Debugger JDWP Agent Library\n"
 863  "               --------------------------------\n"
 864  "\n"
 865  "  (see http://java.sun.com/products/jpda for more information)\n"
 866  "\n"
 867  "jdwp usage: java " AGENTLIB "=[help]|[<option>=<value>, ...]\n"
 868  "\n"
 869  "Option Name and Value            Description                       Default\n"
 870  "---------------------            -----------                       -------\n"
 871  "suspend=y|n                      wait on startup?                  y\n"
 872  "transport=<name>                 transport spec                    none\n"
 873  "address=<listen/attach address>  transport spec                    \"\"\n"
 874  "server=y|n                       listen for debugger?              n\n"
 875  "launch=<command line>            run debugger on event             none\n"
 876  "onthrow=<exception name>         debug on throw                    none\n"
 877  "onuncaught=y|n                   debug on any uncaught?            n\n"
 878  "timeout=<timeout value>          for listen/attach in milliseconds n\n"
 879  "fibers=y|n|all                   support for debugging fibers      y\n"
 880  "mutf8=y|n                        output modified utf-8             n\n"
 881  "quiet=y|n                        control over terminal messages    n\n"));
 882 
 883     TTY_MESSAGE((
 884  "Obsolete Options\n"
 885  "----------------\n"
 886  "strict=y|n\n"
 887  "stdalloc=y|n\n"
 888  "\n"
 889  "Examples\n"
 890  "--------\n"
 891  "  - Using sockets connect to a debugger at a specific address:\n"
 892  "    java " AGENTLIB "=transport=dt_socket,address=localhost:8000 ...\n"
 893  "  - Using sockets listen for a debugger to attach:\n"
 894  "    java " AGENTLIB "=transport=dt_socket,server=y,suspend=y ...\n"
 895  "\n"
 896  "Notes\n"
 897  "-----\n"
 898  "  - A timeout value of 0 (the default) is no timeout.\n"
 899  "\n"
 900  "Warnings\n"
 901  "--------\n"
 902  "  - The older " XRUN " interface can still be used, but will be removed in\n"
 903  "    a future release, for example:\n"
 904  "        java " XDEBUG " " XRUN ":[help]|[<option>=<value>, ...]\n"
 905     ));
 906 
 907 #ifdef DEBUG
 908 
 909      TTY_MESSAGE((
 910  "\n"
 911  "Debugging Options            Description                       Default\n"
 912  "-----------------            -----------                       -------\n"
 913  "pause=y|n                    pause to debug PID                n\n"
 914  "coredump=y|n                 coredump at exit                  n\n"
 915  "errorexit=y|n                exit on any error                 n\n"
 916  "logfile=filename             name of log file                  none\n"
 917  "logflags=flags               log flags (bitmask)               none\n"
 918  "                               JVM calls     = 0x001\n"
 919  "                               JNI calls     = 0x002\n"
 920  "                               JVMTI calls   = 0x004\n"
 921  "                               misc events   = 0x008\n"
 922  "                               step logs     = 0x010\n"
 923  "                               locations     = 0x020\n"
 924  "                               callbacks     = 0x040\n"
 925  "                               errors        = 0x080\n"
 926  "                               everything    = 0xfff"));
 927 
 928     TTY_MESSAGE((
 929  "debugflags=flags             debug flags (bitmask)           none\n"
 930  "                               USE_ITERATE_THROUGH_HEAP 0x01\n"
 931  "\n"
 932  "Environment Variables\n"
 933  "---------------------\n"
 934  "_JAVA_JDWP_OPTIONS\n"
 935  "    Options can be added externally via this environment variable.\n"
 936  "    Anything contained in it will get a comma prepended to it (if needed),\n"
 937  "    then it will be added to the end of the options supplied via the\n"
 938  "    " XRUN " or " AGENTLIB " command line option.\n"
 939     ));
 940 
 941 #endif
 942 
 943 
 944 
 945 }
 946 
 947 static jboolean checkAddress(void *bagItem, void *arg)
 948 {
 949     TransportSpec *spec = (TransportSpec *)bagItem;
 950     if (spec->address == NULL) {
 951         ERROR_MESSAGE(("JDWP Non-server transport %s must have a connection "
 952                 "address specified through the 'address=' option",
 953                 spec->name));
 954         return JNI_FALSE;
 955     } else {
 956         return JNI_TRUE;
 957     }
 958 }
 959 
 960 static  char *
 961 add_to_options(char *options, char *new_options)
 962 {
 963     size_t originalLength;
 964     char *combinedOptions;
 965 
 966     /*
 967      * Allocate enough space for both strings and
 968      * comma in between.
 969      */
 970     originalLength = strlen(options);
 971     combinedOptions = jvmtiAllocate((jint)originalLength + 1 +
 972                                 (jint)strlen(new_options) + 1);
 973     if (combinedOptions == NULL) {
 974         return NULL;
 975     }
 976 
 977     (void)strcpy(combinedOptions, options);
 978     (void)strcat(combinedOptions, ",");
 979     (void)strcat(combinedOptions, new_options);
 980 
 981     return combinedOptions;
 982 }
 983 
 984 static jboolean
 985 get_boolean(char **pstr, jboolean *answer)
 986 {
 987     char buf[80];
 988     *answer = JNI_FALSE;
 989     /*LINTED*/
 990     if (get_tok(pstr, buf, (int)sizeof(buf), ',')) {
 991         if (strcmp(buf, "y") == 0) {
 992             *answer = JNI_TRUE;
 993             return JNI_TRUE;
 994         } else if (strcmp(buf, "n") == 0) {
 995             *answer = JNI_FALSE;
 996             return JNI_TRUE;
 997         }
 998     }
 999     return JNI_FALSE;
1000 }
1001 
1002 /* atexit() callback */
1003 static void
1004 atexit_finish_logging(void)
1005 {
1006     /* Normal exit(0) (not _exit()) may only reach here */
1007     finish_logging();  /* Only first call matters */
1008 }
1009 
1010 static jboolean
1011 parseOptions(char *options)
1012 {
1013     TransportSpec *currentTransport = NULL;
1014     char *end;
1015     char *current;
1016     int length;
1017     char *str;
1018     char *errmsg;
1019     jboolean onJcmd = JNI_FALSE;
1020 
1021     /* Set defaults */
1022     gdata->assertOn     = DEFAULT_ASSERT_ON;
1023     gdata->assertFatal  = DEFAULT_ASSERT_FATAL;
1024     logfile             = DEFAULT_LOGFILE;
1025 
1026     /* Set fiber debugging level. */
1027     gdata->fibersSupported = JNI_TRUE;
1028     gdata->notifyDebuggerOfAllFibers = JNI_FALSE;
1029 
1030     /* Options being NULL will end up being an error. */
1031     if (options == NULL) {
1032         options = "";
1033     }
1034 
1035     /* Check for "help" BEFORE we add any environmental settings */
1036     if ((strcmp(options, "help")) == 0) {
1037         printUsage();
1038         forceExit(0); /* Kill entire process, no core dump wanted */
1039     }
1040 
1041     /* These buffers are never freed */
1042     {
1043         char *envOptions;
1044 
1045         /*
1046          * Add environmentally specified options.
1047          */
1048         envOptions = getenv("_JAVA_JDWP_OPTIONS");
1049         if (envOptions != NULL) {
1050             options = add_to_options(options, envOptions);
1051             if ( options==NULL ) {
1052                 EXIT_ERROR(AGENT_ERROR_OUT_OF_MEMORY,"options");
1053             }
1054         }
1055 
1056         /*
1057          * Allocate a buffer for names derived from option strings. It should
1058          * never be longer than the original options string itself.
1059          * Also keep a copy of the options in gdata->options.
1060          */
1061         length = (int)strlen(options);
1062         gdata->options = jvmtiAllocate(length + 1);
1063         if (gdata->options == NULL) {
1064             EXIT_ERROR(AGENT_ERROR_OUT_OF_MEMORY,"options");
1065         }
1066         (void)strcpy(gdata->options, options);
1067         names = jvmtiAllocate(length + 1);
1068         if (names == NULL) {
1069             EXIT_ERROR(AGENT_ERROR_OUT_OF_MEMORY,"options");
1070         }
1071 
1072         transports = bagCreateBag(sizeof(TransportSpec), 3);
1073         if (transports == NULL) {
1074             EXIT_ERROR(AGENT_ERROR_OUT_OF_MEMORY,"transports");
1075         }
1076     }
1077 
1078     current = names;
1079     end = names + length;
1080     str = options;
1081 
1082     while (*str) {
1083         char buf[100];
1084         /*LINTED*/
1085         if (!get_tok(&str, buf, (int)sizeof(buf), '=')) {
1086             goto syntax_error;
1087         }
1088         if (strcmp(buf, "transport") == 0) {
1089             currentTransport = bagAdd(transports);
1090             /*LINTED*/
1091             if (!get_tok(&str, current, (int)(end - current), ',')) {
1092                 goto syntax_error;
1093             }
1094             currentTransport->name = current;
1095             currentTransport->address = NULL;
1096             currentTransport->allow = NULL;
1097             currentTransport->timeout = 0L;
1098             current += strlen(current) + 1;
1099         } else if (strcmp(buf, "address") == 0) {
1100             if (currentTransport == NULL) {
1101                 errmsg = "address specified without transport";
1102                 goto bad_option_with_errmsg;
1103             }
1104             /*LINTED*/
1105             if (!get_tok(&str, current, (int)(end - current), ',')) {
1106                 goto syntax_error;
1107             }
1108             currentTransport->address = current;
1109             current += strlen(current) + 1;
1110         } else if (strcmp(buf, "allow") == 0) {
1111             if (currentTransport == NULL) {
1112                 errmsg = "allow specified without transport";
1113                 goto bad_option_with_errmsg;
1114             }
1115             /*LINTED*/
1116             if (!get_tok(&str, current, (int)(end - current), ',')) {
1117                 goto syntax_error;
1118             }
1119             currentTransport->allow = current;
1120             current += strlen(current) + 1;
1121          } else if (strcmp(buf, "timeout") == 0) {
1122             if (currentTransport == NULL) {
1123                 errmsg = "timeout specified without transport";
1124                 goto bad_option_with_errmsg;
1125             }
1126             /*LINTED*/
1127             if (!get_tok(&str, current, (int)(end - current), ',')) {
1128                 goto syntax_error;
1129             }
1130             currentTransport->timeout = atol(current);
1131             current += strlen(current) + 1;
1132         } else if (strcmp(buf, "fibers") == 0) {
1133             if (!get_tok(&str, current, (int)(end - current), ',')) {
1134                 goto syntax_error;
1135             }
1136             if (strcmp(current, "y") == 0) {
1137                 gdata->fibersSupported = JNI_TRUE;
1138                 gdata->notifyDebuggerOfAllFibers = JNI_FALSE;
1139             } else if (strcmp(current, "all") == 0) {
1140                 gdata->fibersSupported = JNI_TRUE;
1141                 gdata->notifyDebuggerOfAllFibers = JNI_TRUE;
1142             } else if (strcmp(current, "n") == 0) {
1143                 gdata->fibersSupported = JNI_FALSE;
1144                 gdata->notifyDebuggerOfAllFibers = JNI_FALSE;
1145             } else {
1146                 goto syntax_error;
1147             }
1148             current += strlen(current) + 1;
1149         } else if (strcmp(buf, "launch") == 0) {
1150             /*LINTED*/
1151             if (!get_tok(&str, current, (int)(end - current), ',')) {
1152                 goto syntax_error;
1153             }
1154             launchOnInit = current;
1155             current += strlen(current) + 1;
1156         } else if (strcmp(buf, "onthrow") == 0) {
1157             /* Read class name and convert in place to a signature */
1158             *current = 'L';
1159             /*LINTED*/
1160             if (!get_tok(&str, current + 1, (int)(end - current - 1), ',')) {
1161                 goto syntax_error;
1162             }
1163             initOnException = current;
1164             while (*current != '\0') {
1165                 if (*current == '.') {
1166                     *current = '/';
1167                 }
1168                 current++;
1169             }
1170             *current++ = ';';
1171             *current++ = '\0';
1172         } else if (strcmp(buf, "assert") == 0) {
1173             /*LINTED*/
1174             if (!get_tok(&str, current, (int)(end - current), ',')) {
1175                 goto syntax_error;
1176             }
1177             if (strcmp(current, "y") == 0) {
1178                 gdata->assertOn = JNI_TRUE;
1179                 gdata->assertFatal = JNI_FALSE;
1180             } else if (strcmp(current, "fatal") == 0) {
1181                 gdata->assertOn = JNI_TRUE;
1182                 gdata->assertFatal = JNI_TRUE;
1183             } else if (strcmp(current, "n") == 0) {
1184                 gdata->assertOn = JNI_FALSE;
1185                 gdata->assertFatal = JNI_FALSE;
1186             } else {
1187                 goto syntax_error;
1188             }
1189             current += strlen(current) + 1;
1190         } else if (strcmp(buf, "pause") == 0) {
1191             if ( !get_boolean(&str, &dopause) ) {
1192                 goto syntax_error;
1193             }
1194             if ( dopause ) {
1195                 do_pause();
1196             }
1197         } else if (strcmp(buf, "coredump") == 0) {
1198             if ( !get_boolean(&str, &docoredump) ) {
1199                 goto syntax_error;
1200             }
1201         } else if (strcmp(buf, "errorexit") == 0) {
1202             if ( !get_boolean(&str, &(gdata->doerrorexit)) ) {
1203                 goto syntax_error;
1204             }
1205         } else if (strcmp(buf, "exitpause") == 0) {
1206             errmsg = "The exitpause option removed, use -XX:OnError";
1207             goto bad_option_with_errmsg;
1208         } else if (strcmp(buf, "precrash") == 0) {
1209             errmsg = "The precrash option removed, use -XX:OnError";
1210             goto bad_option_with_errmsg;
1211         } else if (strcmp(buf, "logfile") == 0) {
1212             /*LINTED*/
1213             if (!get_tok(&str, current, (int)(end - current), ',')) {
1214                 goto syntax_error;
1215             }
1216             logfile = current;
1217             current += strlen(current) + 1;
1218         } else if (strcmp(buf, "logflags") == 0) {
1219             /*LINTED*/
1220             if (!get_tok(&str, current, (int)(end - current), ',')) {
1221                 goto syntax_error;
1222             }
1223             /*LINTED*/
1224             logflags = (unsigned)strtol(current, NULL, 0);
1225         } else if (strcmp(buf, "debugflags") == 0) {
1226             /*LINTED*/
1227             if (!get_tok(&str, current, (int)(end - current), ',')) {
1228                 goto syntax_error;
1229             }
1230             /*LINTED*/
1231             gdata->debugflags = (unsigned)strtol(current, NULL, 0);
1232         } else if ( strcmp(buf, "suspend")==0 ) {
1233             if ( !get_boolean(&str, &suspendOnInit) ) {
1234                 goto syntax_error;
1235             }
1236         } else if ( strcmp(buf, "server")==0 ) {
1237             if ( !get_boolean(&str, &isServer) ) {
1238                 goto syntax_error;
1239             }
1240         } else if ( strcmp(buf, "strict")==0 ) { /* Obsolete, but accept it */
1241             if ( !get_boolean(&str, &isStrict) ) {
1242                 goto syntax_error;
1243             }
1244         } else if ( strcmp(buf, "quiet")==0 ) {
1245             if ( !get_boolean(&str, &(gdata->quiet)) ) {
1246                 goto syntax_error;
1247             }
1248         } else if ( strcmp(buf, "onuncaught")==0 ) {
1249             if ( !get_boolean(&str, &initOnUncaught) ) {
1250                 goto syntax_error;
1251             }
1252         } else if ( strcmp(buf, "mutf8")==0 ) {
1253             if ( !get_boolean(&str, &(gdata->modifiedUtf8)) ) {
1254                 goto syntax_error;
1255             }
1256         } else if ( strcmp(buf, "stdalloc")==0 ) { /* Obsolete, but accept it */
1257             if ( !get_boolean(&str, &useStandardAlloc) ) {
1258                 goto syntax_error;
1259             }
1260         } else if (strcmp(buf, "onjcmd") == 0) {
1261             if (!get_boolean(&str, &onJcmd)) {
1262                 goto syntax_error;
1263             }
1264         } else {
1265             goto syntax_error;
1266         }
1267     }
1268 
1269     /* Setup logging now */
1270     if ( logfile!=NULL ) {
1271         setup_logging(logfile, logflags);
1272         (void)atexit(&atexit_finish_logging);
1273     }
1274 
1275     if (bagSize(transports) == 0) {
1276         errmsg = "no transport specified";
1277         goto bad_option_with_errmsg;
1278     }
1279 
1280     /*
1281      * TO DO: Remove when multiple transports are allowed. (replace with
1282      * check below.
1283      */
1284     if (bagSize(transports) > 1) {
1285         errmsg = "multiple transports are not supported in this release";
1286         goto bad_option_with_errmsg;
1287     }
1288 
1289     if (!isServer) {
1290         jboolean specified = bagEnumerateOver(transports, checkAddress, NULL);
1291         if (!specified) {
1292             /* message already printed */
1293             goto bad_option_no_msg;
1294         }
1295     }
1296 
1297     /*
1298      * The user has selected to wait for an exception before init happens
1299      */
1300     if ((initOnException != NULL) || (initOnUncaught)) {
1301         initOnStartup = JNI_FALSE;
1302 
1303         if (launchOnInit == NULL) {
1304             /*
1305              * These rely on the launch=/usr/bin/foo
1306              * suboption, so it is an error if user did not
1307              * provide one.
1308              */
1309             errmsg = "Specify launch=<command line> when using onthrow or onuncaught suboption";
1310             goto bad_option_with_errmsg;
1311         }
1312     }
1313 
1314     if (onJcmd) {
1315         if (launchOnInit != NULL) {
1316             errmsg = "Cannot combine onjcmd and launch suboptions";
1317             goto bad_option_with_errmsg;
1318         }
1319         if (!isServer) {
1320             errmsg = "Can only use onjcmd with server=y";
1321             goto bad_option_with_errmsg;
1322         }
1323         suspendOnInit = JNI_FALSE;
1324         initOnStartup = JNI_FALSE;
1325         allowStartViaJcmd = JNI_TRUE;
1326     }
1327 
1328     return JNI_TRUE;
1329 
1330 syntax_error:
1331     ERROR_MESSAGE(("JDWP option syntax error: %s=%s", AGENTLIB, options));
1332     return JNI_FALSE;
1333 
1334 bad_option_with_errmsg:
1335     ERROR_MESSAGE(("JDWP %s: %s=%s", errmsg, AGENTLIB, options));
1336     return JNI_FALSE;
1337 
1338 bad_option_no_msg:
1339     ERROR_MESSAGE(("JDWP %s: %s=%s", "invalid option", AGENTLIB, options));
1340     return JNI_FALSE;
1341 }
1342 
1343 /* All normal exit doors lead here */
1344 void
1345 debugInit_exit(jvmtiError error, const char *msg)
1346 {
1347     enum exit_codes { EXIT_NO_ERRORS = 0, EXIT_JVMTI_ERROR = 1, EXIT_TRANSPORT_ERROR = 2 };
1348 
1349     // Release commandLoop vmDeathLock if necessary
1350     commandLoop_exitVmDeathLockOnError();
1351 
1352     // Prepare to exit. Log error and finish logging
1353     LOG_MISC(("Exiting with error %s(%d): %s", jvmtiErrorText(error), error,
1354                                                ((msg == NULL) ? "" : msg)));
1355 
1356     // coredump requested by command line. Keep JVMTI data dirty
1357     if (error != JVMTI_ERROR_NONE && docoredump) {
1358         LOG_MISC(("Dumping core as requested by command line"));
1359         finish_logging();
1360         abort();
1361     }
1362 
1363     finish_logging();
1364 
1365     // Cleanup the JVMTI if we have one
1366     if (gdata != NULL) {
1367         gdata->vmDead = JNI_TRUE;
1368         if (gdata->jvmti != NULL) {
1369             // Dispose of jvmti (gdata->jvmti becomes NULL)
1370             disposeEnvironment(gdata->jvmti);
1371         }
1372     }
1373 
1374     // We are here with no errors. Kill entire process and exit with zero exit code
1375     if (error == JVMTI_ERROR_NONE) {
1376         forceExit(EXIT_NO_ERRORS);
1377         return;
1378     }
1379 
1380     // No transport initilized.
1381     // As we don't have any details here exiting with separate exit code
1382     if (error == AGENT_ERROR_TRANSPORT_INIT) {
1383         forceExit(EXIT_TRANSPORT_ERROR);
1384         return;
1385     }
1386 
1387     // We have JVMTI error. Call hotspot jni_FatalError handler
1388     jniFatalError(NULL, msg, error, EXIT_JVMTI_ERROR);
1389 
1390     // hotspot calls os:abort() so we should never reach code below,
1391     // but guard against possible hotspot changes
1392 
1393     // Last chance to die, this kills the entire process.
1394     forceExit(EXIT_JVMTI_ERROR);
1395 }
1396 
1397 static jboolean getFirstTransport(void *item, void *arg)
1398 {
1399     TransportSpec** store = arg;
1400     *store = item;
1401 
1402     return JNI_FALSE; /* Want the first */
1403 }
1404 
1405 /* Call to start up debugging. */
1406 JNIEXPORT char const* JNICALL debugInit_startDebuggingViaCommand(JNIEnv* env, jthread thread, char const** transport_name,
1407                                                                 char const** address, jboolean* first_start) {
1408     jboolean is_first_start = JNI_FALSE;
1409     TransportSpec* spec = NULL;
1410 
1411     if (!vmInitialized) {
1412         return "Not yet initialized. Try again later.";
1413     }
1414 
1415     if (!allowStartViaJcmd) {
1416         return "Starting debugging via jcmd was not enabled via the onjcmd option of the jdwp agent.";
1417     }
1418 
1419     if (!startedViaJcmd) {
1420         startedViaJcmd = JNI_TRUE;
1421         is_first_start = JNI_TRUE;
1422         initialize(env, thread, EI_VM_INIT);
1423     }
1424 
1425     bagEnumerateOver(transports, getFirstTransport, &spec);
1426 
1427     if ((spec != NULL) && (transport_name != NULL) && (address != NULL)) {
1428         *transport_name = spec->name;
1429         *address = spec->address;
1430     }
1431 
1432     if (first_start != NULL) {
1433         *first_start = is_first_start;
1434     }
1435 
1436     return NULL;
1437 }