1 /*
   2  * Copyright (c) 2005, 2020, 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.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/javaClasses.hpp"
  27 #include "classfile/systemDictionary.hpp"
  28 #include "gc/shared/gcVMOperations.hpp"
  29 #include "memory/resourceArea.hpp"
  30 #include "memory/universe.hpp"
  31 #include "oops/oop.inline.hpp"
  32 #include "oops/typeArrayOop.inline.hpp"
  33 #include "prims/jvmtiExport.hpp"
  34 #include "runtime/arguments.hpp"
  35 #include "runtime/flags/jvmFlag.hpp"
  36 #include "runtime/globals.hpp"
  37 #include "runtime/handles.inline.hpp"
  38 #include "runtime/java.hpp"
  39 #include "runtime/javaCalls.hpp"
  40 #include "runtime/os.hpp"
  41 #include "services/attachListener.hpp"
  42 #include "services/diagnosticCommand.hpp"
  43 #include "services/heapDumper.hpp"
  44 #include "services/writeableFlags.hpp"
  45 #include "utilities/debug.hpp"
  46 #include "utilities/formatBuffer.hpp"
  47 
  48 volatile AttachListenerState AttachListener::_state = AL_NOT_INITIALIZED;
  49 
  50 // Implementation of "properties" command.
  51 //
  52 // Invokes VMSupport.serializePropertiesToByteArray to serialize
  53 // the system properties into a byte array.
  54 
  55 static InstanceKlass* load_and_initialize_klass(Symbol* sh, TRAPS) {
  56   Klass* k = SystemDictionary::resolve_or_fail(sh, true, CHECK_NULL);
  57   InstanceKlass* ik = InstanceKlass::cast(k);
  58   if (ik->should_be_initialized()) {
  59     ik->initialize(CHECK_NULL);
  60   }
  61   return ik;
  62 }
  63 
  64 static jint get_properties(AttachOperation* op, outputStream* out, Symbol* serializePropertiesMethod) {
  65   Thread* THREAD = Thread::current();
  66   HandleMark hm;
  67 
  68   // load VMSupport
  69   Symbol* klass = vmSymbols::jdk_internal_vm_VMSupport();
  70   InstanceKlass* k = load_and_initialize_klass(klass, THREAD);
  71   if (HAS_PENDING_EXCEPTION) {
  72     java_lang_Throwable::print(PENDING_EXCEPTION, out);
  73     CLEAR_PENDING_EXCEPTION;
  74     return JNI_ERR;
  75   }
  76 
  77   // invoke the serializePropertiesToByteArray method
  78   JavaValue result(T_OBJECT);
  79   JavaCallArguments args;
  80 
  81 
  82   Symbol* signature = vmSymbols::serializePropertiesToByteArray_signature();
  83   JavaCalls::call_static(&result,
  84                          k,
  85                          serializePropertiesMethod,
  86                          signature,
  87                          &args,
  88                          THREAD);
  89   if (HAS_PENDING_EXCEPTION) {
  90     java_lang_Throwable::print(PENDING_EXCEPTION, out);
  91     CLEAR_PENDING_EXCEPTION;
  92     return JNI_ERR;
  93   }
  94 
  95   // The result should be a [B
  96   oop res = (oop)result.get_jobject();
  97   assert(res->is_typeArray(), "just checking");
  98   assert(TypeArrayKlass::cast(res->klass())->element_type() == T_BYTE, "just checking");
  99 
 100   // copy the bytes to the output stream
 101   typeArrayOop ba = typeArrayOop(res);
 102   jbyte* addr = typeArrayOop(res)->byte_at_addr(0);
 103   out->print_raw((const char*)addr, ba->length());
 104 
 105   return JNI_OK;
 106 }
 107 
 108 // Implementation of "load" command.
 109 static jint load_agent(AttachOperation* op, outputStream* out) {
 110   // get agent name and options
 111   const char* agent = op->arg(0);
 112   const char* absParam = op->arg(1);
 113   const char* options = op->arg(2);
 114 
 115   // If loading a java agent then need to ensure that the java.instrument module is loaded
 116   if (strcmp(agent, "instrument") == 0) {
 117     Thread* THREAD = Thread::current();
 118     ResourceMark rm(THREAD);
 119     HandleMark hm(THREAD);
 120     JavaValue result(T_OBJECT);
 121     Handle h_module_name = java_lang_String::create_from_str("java.instrument", THREAD);
 122     JavaCalls::call_static(&result,
 123                            SystemDictionary::module_Modules_klass(),
 124                            vmSymbols::loadModule_name(),
 125                            vmSymbols::loadModule_signature(),
 126                            h_module_name,
 127                            THREAD);
 128     if (HAS_PENDING_EXCEPTION) {
 129       java_lang_Throwable::print(PENDING_EXCEPTION, out);
 130       CLEAR_PENDING_EXCEPTION;
 131       return JNI_ERR;
 132     }
 133   }
 134 
 135   return JvmtiExport::load_agent_library(agent, absParam, options, out);
 136 }
 137 
 138 // Implementation of "properties" command.
 139 // See also: PrintSystemPropertiesDCmd class
 140 static jint get_system_properties(AttachOperation* op, outputStream* out) {
 141   return get_properties(op, out, vmSymbols::serializePropertiesToByteArray_name());
 142 }
 143 
 144 // Implementation of "agent_properties" command.
 145 static jint get_agent_properties(AttachOperation* op, outputStream* out) {
 146   return get_properties(op, out, vmSymbols::serializeAgentPropertiesToByteArray_name());
 147 }
 148 
 149 // Implementation of "datadump" command.
 150 //
 151 // Raises a SIGBREAK signal so that VM dump threads, does deadlock detection,
 152 // etc. In theory this command should only post a DataDumpRequest to any
 153 // JVMTI environment that has enabled this event. However it's useful to
 154 // trigger the SIGBREAK handler.
 155 
 156 static jint data_dump(AttachOperation* op, outputStream* out) {
 157   if (!ReduceSignalUsage) {
 158     AttachListener::pd_data_dump();
 159   } else {
 160     if (JvmtiExport::should_post_data_dump()) {
 161       JvmtiExport::post_data_dump();
 162     }
 163   }
 164   return JNI_OK;
 165 }
 166 
 167 // Implementation of "threaddump" command - essentially a remote ctrl-break
 168 // See also: ThreadDumpDCmd class
 169 //
 170 static jint thread_dump(AttachOperation* op, outputStream* out) {
 171   bool print_concurrent_locks = false;
 172   bool print_extended_info = false;
 173   if (op->arg(0) != NULL) {
 174     for (int i = 0; op->arg(0)[i] != 0; ++i) {
 175       if (op->arg(0)[i] == 'l') {
 176         print_concurrent_locks = true;
 177       }
 178       if (op->arg(0)[i] == 'e') {
 179         print_extended_info = true;
 180       }
 181     }
 182   }
 183 
 184   // thread stacks
 185   VM_PrintThreads op1(out, print_concurrent_locks, print_extended_info);
 186   VMThread::execute(&op1);
 187 
 188   // JNI global handles
 189   VM_PrintJNI op2(out);
 190   VMThread::execute(&op2);
 191 
 192   // Deadlock detection
 193   VM_FindDeadlocks op3(out);
 194   VMThread::execute(&op3);
 195 
 196   return JNI_OK;
 197 }
 198 
 199 // A jcmd attach operation request was received, which will now
 200 // dispatch to the diagnostic commands used for serviceability functions.
 201 static jint jcmd(AttachOperation* op, outputStream* out) {
 202   Thread* THREAD = Thread::current();
 203   // All the supplied jcmd arguments are stored as a single
 204   // string (op->arg(0)). This is parsed by the Dcmd framework.
 205   DCmd::parse_and_execute(DCmd_Source_AttachAPI, out, op->arg(0), ' ', THREAD);
 206   if (HAS_PENDING_EXCEPTION) {
 207     java_lang_Throwable::print(PENDING_EXCEPTION, out);
 208     out->cr();
 209     CLEAR_PENDING_EXCEPTION;
 210     return JNI_ERR;
 211   }
 212   return JNI_OK;
 213 }
 214 
 215 // Implementation of "dumpheap" command.
 216 // See also: HeapDumpDCmd class
 217 //
 218 // Input arguments :-
 219 //   arg0: Name of the dump file
 220 //   arg1: "-live" or "-all"
 221 jint dump_heap(AttachOperation* op, outputStream* out) {
 222   const char* path = op->arg(0);
 223   if (path == NULL || path[0] == '\0') {
 224     out->print_cr("No dump file specified");
 225   } else {
 226     bool live_objects_only = true;   // default is true to retain the behavior before this change is made
 227     const char* arg1 = op->arg(1);
 228     if (arg1 != NULL && (strlen(arg1) > 0)) {
 229       if (strcmp(arg1, "-all") != 0 && strcmp(arg1, "-live") != 0) {
 230         out->print_cr("Invalid argument to dumpheap operation: %s", arg1);
 231         return JNI_ERR;
 232       }
 233       live_objects_only = strcmp(arg1, "-live") == 0;
 234     }
 235 
 236     // Request a full GC before heap dump if live_objects_only = true
 237     // This helps reduces the amount of unreachable objects in the dump
 238     // and makes it easier to browse.
 239     HeapDumper dumper(live_objects_only /* request GC */);
 240     dumper.dump(op->arg(0), out);
 241   }
 242   return JNI_OK;
 243 }
 244 


































































 245 // Implementation of "inspectheap" command
 246 // See also: ClassHistogramDCmd class
 247 //
 248 // Input arguments :-
 249 //   arg0: "-live" or "-all"
 250 //   arg1: Name of the dump file or NULL
 251 static jint heap_inspection(AttachOperation* op, outputStream* out) {
 252   bool live_objects_only = true;   // default is true to retain the behavior before this change is made
 253   outputStream* os = out;   // if path not specified or path is NULL, use out
 254   fileStream* fs = NULL;
 255   const char* arg0 = op->arg(0);
 256   if (arg0 != NULL && (strlen(arg0) > 0)) {
 257     if (strcmp(arg0, "-all") != 0 && strcmp(arg0, "-live") != 0) {
 258       out->print_cr("Invalid argument to inspectheap operation: %s", arg0);
 259       return JNI_ERR;
 260     }
 261     live_objects_only = strcmp(arg0, "-live") == 0;
 262   }
 263 
 264   const char* path = op->arg(1);
 265   if (path != NULL) {
 266     if (path[0] == '\0') {
 267       out->print_cr("No dump file specified");
 268     } else {
 269       // create file
 270       fs = new (ResourceObj::C_HEAP, mtInternal) fileStream(path);
 271       if (fs == NULL) {
 272         out->print_cr("Failed to allocate space for file: %s", path);
 273         return JNI_ERR;
 274       }
 275       os = fs;





 276     }
 277   }
 278 
 279   VM_GC_HeapInspection heapop(os, live_objects_only /* request full gc */);
 280   VMThread::execute(&heapop);
 281   if (os != NULL && os != out) {
 282     out->print_cr("Heap inspection file created: %s", path);
 283     delete fs;
 284   }
 285   return JNI_OK;
 286 }
 287 
 288 // Implementation of "setflag" command
 289 static jint set_flag(AttachOperation* op, outputStream* out) {
 290 
 291   const char* name = NULL;
 292   if ((name = op->arg(0)) == NULL) {
 293     out->print_cr("flag name is missing");
 294     return JNI_ERR;
 295   }
 296 
 297   FormatBuffer<80> err_msg("%s", "");
 298 
 299   int ret = WriteableFlags::set_flag(op->arg(0), op->arg(1), JVMFlag::ATTACH_ON_DEMAND, err_msg);
 300   if (ret != JVMFlag::SUCCESS) {
 301     if (ret == JVMFlag::NON_WRITABLE) {
 302       // if the flag is not manageable try to change it through
 303       // the platform dependent implementation
 304       return AttachListener::pd_set_flag(op, out);
 305     } else {
 306       out->print_cr("%s", err_msg.buffer());
 307     }
 308 
 309     return JNI_ERR;
 310   }
 311   return JNI_OK;
 312 }
 313 
 314 // Implementation of "printflag" command
 315 // See also: PrintVMFlagsDCmd class
 316 static jint print_flag(AttachOperation* op, outputStream* out) {
 317   const char* name = NULL;
 318   if ((name = op->arg(0)) == NULL) {
 319     out->print_cr("flag name is missing");
 320     return JNI_ERR;
 321   }
 322   JVMFlag* f = JVMFlag::find_flag(name);
 323   if (f) {
 324     f->print_as_flag(out);
 325     out->cr();
 326   } else {
 327     out->print_cr("no such flag '%s'", name);
 328   }
 329   return JNI_OK;
 330 }
 331 
 332 // Table to map operation names to functions.
 333 
 334 // names must be of length <= AttachOperation::name_length_max
 335 static AttachOperationFunctionInfo funcs[] = {
 336   { "agentProperties",  get_agent_properties },
 337   { "datadump",         data_dump },
 338   { "dumpheap",         dump_heap },
 339   { "load",             load_agent },
 340   { "properties",       get_system_properties },
 341   { "threaddump",       thread_dump },
 342   { "inspectheap",      heap_inspection },
 343   { "setflag",          set_flag },
 344   { "printflag",        print_flag },
 345   { "jcmd",             jcmd },
 346   { NULL,               NULL }
 347 };
 348 
 349 
 350 
 351 // The Attach Listener threads services a queue. It dequeues an operation
 352 // from the queue, examines the operation name (command), and dispatches
 353 // to the corresponding function to perform the operation.
 354 
 355 static void attach_listener_thread_entry(JavaThread* thread, TRAPS) {
 356   os::set_priority(thread, NearMaxPriority);
 357 
 358   assert(thread == Thread::current(), "Must be");
 359   assert(thread->stack_base() != NULL && thread->stack_size() > 0,
 360          "Should already be setup");
 361 
 362   if (AttachListener::pd_init() != 0) {
 363     AttachListener::set_state(AL_NOT_INITIALIZED);
 364     return;
 365   }
 366   AttachListener::set_initialized();
 367 
 368   for (;;) {
 369     AttachOperation* op = AttachListener::dequeue();
 370     if (op == NULL) {
 371       AttachListener::set_state(AL_NOT_INITIALIZED);
 372       return;   // dequeue failed or shutdown
 373     }
 374 
 375     ResourceMark rm;
 376     bufferedStream st;
 377     jint res = JNI_OK;
 378 
 379     // handle special detachall operation
 380     if (strcmp(op->name(), AttachOperation::detachall_operation_name()) == 0) {
 381       AttachListener::detachall();
 382     } else if (!EnableDynamicAgentLoading && strcmp(op->name(), "load") == 0) {
 383       st.print("Dynamic agent loading is not enabled. "
 384                "Use -XX:+EnableDynamicAgentLoading to launch target VM.");
 385       res = JNI_ERR;
 386     } else {
 387       // find the function to dispatch too
 388       AttachOperationFunctionInfo* info = NULL;
 389       for (int i=0; funcs[i].name != NULL; i++) {
 390         const char* name = funcs[i].name;
 391         assert(strlen(name) <= AttachOperation::name_length_max, "operation <= name_length_max");
 392         if (strcmp(op->name(), name) == 0) {
 393           info = &(funcs[i]);
 394           break;
 395         }
 396       }
 397 
 398       // check for platform dependent attach operation
 399       if (info == NULL) {
 400         info = AttachListener::pd_find_operation(op->name());
 401       }
 402 
 403       if (info != NULL) {
 404         // dispatch to the function that implements this operation
 405         res = (info->func)(op, &st);
 406       } else {
 407         st.print("Operation %s not recognized!", op->name());
 408         res = JNI_ERR;
 409       }
 410     }
 411 
 412     // operation complete - send result and output to client
 413     op->complete(res, &st);
 414   }
 415 
 416   ShouldNotReachHere();
 417 }
 418 
 419 bool AttachListener::has_init_error(TRAPS) {
 420   if (HAS_PENDING_EXCEPTION) {
 421     tty->print_cr("Exception in VM (AttachListener::init) : ");
 422     java_lang_Throwable::print(PENDING_EXCEPTION, tty);
 423     tty->cr();
 424 
 425     CLEAR_PENDING_EXCEPTION;
 426 
 427     return true;
 428   } else {
 429     return false;
 430   }
 431 }
 432 
 433 // Starts the Attach Listener thread
 434 void AttachListener::init() {
 435   EXCEPTION_MARK;
 436 
 437   const char thread_name[] = "Attach Listener";
 438   Handle string = java_lang_String::create_from_str(thread_name, THREAD);
 439   if (has_init_error(THREAD)) {
 440     set_state(AL_NOT_INITIALIZED);
 441     return;
 442   }
 443 
 444   // Initialize thread_oop to put it into the system threadGroup
 445   Handle thread_group (THREAD, Universe::system_thread_group());
 446   Handle thread_oop = JavaCalls::construct_new_instance(SystemDictionary::Thread_klass(),
 447                        vmSymbols::threadgroup_string_void_signature(),
 448                        thread_group,
 449                        string,
 450                        THREAD);
 451   if (has_init_error(THREAD)) {
 452     set_state(AL_NOT_INITIALIZED);
 453     return;
 454   }
 455 
 456   Klass* group = SystemDictionary::ThreadGroup_klass();
 457   JavaValue result(T_VOID);
 458   JavaCalls::call_special(&result,
 459                         thread_group,
 460                         group,
 461                         vmSymbols::add_method_name(),
 462                         vmSymbols::thread_void_signature(),
 463                         thread_oop,
 464                         THREAD);
 465   if (has_init_error(THREAD)) {
 466     set_state(AL_NOT_INITIALIZED);
 467     return;
 468   }
 469 
 470   { MutexLocker mu(THREAD, Threads_lock);
 471     JavaThread* listener_thread = new JavaThread(&attach_listener_thread_entry);
 472 
 473     // Check that thread and osthread were created
 474     if (listener_thread == NULL || listener_thread->osthread() == NULL) {
 475       vm_exit_during_initialization("java.lang.OutOfMemoryError",
 476                                     os::native_thread_creation_failed_msg());
 477     }
 478 
 479     java_lang_Thread::set_thread(thread_oop(), listener_thread);
 480     java_lang_Thread::set_daemon(thread_oop());
 481 
 482     listener_thread->set_threadObj(thread_oop());
 483     Threads::add(listener_thread);
 484     Thread::start(listener_thread);
 485   }
 486 }
 487 
 488 // Performs clean-up tasks on platforms where we can detect that the last
 489 // client has detached
 490 void AttachListener::detachall() {
 491   // call the platform dependent clean-up
 492   pd_detachall();
 493 }
--- EOF ---