Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/back/debugInit.c
38765 views
/*1* Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425#include <ctype.h>2627#include "util.h"28#include "commonRef.h"29#include "debugDispatch.h"30#include "eventHandler.h"31#include "eventHelper.h"32#include "threadControl.h"33#include "stepControl.h"34#include "transport.h"35#include "classTrack.h"36#include "debugLoop.h"37#include "bag.h"38#include "invoker.h"39#include "sys.h"4041/* How the options get to OnLoad: */42#define XDEBUG "-Xdebug"43#define XRUN "-Xrunjdwp"44#define AGENTLIB "-agentlib:jdwp"4546/* Debug version defaults */47#ifdef DEBUG48#define DEFAULT_ASSERT_ON JNI_TRUE49#define DEFAULT_ASSERT_FATAL JNI_TRUE50#define DEFAULT_LOGFILE "jdwp.log"51#else52#define DEFAULT_ASSERT_ON JNI_FALSE53#define DEFAULT_ASSERT_FATAL JNI_FALSE54#define DEFAULT_LOGFILE NULL55#endif5657static jboolean vmInitialized;58static jrawMonitorID initMonitor;59static jboolean initComplete;60static jbyte currentSessionID;6162/*63* Options set through the OnLoad options string. All of these values64* are set once at VM startup and never reset.65*/66static jboolean isServer = JNI_FALSE; /* Listens for connecting debuggers? */67static jboolean isStrict = JNI_FALSE; /* Unused */68static jboolean useStandardAlloc = JNI_FALSE; /* Use standard malloc/free? */69static struct bag *transports; /* of TransportSpec */7071static jboolean initOnStartup = JNI_TRUE; /* init immediately */72static char *initOnException = NULL; /* init when this exception thrown */73static jboolean initOnUncaught = JNI_FALSE; /* init when uncaught exc thrown */7475static char *launchOnInit = NULL; /* launch this app during init */76static jboolean suspendOnInit = JNI_TRUE; /* suspend all app threads after init */77static jboolean dopause = JNI_FALSE; /* pause for debugger attach */78static jboolean docoredump = JNI_FALSE; /* core dump on exit */79static char *logfile = NULL; /* Name of logfile (if logging) */80static unsigned logflags = 0; /* Log flags */8182static char *names; /* strings derived from OnLoad options */8384/*85* Elements of the transports bag86*/87typedef struct TransportSpec {88char *name;89char *address;90long timeout;91} TransportSpec;9293/*94* Forward Refs95*/96static void JNICALL cbEarlyVMInit(jvmtiEnv*, JNIEnv *, jthread);97static void JNICALL cbEarlyVMDeath(jvmtiEnv*, JNIEnv *);98static void JNICALL cbEarlyException(jvmtiEnv*, JNIEnv *,99jthread, jmethodID, jlocation, jobject, jmethodID, jlocation);100101static void initialize(JNIEnv *env, jthread thread, EventIndex triggering_ei);102static jboolean parseOptions(char *str);103104/*105* Phase 1: Initial load.106*107* OnLoad is called by the VM immediately after the back-end108* library is loaded. We can do very little in this function since109* the VM has not completed initialization. So, we parse the JDWP110* options and set up a simple initial event callbacks for JVMTI events.111* When a triggering event occurs, that callback will begin debugger initialization.112*/113114/* Get a static area to hold the Global Data */115static BackendGlobalData *116get_gdata(void)117{118static BackendGlobalData s;119(void)memset(&s, 0, sizeof(BackendGlobalData));120return &s;121}122123static jvmtiError124set_event_notification(jvmtiEventMode mode, EventIndex ei)125{126jvmtiError error;127error = JVMTI_FUNC_PTR(gdata->jvmti,SetEventNotificationMode)128(gdata->jvmti, mode, eventIndex2jvmti(ei), NULL);129if (error != JVMTI_ERROR_NONE) {130ERROR_MESSAGE(("JDWP unable to configure initial JVMTI event %s: %s(%d)",131eventText(ei), jvmtiErrorText(error), error));132}133return error;134}135136typedef struct {137int major;138int minor;139} version_type;140141typedef struct {142version_type runtime;143version_type compiletime;144} compatible_versions_type;145146/*147* List of explicitly compatible JVMTI versions, specified as148* { runtime version, compile-time version } pairs. -1 is a wildcard.149*/150static int nof_compatible_versions = 3;151static compatible_versions_type compatible_versions_list[] = {152/*153* FIXUP: Allow version 0 to be compatible with anything154* Special check for FCS of 1.0.155*/156{ { 0, -1 }, { -1, -1 } },157{ { -1, -1 }, { 0, -1 } },158/*159* 1.2 is runtime compatible with 1.1 -- just make sure to check the160* version before using any new 1.2 features161*/162{ { 1, 1 }, { 1, 2 } }163};164165166/* Logic to determine JVMTI version compatibility */167static jboolean168compatible_versions(jint major_runtime, jint minor_runtime,169jint major_compiletime, jint minor_compiletime)170{171/*172* First check to see if versions are explicitly compatible via the173* list specified above.174*/175int i;176for (i = 0; i < nof_compatible_versions; ++i) {177version_type runtime = compatible_versions_list[i].runtime;178version_type comptime = compatible_versions_list[i].compiletime;179180if ((major_runtime == runtime.major || runtime.major == -1) &&181(minor_runtime == runtime.minor || runtime.minor == -1) &&182(major_compiletime == comptime.major || comptime.major == -1) &&183(minor_compiletime == comptime.minor || comptime.minor == -1)) {184return JNI_TRUE;185}186}187188return major_runtime == major_compiletime &&189minor_runtime >= minor_compiletime;190}191192/* OnLoad startup:193* Returning JNI_ERR will cause the java_g VM to core dump, be careful.194*/195JNIEXPORT jint JNICALL196Agent_OnLoad(JavaVM *vm, char *options, void *reserved)197{198jvmtiError error;199jvmtiCapabilities needed_capabilities;200jvmtiCapabilities potential_capabilities;201jint jvmtiCompileTimeMajorVersion;202jint jvmtiCompileTimeMinorVersion;203jint jvmtiCompileTimeMicroVersion;204char *boot_path = NULL;205char npt_lib[MAXPATHLEN];206207/* See if it's already loaded */208if ( gdata!=NULL && gdata->isLoaded==JNI_TRUE ) {209ERROR_MESSAGE(("Cannot load this JVM TI agent twice, check your java command line for duplicate jdwp options."));210return JNI_ERR;211}212213/* If gdata is defined and the VM died, why are we here? */214if ( gdata!=NULL && gdata->vmDead ) {215ERROR_MESSAGE(("JDWP unable to load, VM died"));216return JNI_ERR;217}218219/* Get global data area */220gdata = get_gdata();221if (gdata == NULL) {222ERROR_MESSAGE(("JDWP unable to allocate memory"));223return JNI_ERR;224}225gdata->isLoaded = JNI_TRUE;226227/* Start filling in gdata */228gdata->jvm = vm;229vmInitialized = JNI_FALSE;230gdata->vmDead = JNI_FALSE;231232/* Get the JVMTI Env, IMPORTANT: Do this first! For jvmtiAllocate(). */233error = JVM_FUNC_PTR(vm,GetEnv)234(vm, (void **)&(gdata->jvmti), JVMTI_VERSION_1);235if (error != JNI_OK) {236ERROR_MESSAGE(("JDWP unable to access JVMTI Version 1 (0x%x),"237" is your J2SE a 1.5 or newer version?"238" JNIEnv's GetEnv() returned %d",239JVMTI_VERSION_1, error));240forceExit(1); /* Kill entire process, no core dump */241}242243/* Check to make sure the version of jvmti.h we compiled with244* matches the runtime version we are using.245*/246jvmtiCompileTimeMajorVersion = ( JVMTI_VERSION & JVMTI_VERSION_MASK_MAJOR )247>> JVMTI_VERSION_SHIFT_MAJOR;248jvmtiCompileTimeMinorVersion = ( JVMTI_VERSION & JVMTI_VERSION_MASK_MINOR )249>> JVMTI_VERSION_SHIFT_MINOR;250jvmtiCompileTimeMicroVersion = ( JVMTI_VERSION & JVMTI_VERSION_MASK_MICRO )251>> JVMTI_VERSION_SHIFT_MICRO;252253/* Check for compatibility */254if ( !compatible_versions(jvmtiMajorVersion(), jvmtiMinorVersion(),255jvmtiCompileTimeMajorVersion, jvmtiCompileTimeMinorVersion) ) {256257ERROR_MESSAGE(("This jdwp native library will not work with this VM's "258"version of JVMTI (%d.%d.%d), it needs JVMTI %d.%d[.%d].",259jvmtiMajorVersion(),260jvmtiMinorVersion(),261jvmtiMicroVersion(),262jvmtiCompileTimeMajorVersion,263jvmtiCompileTimeMinorVersion,264jvmtiCompileTimeMicroVersion));265266/* Do not let VM get a fatal error, we don't want a core dump here. */267forceExit(1); /* Kill entire process, no core dump wanted */268}269270JVMTI_FUNC_PTR(gdata->jvmti, GetSystemProperty)271(gdata->jvmti, (const char *)"sun.boot.library.path",272&boot_path);273274dbgsysBuildLibName(npt_lib, sizeof(npt_lib), boot_path, NPT_LIBNAME);275/* Npt and Utf function init */276NPT_INITIALIZE(npt_lib, &(gdata->npt), NPT_VERSION, NULL);277jvmtiDeallocate(boot_path);278if (gdata->npt == NULL) {279ERROR_MESSAGE(("JDWP: unable to initialize NPT library"));280return JNI_ERR;281}282gdata->npt->utf = (gdata->npt->utfInitialize)(NULL);283if (gdata->npt->utf == NULL) {284ERROR_MESSAGE(("JDWP: UTF function initialization failed"));285return JNI_ERR;286}287288/* Parse input options */289if (!parseOptions(options)) {290/* No message necessary, should have been printed out already */291/* Do not let VM get a fatal error, we don't want a core dump here. */292forceExit(1); /* Kill entire process, no core dump wanted */293}294295LOG_MISC(("Onload: %s", options));296297/* Get potential capabilities */298(void)memset(&potential_capabilities,0,sizeof(potential_capabilities));299error = JVMTI_FUNC_PTR(gdata->jvmti,GetPotentialCapabilities)300(gdata->jvmti, &potential_capabilities);301if (error != JVMTI_ERROR_NONE) {302ERROR_MESSAGE(("JDWP unable to get potential JVMTI capabilities: %s(%d)",303jvmtiErrorText(error), error));304return JNI_ERR;305}306307/* Fill in ones that we must have */308(void)memset(&needed_capabilities,0,sizeof(needed_capabilities));309needed_capabilities.can_access_local_variables = 1;310needed_capabilities.can_generate_single_step_events = 1;311needed_capabilities.can_generate_exception_events = 1;312needed_capabilities.can_generate_frame_pop_events = 1;313needed_capabilities.can_generate_breakpoint_events = 1;314needed_capabilities.can_suspend = 1;315needed_capabilities.can_generate_method_entry_events = 1;316needed_capabilities.can_generate_method_exit_events = 1;317needed_capabilities.can_generate_garbage_collection_events = 1;318needed_capabilities.can_maintain_original_method_order = 1;319needed_capabilities.can_generate_monitor_events = 1;320needed_capabilities.can_tag_objects = 1;321322/* And what potential ones that would be nice to have */323needed_capabilities.can_force_early_return324= potential_capabilities.can_force_early_return;325needed_capabilities.can_generate_field_modification_events326= potential_capabilities.can_generate_field_modification_events;327needed_capabilities.can_generate_field_access_events328= potential_capabilities.can_generate_field_access_events;329needed_capabilities.can_get_bytecodes330= potential_capabilities.can_get_bytecodes;331needed_capabilities.can_get_synthetic_attribute332= potential_capabilities.can_get_synthetic_attribute;333needed_capabilities.can_get_owned_monitor_info334= potential_capabilities.can_get_owned_monitor_info;335needed_capabilities.can_get_current_contended_monitor336= potential_capabilities.can_get_current_contended_monitor;337needed_capabilities.can_get_monitor_info338= potential_capabilities.can_get_monitor_info;339needed_capabilities.can_pop_frame340= potential_capabilities.can_pop_frame;341needed_capabilities.can_redefine_classes342= potential_capabilities.can_redefine_classes;343needed_capabilities.can_redefine_any_class344= potential_capabilities.can_redefine_any_class;345needed_capabilities.can_get_owned_monitor_stack_depth_info346= potential_capabilities.can_get_owned_monitor_stack_depth_info;347needed_capabilities.can_get_constant_pool348= potential_capabilities.can_get_constant_pool;349{350needed_capabilities.can_get_source_debug_extension = 1;351needed_capabilities.can_get_source_file_name = 1;352needed_capabilities.can_get_line_numbers = 1;353needed_capabilities.can_signal_thread354= potential_capabilities.can_signal_thread;355}356357/* Add the capabilities */358error = JVMTI_FUNC_PTR(gdata->jvmti,AddCapabilities)359(gdata->jvmti, &needed_capabilities);360if (error != JVMTI_ERROR_NONE) {361ERROR_MESSAGE(("JDWP unable to get necessary JVMTI capabilities."));362forceExit(1); /* Kill entire process, no core dump wanted */363}364365/* Initialize event number mapping tables */366eventIndexInit();367368/* Set the initial JVMTI event notifications */369error = set_event_notification(JVMTI_ENABLE, EI_VM_DEATH);370if (error != JVMTI_ERROR_NONE) {371return JNI_ERR;372}373error = set_event_notification(JVMTI_ENABLE, EI_VM_INIT);374if (error != JVMTI_ERROR_NONE) {375return JNI_ERR;376}377if (initOnUncaught || (initOnException != NULL)) {378error = set_event_notification(JVMTI_ENABLE, EI_EXCEPTION);379if (error != JVMTI_ERROR_NONE) {380return JNI_ERR;381}382}383384/* Set callbacks just for 3 functions */385(void)memset(&(gdata->callbacks),0,sizeof(gdata->callbacks));386gdata->callbacks.VMInit = &cbEarlyVMInit;387gdata->callbacks.VMDeath = &cbEarlyVMDeath;388gdata->callbacks.Exception = &cbEarlyException;389error = JVMTI_FUNC_PTR(gdata->jvmti,SetEventCallbacks)390(gdata->jvmti, &(gdata->callbacks), sizeof(gdata->callbacks));391if (error != JVMTI_ERROR_NONE) {392ERROR_MESSAGE(("JDWP unable to set JVMTI event callbacks: %s(%d)",393jvmtiErrorText(error), error));394return JNI_ERR;395}396397LOG_MISC(("OnLoad: DONE"));398return JNI_OK;399}400401JNIEXPORT void JNICALL402Agent_OnUnload(JavaVM *vm)403{404405gdata->isLoaded = JNI_FALSE;406407/* Cleanup, but make sure VM is alive before using JNI, and408* make sure JVMTI environment is ok before deallocating409* memory allocated through JVMTI, which all of it is.410*/411412/*413* Close transport before exit414*/415if (transport_is_open()) {416transport_close();417}418}419420/*421* Phase 2: Initial events. Phase 2 consists of waiting for the422* event that triggers full initialization. Under normal circumstances423* (initOnStartup == TRUE) this is the JVMTI_EVENT_VM_INIT event.424* Otherwise, we delay initialization until the app throws a425* particular exception. The triggering event invokes426* the bulk of the initialization, including creation of threads and427* monitors, transport setup, and installation of a new event callback which428* handles the complete set of events.429*430* Since the triggering event comes in on an application thread, some of the431* initialization is difficult to do here. Specifically, this thread along432* with all other app threads may need to be suspended until a debugger433* connects. These kinds of tasks are left to the third phase which is434* invoked by one of the spawned debugger threads, the event handler.435*/436437/*438* Wait for a triggering event; then kick off debugger439* initialization. A different event callback will be installed by440* debugger initialization, and this function will not be called441* again.442*/443444/*445* TO DO: Decide whether we need to protect this code with446* a lock. It might be too early to create a monitor safely (?).447*/448449static void JNICALL450cbEarlyVMInit(jvmtiEnv *jvmti_env, JNIEnv *env, jthread thread)451{452LOG_CB(("cbEarlyVMInit"));453if ( gdata->vmDead ) {454EXIT_ERROR(AGENT_ERROR_INTERNAL,"VM dead at VM_INIT time");455}456if (initOnStartup)457initialize(env, thread, EI_VM_INIT);458vmInitialized = JNI_TRUE;459LOG_MISC(("END cbEarlyVMInit"));460}461462static void463disposeEnvironment(jvmtiEnv *jvmti_env)464{465jvmtiError error;466467error = JVMTI_FUNC_PTR(jvmti_env,DisposeEnvironment)(jvmti_env);468if ( error == JVMTI_ERROR_MUST_POSSESS_CAPABILITY )469error = JVMTI_ERROR_NONE; /* Hack! FIXUP when JVMTI has disposeEnv */470/* What should error return say? */471if (error != JVMTI_ERROR_NONE) {472ERROR_MESSAGE(("JDWP unable to dispose of JVMTI environment: %s(%d)",473jvmtiErrorText(error), error));474}475gdata->jvmti = NULL;476}477478static void JNICALL479cbEarlyVMDeath(jvmtiEnv *jvmti_env, JNIEnv *env)480{481LOG_CB(("cbEarlyVMDeath"));482if ( gdata->vmDead ) {483EXIT_ERROR(AGENT_ERROR_INTERNAL,"VM died more than once");484}485disposeEnvironment(jvmti_env);486gdata->jvmti = NULL;487gdata->jvm = NULL;488gdata->vmDead = JNI_TRUE;489LOG_MISC(("END cbEarlyVMDeath"));490}491492static void JNICALL493cbEarlyException(jvmtiEnv *jvmti_env, JNIEnv *env,494jthread thread, jmethodID method, jlocation location,495jobject exception,496jmethodID catch_method, jlocation catch_location)497{498jvmtiError error;499jthrowable currentException;500501LOG_CB(("cbEarlyException: thread=%p", thread));502503if ( gdata->vmDead ) {504EXIT_ERROR(AGENT_ERROR_INTERNAL,"VM dead at initial Exception event");505}506if (!vmInitialized) {507LOG_MISC(("VM is not initialized yet"));508return;509}510511/*512* We want to preserve any current exception that might get wiped513* out during event handling (e.g. JNI calls). We have to rely on514* space for the local reference on the current frame because515* doing a PushLocalFrame here might itself generate an exception.516*/517518currentException = JNI_FUNC_PTR(env,ExceptionOccurred)(env);519JNI_FUNC_PTR(env,ExceptionClear)(env);520521if (initOnUncaught && catch_method == NULL) {522523LOG_MISC(("Initializing on uncaught exception"));524initialize(env, thread, EI_EXCEPTION);525526} else if (initOnException != NULL) {527528jclass clazz;529530/* Get class of exception thrown */531clazz = JNI_FUNC_PTR(env,GetObjectClass)(env, exception);532if ( clazz != NULL ) {533char *signature = NULL;534/* initing on throw, check */535error = classSignature(clazz, &signature, NULL);536LOG_MISC(("Checking specific exception: looking for %s, got %s",537initOnException, signature));538if ( (error==JVMTI_ERROR_NONE) &&539(strcmp(signature, initOnException) == 0)) {540LOG_MISC(("Initializing on specific exception"));541initialize(env, thread, EI_EXCEPTION);542} else {543error = AGENT_ERROR_INTERNAL; /* Just to cause restore */544}545if ( signature != NULL ) {546jvmtiDeallocate(signature);547}548} else {549error = AGENT_ERROR_INTERNAL; /* Just to cause restore */550}551552/* If initialize didn't happen, we need to restore things */553if ( error != JVMTI_ERROR_NONE ) {554/*555* Restore exception state from before callback call556*/557LOG_MISC(("No initialization, didn't find right exception"));558if (currentException != NULL) {559JNI_FUNC_PTR(env,Throw)(env, currentException);560} else {561JNI_FUNC_PTR(env,ExceptionClear)(env);562}563}564565}566567LOG_MISC(("END cbEarlyException"));568569}570571typedef struct EnumerateArg {572jboolean isServer;573jdwpError error;574jint startCount;575} EnumerateArg;576577static jboolean578startTransport(void *item, void *arg)579{580TransportSpec *transport = item;581EnumerateArg *enumArg = arg;582jdwpError serror;583584LOG_MISC(("Begin startTransport"));585serror = transport_startTransport(enumArg->isServer, transport->name,586transport->address, transport->timeout);587if (serror != JDWP_ERROR(NONE)) {588ERROR_MESSAGE(("JDWP Transport %s failed to initialize, %s(%d)",589transport->name, jdwpErrorText(serror), serror));590enumArg->error = serror;591} else {592/* (Don't overwrite any previous error) */593594enumArg->startCount++;595}596597LOG_MISC(("End startTransport"));598599return JNI_TRUE; /* Always continue, even if there was an error */600}601602static void603signalInitComplete(void)604{605/*606* Initialization is complete607*/608LOG_MISC(("signal initialization complete"));609debugMonitorEnter(initMonitor);610initComplete = JNI_TRUE;611debugMonitorNotifyAll(initMonitor);612debugMonitorExit(initMonitor);613}614615/*616* Determine if initialization is complete.617*/618jboolean619debugInit_isInitComplete(void)620{621return initComplete;622}623624/*625* Wait for all initialization to complete.626*/627void628debugInit_waitInitComplete(void)629{630debugMonitorEnter(initMonitor);631while (!initComplete) {632debugMonitorWait(initMonitor);633}634debugMonitorExit(initMonitor);635}636637/* All process exit() calls come from here */638void639forceExit(int exit_code)640{641/* make sure the transport is closed down before we exit() */642transport_close();643exit(exit_code);644}645646/* All JVM fatal error exits lead here (e.g. we need to kill the VM). */647static void648jniFatalError(JNIEnv *env, const char *msg, jvmtiError error, int exit_code)649{650JavaVM *vm;651char buf[512];652653gdata->vmDead = JNI_TRUE;654if ( msg==NULL )655msg = "UNKNOWN REASON";656vm = gdata->jvm;657if ( env==NULL && vm!=NULL ) {658jint rc = (*((*vm)->GetEnv))(vm, (void **)&env, JNI_VERSION_1_2);659if (rc != JNI_OK ) {660env = NULL;661}662}663if ( error != JVMTI_ERROR_NONE ) {664(void)snprintf(buf, sizeof(buf), "JDWP %s, jvmtiError=%s(%d)",665msg, jvmtiErrorText(error), error);666} else {667(void)snprintf(buf, sizeof(buf), "JDWP %s", msg);668}669if (env != NULL) {670(*((*env)->FatalError))(env, buf);671} else {672/* Should rarely ever reach here, means VM is really dead */673print_message(stderr, "ERROR: JDWP: ", "\n",674"Can't call JNI FatalError(NULL, \"%s\")", buf);675}676forceExit(exit_code);677}678679/*680* Initialize debugger back end modules681*/682static void683initialize(JNIEnv *env, jthread thread, EventIndex triggering_ei)684{685jvmtiError error;686EnumerateArg arg;687jbyte suspendPolicy;688689LOG_MISC(("Begin initialize()"));690currentSessionID = 0;691initComplete = JNI_FALSE;692693if ( gdata->vmDead ) {694EXIT_ERROR(AGENT_ERROR_INTERNAL,"VM dead at initialize() time");695}696697/* Turn off the initial JVMTI event notifications */698error = set_event_notification(JVMTI_DISABLE, EI_EXCEPTION);699if (error != JVMTI_ERROR_NONE) {700EXIT_ERROR(error, "unable to disable JVMTI event notification");701}702error = set_event_notification(JVMTI_DISABLE, EI_VM_INIT);703if (error != JVMTI_ERROR_NONE) {704EXIT_ERROR(error, "unable to disable JVMTI event notification");705}706error = set_event_notification(JVMTI_DISABLE, EI_VM_DEATH);707if (error != JVMTI_ERROR_NONE) {708EXIT_ERROR(error, "unable to disable JVMTI event notification");709}710711/* Remove initial event callbacks */712(void)memset(&(gdata->callbacks),0,sizeof(gdata->callbacks));713error = JVMTI_FUNC_PTR(gdata->jvmti,SetEventCallbacks)714(gdata->jvmti, &(gdata->callbacks), sizeof(gdata->callbacks));715if (error != JVMTI_ERROR_NONE) {716EXIT_ERROR(error, "unable to clear JVMTI callbacks");717}718719commonRef_initialize();720util_initialize(env);721threadControl_initialize();722stepControl_initialize();723invoker_initialize();724debugDispatch_initialize();725classTrack_initialize(env);726debugLoop_initialize();727728initMonitor = debugMonitorCreate("JDWP Initialization Monitor");729730731/*732* Initialize transports733*/734arg.isServer = isServer;735arg.error = JDWP_ERROR(NONE);736arg.startCount = 0;737738transport_initialize();739(void)bagEnumerateOver(transports, startTransport, &arg);740741/*742* Exit with an error only if743* 1) none of the transports was successfully started, and744* 2) the application has not yet started running745*/746if ((arg.error != JDWP_ERROR(NONE)) &&747(arg.startCount == 0) &&748initOnStartup) {749EXIT_ERROR(map2jvmtiError(arg.error), "No transports initialized");750}751752eventHandler_initialize(currentSessionID);753754signalInitComplete();755756transport_waitForConnection();757758suspendPolicy = suspendOnInit ? JDWP_SUSPEND_POLICY(ALL)759: JDWP_SUSPEND_POLICY(NONE);760if (triggering_ei == EI_VM_INIT) {761LOG_MISC(("triggering_ei == EI_VM_INIT"));762eventHelper_reportVMInit(env, currentSessionID, thread, suspendPolicy);763} else {764/*765* TO DO: Kludgy way of getting the triggering event to the766* just-attached debugger. It would be nice to make this a little767* cleaner. There is also a race condition where other events768* can get in the queue (from other not-yet-suspended threads)769* before this one does. (Also need to handle allocation error below?)770*/771EventInfo info;772struct bag *initEventBag;773LOG_MISC(("triggering_ei != EI_VM_INIT"));774initEventBag = eventHelper_createEventBag();775(void)memset(&info,0,sizeof(info));776info.ei = triggering_ei;777eventHelper_recordEvent(&info, 0, suspendPolicy, initEventBag);778(void)eventHelper_reportEvents(currentSessionID, initEventBag);779bagDestroyBag(initEventBag);780}781782if ( gdata->vmDead ) {783EXIT_ERROR(AGENT_ERROR_INTERNAL,"VM dead before initialize() completes");784}785LOG_MISC(("End initialize()"));786}787788/*789* Restore all static data to the initialized state so that another790* debugger can connect properly later.791*/792void793debugInit_reset(JNIEnv *env)794{795EnumerateArg arg;796797LOG_MISC(("debugInit_reset() beginning"));798799currentSessionID++;800initComplete = JNI_FALSE;801802eventHandler_reset(currentSessionID);803transport_reset();804debugDispatch_reset();805invoker_reset();806stepControl_reset();807threadControl_reset();808util_reset();809commonRef_reset(env);810classTrack_reset();811812/*813* If this is a server, we are now ready to accept another connection.814* If it's a client, then we've cleaned up some (more should be added815* later) and we're done.816*/817if (isServer) {818arg.isServer = JNI_TRUE;819arg.error = JDWP_ERROR(NONE);820arg.startCount = 0;821(void)bagEnumerateOver(transports, startTransport, &arg);822823signalInitComplete();824825transport_waitForConnection();826} else {827signalInitComplete(); /* Why? */828}829830LOG_MISC(("debugInit_reset() completed."));831}832833834char *835debugInit_launchOnInit(void)836{837return launchOnInit;838}839840jboolean841debugInit_suspendOnInit(void)842{843return suspendOnInit;844}845846/*847* code below is shamelessly swiped from hprof.848*/849850static int851get_tok(char **src, char *buf, int buflen, char sep)852{853int i;854char *p = *src;855for (i = 0; i < buflen; i++) {856if (p[i] == 0 || p[i] == sep) {857buf[i] = 0;858if (p[i] == sep) {859i++;860}861*src += i;862return i;863}864buf[i] = p[i];865}866/* overflow */867return 0;868}869870static void871printUsage(void)872{873TTY_MESSAGE((874" Java Debugger JDWP Agent Library\n"875" --------------------------------\n"876"\n"877" (see http://java.sun.com/products/jpda for more information)\n"878"\n"879"jdwp usage: java " AGENTLIB "=[help]|[<option>=<value>, ...]\n"880"\n"881"Option Name and Value Description Default\n"882"--------------------- ----------- -------\n"883"suspend=y|n wait on startup? y\n"884"transport=<name> transport spec none\n"885"address=<listen/attach address> transport spec \"\"\n"886"server=y|n listen for debugger? n\n"887"launch=<command line> run debugger on event none\n"888"onthrow=<exception name> debug on throw none\n"889"onuncaught=y|n debug on any uncaught? n\n"890"timeout=<timeout value> for listen/attach in milliseconds n\n"891"mutf8=y|n output modified utf-8 n\n"892"quiet=y|n control over terminal messages n\n"893"\n"894"Obsolete Options\n"895"----------------\n"896"strict=y|n\n"897"stdalloc=y|n\n"898"\n"899"Examples\n"900"--------\n"901" - Using sockets connect to a debugger at a specific address:\n"902" java " AGENTLIB "=transport=dt_socket,address=localhost:8000 ...\n"903" - Using sockets listen for a debugger to attach:\n"904" java " AGENTLIB "=transport=dt_socket,server=y,suspend=y ...\n"905"\n"906"Notes\n"907"-----\n"908" - A timeout value of 0 (the default) is no timeout.\n"909"\n"910"Warnings\n"911"--------\n"912" - The older " XRUN " interface can still be used, but will be removed in\n"913" a future release, for example:\n"914" java " XDEBUG " " XRUN ":[help]|[<option>=<value>, ...]\n"915));916917#ifdef DEBUG918919TTY_MESSAGE((920"\n"921"Debugging Options Description Default\n"922"----------------- ----------- -------\n"923"pause=y|n pause to debug PID n\n"924"coredump=y|n coredump at exit n\n"925"errorexit=y|n exit on any error n\n"926"logfile=filename name of log file none\n"927"logflags=flags log flags (bitmask) none\n"928" JVM calls = 0x001\n"929" JNI calls = 0x002\n"930" JVMTI calls = 0x004\n"931" misc events = 0x008\n"932" step logs = 0x010\n"933" locations = 0x020\n"934" callbacks = 0x040\n"935" errors = 0x080\n"936" everything = 0xfff\n"937"debugflags=flags debug flags (bitmask) none\n"938" USE_ITERATE_THROUGH_HEAP 0x01\n"939"\n"940"Environment Variables\n"941"---------------------\n"942"_JAVA_JDWP_OPTIONS\n"943" Options can be added externally via this environment variable.\n"944" Anything contained in it will get a comma prepended to it (if needed),\n"945" then it will be added to the end of the options supplied via the\n"946" " XRUN " or " AGENTLIB " command line option.\n"947));948949#endif950951952953}954955static jboolean checkAddress(void *bagItem, void *arg)956{957TransportSpec *spec = (TransportSpec *)bagItem;958if (spec->address == NULL) {959ERROR_MESSAGE(("JDWP Non-server transport %s must have a connection "960"address specified through the 'address=' option",961spec->name));962return JNI_FALSE;963} else {964return JNI_TRUE;965}966}967968static char *969add_to_options(char *options, char *new_options)970{971size_t originalLength;972char *combinedOptions;973974/*975* Allocate enough space for both strings and976* comma in between.977*/978originalLength = strlen(options);979combinedOptions = jvmtiAllocate((jint)originalLength + 1 +980(jint)strlen(new_options) + 1);981if (combinedOptions == NULL) {982return NULL;983}984985(void)strcpy(combinedOptions, options);986(void)strcat(combinedOptions, ",");987(void)strcat(combinedOptions, new_options);988989return combinedOptions;990}991992static jboolean993get_boolean(char **pstr, jboolean *answer)994{995char buf[80];996*answer = JNI_FALSE;997/*LINTED*/998if (get_tok(pstr, buf, (int)sizeof(buf), ',')) {999if (strcmp(buf, "y") == 0) {1000*answer = JNI_TRUE;1001return JNI_TRUE;1002} else if (strcmp(buf, "n") == 0) {1003*answer = JNI_FALSE;1004return JNI_TRUE;1005}1006}1007return JNI_FALSE;1008}10091010/* atexit() callback */1011static void1012atexit_finish_logging(void)1013{1014/* Normal exit(0) (not _exit()) may only reach here */1015finish_logging(); /* Only first call matters */1016}10171018static jboolean1019parseOptions(char *options)1020{1021TransportSpec *currentTransport = NULL;1022char *end;1023char *current;1024int length;1025char *str;1026char *errmsg;10271028/* Set defaults */1029gdata->assertOn = DEFAULT_ASSERT_ON;1030gdata->assertFatal = DEFAULT_ASSERT_FATAL;1031logfile = DEFAULT_LOGFILE;10321033/* Options being NULL will end up being an error. */1034if (options == NULL) {1035options = "";1036}10371038/* Check for "help" BEFORE we add any environmental settings */1039if ((strcmp(options, "help")) == 0) {1040printUsage();1041forceExit(0); /* Kill entire process, no core dump wanted */1042}10431044/* These buffers are never freed */1045{1046char *envOptions;10471048/*1049* Add environmentally specified options.1050*/1051envOptions = getenv("_JAVA_JDWP_OPTIONS");1052if (envOptions != NULL) {1053options = add_to_options(options, envOptions);1054if ( options==NULL ) {1055EXIT_ERROR(AGENT_ERROR_OUT_OF_MEMORY,"options");1056}1057}10581059/*1060* Allocate a buffer for names derived from option strings. It should1061* never be longer than the original options string itself.1062* Also keep a copy of the options in gdata->options.1063*/1064length = (int)strlen(options);1065gdata->options = jvmtiAllocate(length + 1);1066if (gdata->options == NULL) {1067EXIT_ERROR(AGENT_ERROR_OUT_OF_MEMORY,"options");1068}1069(void)strcpy(gdata->options, options);1070names = jvmtiAllocate(length + 1);1071if (names == NULL) {1072EXIT_ERROR(AGENT_ERROR_OUT_OF_MEMORY,"options");1073}10741075transports = bagCreateBag(sizeof(TransportSpec), 3);1076if (transports == NULL) {1077EXIT_ERROR(AGENT_ERROR_OUT_OF_MEMORY,"transports");1078}10791080}10811082current = names;1083end = names + length;1084str = options;10851086while (*str) {1087char buf[100];1088/*LINTED*/1089if (!get_tok(&str, buf, (int)sizeof(buf), '=')) {1090goto syntax_error;1091}1092if (strcmp(buf, "transport") == 0) {1093currentTransport = bagAdd(transports);1094/*LINTED*/1095if (!get_tok(&str, current, (int)(end - current), ',')) {1096goto syntax_error;1097}1098currentTransport->name = current;1099current += strlen(current) + 1;1100} else if (strcmp(buf, "address") == 0) {1101if (currentTransport == NULL) {1102errmsg = "address specified without transport";1103goto bad_option_with_errmsg;1104}1105/*LINTED*/1106if (!get_tok(&str, current, (int)(end - current), ',')) {1107goto syntax_error;1108}1109currentTransport->address = current;1110current += strlen(current) + 1;1111} else if (strcmp(buf, "timeout") == 0) {1112if (currentTransport == NULL) {1113errmsg = "timeout specified without transport";1114goto bad_option_with_errmsg;1115}1116/*LINTED*/1117if (!get_tok(&str, current, (int)(end - current), ',')) {1118goto syntax_error;1119}1120currentTransport->timeout = atol(current);1121current += strlen(current) + 1;1122} else if (strcmp(buf, "launch") == 0) {1123/*LINTED*/1124if (!get_tok(&str, current, (int)(end - current), ',')) {1125goto syntax_error;1126}1127launchOnInit = current;1128current += strlen(current) + 1;1129} else if (strcmp(buf, "onthrow") == 0) {1130/* Read class name and convert in place to a signature */1131*current = 'L';1132/*LINTED*/1133if (!get_tok(&str, current + 1, (int)(end - current - 1), ',')) {1134goto syntax_error;1135}1136initOnException = current;1137while (*current != '\0') {1138if (*current == '.') {1139*current = '/';1140}1141current++;1142}1143*current++ = ';';1144*current++ = '\0';1145} else if (strcmp(buf, "assert") == 0) {1146/*LINTED*/1147if (!get_tok(&str, current, (int)(end - current), ',')) {1148goto syntax_error;1149}1150if (strcmp(current, "y") == 0) {1151gdata->assertOn = JNI_TRUE;1152gdata->assertFatal = JNI_FALSE;1153} else if (strcmp(current, "fatal") == 0) {1154gdata->assertOn = JNI_TRUE;1155gdata->assertFatal = JNI_TRUE;1156} else if (strcmp(current, "n") == 0) {1157gdata->assertOn = JNI_FALSE;1158gdata->assertFatal = JNI_FALSE;1159} else {1160goto syntax_error;1161}1162current += strlen(current) + 1;1163} else if (strcmp(buf, "pause") == 0) {1164if ( !get_boolean(&str, &dopause) ) {1165goto syntax_error;1166}1167if ( dopause ) {1168do_pause();1169}1170} else if (strcmp(buf, "coredump") == 0) {1171if ( !get_boolean(&str, &docoredump) ) {1172goto syntax_error;1173}1174} else if (strcmp(buf, "errorexit") == 0) {1175if ( !get_boolean(&str, &(gdata->doerrorexit)) ) {1176goto syntax_error;1177}1178} else if (strcmp(buf, "exitpause") == 0) {1179errmsg = "The exitpause option removed, use -XX:OnError";1180goto bad_option_with_errmsg;1181} else if (strcmp(buf, "precrash") == 0) {1182errmsg = "The precrash option removed, use -XX:OnError";1183goto bad_option_with_errmsg;1184} else if (strcmp(buf, "logfile") == 0) {1185/*LINTED*/1186if (!get_tok(&str, current, (int)(end - current), ',')) {1187goto syntax_error;1188}1189logfile = current;1190current += strlen(current) + 1;1191} else if (strcmp(buf, "logflags") == 0) {1192/*LINTED*/1193if (!get_tok(&str, current, (int)(end - current), ',')) {1194goto syntax_error;1195}1196/*LINTED*/1197logflags = (unsigned)strtol(current, NULL, 0);1198} else if (strcmp(buf, "debugflags") == 0) {1199/*LINTED*/1200if (!get_tok(&str, current, (int)(end - current), ',')) {1201goto syntax_error;1202}1203/*LINTED*/1204gdata->debugflags = (unsigned)strtol(current, NULL, 0);1205} else if ( strcmp(buf, "suspend")==0 ) {1206if ( !get_boolean(&str, &suspendOnInit) ) {1207goto syntax_error;1208}1209} else if ( strcmp(buf, "server")==0 ) {1210if ( !get_boolean(&str, &isServer) ) {1211goto syntax_error;1212}1213} else if ( strcmp(buf, "strict")==0 ) { /* Obsolete, but accept it */1214if ( !get_boolean(&str, &isStrict) ) {1215goto syntax_error;1216}1217} else if ( strcmp(buf, "quiet")==0 ) {1218if ( !get_boolean(&str, &(gdata->quiet)) ) {1219goto syntax_error;1220}1221} else if ( strcmp(buf, "onuncaught")==0 ) {1222if ( !get_boolean(&str, &initOnUncaught) ) {1223goto syntax_error;1224}1225} else if ( strcmp(buf, "mutf8")==0 ) {1226if ( !get_boolean(&str, &(gdata->modifiedUtf8)) ) {1227goto syntax_error;1228}1229} else if ( strcmp(buf, "stdalloc")==0 ) { /* Obsolete, but accept it */1230if ( !get_boolean(&str, &useStandardAlloc) ) {1231goto syntax_error;1232}1233} else {1234goto syntax_error;1235}1236}12371238/* Setup logging now */1239if ( logfile!=NULL ) {1240setup_logging(logfile, logflags);1241(void)atexit(&atexit_finish_logging);1242}12431244if (bagSize(transports) == 0) {1245errmsg = "no transport specified";1246goto bad_option_with_errmsg;1247}12481249/*1250* TO DO: Remove when multiple transports are allowed. (replace with1251* check below.1252*/1253if (bagSize(transports) > 1) {1254errmsg = "multiple transports are not supported in this release";1255goto bad_option_with_errmsg;1256}125712581259if (!isServer) {1260jboolean specified = bagEnumerateOver(transports, checkAddress, NULL);1261if (!specified) {1262/* message already printed */1263goto bad_option_no_msg;1264}1265}12661267/*1268* The user has selected to wait for an exception before init happens1269*/1270if ((initOnException != NULL) || (initOnUncaught)) {1271initOnStartup = JNI_FALSE;12721273if (launchOnInit == NULL) {1274/*1275* These rely on the launch=/usr/bin/foo1276* suboption, so it is an error if user did not1277* provide one.1278*/1279errmsg = "Specify launch=<command line> when using onthrow or onuncaught suboption";1280goto bad_option_with_errmsg;1281}1282}12831284return JNI_TRUE;12851286syntax_error:1287ERROR_MESSAGE(("JDWP option syntax error: %s=%s", AGENTLIB, options));1288return JNI_FALSE;12891290bad_option_with_errmsg:1291ERROR_MESSAGE(("JDWP %s: %s=%s", errmsg, AGENTLIB, options));1292return JNI_FALSE;12931294bad_option_no_msg:1295ERROR_MESSAGE(("JDWP %s: %s=%s", "invalid option", AGENTLIB, options));1296return JNI_FALSE;1297}12981299/* All normal exit doors lead here */1300void1301debugInit_exit(jvmtiError error, const char *msg)1302{1303enum exit_codes { EXIT_NO_ERRORS = 0, EXIT_JVMTI_ERROR = 1, EXIT_TRANSPORT_ERROR = 2 };13041305// Prepare to exit. Log error and finish logging1306LOG_MISC(("Exiting with error %s(%d): %s", jvmtiErrorText(error), error,1307((msg == NULL) ? "" : msg)));13081309// coredump requested by command line. Keep JVMTI data dirty1310if (error != JVMTI_ERROR_NONE && docoredump) {1311LOG_MISC(("Dumping core as requested by command line"));1312finish_logging();1313abort();1314}13151316finish_logging();13171318// Cleanup the JVMTI if we have one1319if (gdata != NULL) {1320gdata->vmDead = JNI_TRUE;1321if (gdata->jvmti != NULL) {1322// Dispose of jvmti (gdata->jvmti becomes NULL)1323disposeEnvironment(gdata->jvmti);1324}1325}13261327// We are here with no errors. Kill entire process and exit with zero exit code1328if (error == JVMTI_ERROR_NONE) {1329forceExit(EXIT_NO_ERRORS);1330return;1331}13321333// No transport initilized.1334// As we don't have any details here exiting with separate exit code1335if (error == AGENT_ERROR_TRANSPORT_INIT) {1336forceExit(EXIT_TRANSPORT_ERROR);1337return;1338}13391340// We have JVMTI error. Call hotspot jni_FatalError handler1341jniFatalError(NULL, msg, error, EXIT_JVMTI_ERROR);13421343// hotspot calls os:abort() so we should never reach code below,1344// but guard against possible hotspot changes13451346// Last chance to die, this kills the entire process.1347forceExit(EXIT_JVMTI_ERROR);1348}134913501351