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 // Valid Arguments:
 246 // "-live" or "-all"
 247 // "parallelThreadNum=<N>"
 248 // "<filepath>"
 249 static jint process_heap_inspect_options(const char* argline,
 250                                          outputStream* out,
 251                                          HeapInspectArgs* args) {
 252   char* save_ptr;
 253   char* buf = NEW_C_HEAP_ARRAY(char, strlen(argline)+1, mtInternal);
 254   snprintf(buf, strlen(argline)+1, "%s", argline);
 255   if (buf == NULL) {
 256     return JNI_ERR;
 257   }
 258   char* arg = strtok_r(buf, ",", &save_ptr);
 259   while (arg != NULL) {
 260     // "-live" or "-all"
 261     if (strcmp(arg, "-live") == 0) {
 262       args->_live_object_only = true;
 263     } else if (strcmp(arg, "-all") == 0) {
 264       args->_live_object_only = false;
 265     } else if (strncmp(arg, "parallelThreadNum=", 18) == 0) {
 266       char* num_str = &arg[18];
 267       uintx num = 0;
 268       if (!Arguments::parse_uintx(num_str, &num, 0)) {
 269         out->print_cr("Invalid parallel thread number");
 270         return JNI_ERR;
 271       }
 272       args->_parallel_thread_num = num;
 273     } else {
 274       // must be file path
 275       assert(args->_path == NULL, "Must be");
 276       char* path = args->_path = NEW_C_HEAP_ARRAY(char, strlen(arg)+1, mtInternal);
 277       if (path == NULL) {
 278         out->print_cr("Out of internal memory.");
 279         return JNI_ERR;
 280       }
 281       snprintf(path, strlen(arg)+1, "%s", arg);
 282       if (path[0] == '\0') {
 283         out->print_cr("No dump file specified.");
 284       } else {
 285         fileStream* fs = new (ResourceObj::C_HEAP, mtInternal) fileStream(path);
 286         if (fs == NULL) {
 287           out->print_cr("Failed to allocate filestream for file: %s", path);
 288           return JNI_ERR;
 289         }
 290         args->_fs = fs;
 291       }
 292     }
 293    arg = strtok_r(NULL, ",", &save_ptr);
 294   }
 295   FREE_C_HEAP_ARRAY(char, buf);
 296   return JNI_OK;
 297 }
 298 
 299 // Parse command options
 300 static jint parse_cmd_options(const char* cmd, const char* argline,
 301                               outputStream* out, void* args) {
 302   assert(argline != NULL, "Must be");
 303   if (strncmp(cmd, "heap_inspection", 11) == 0) {
 304     HeapInspectArgs* insp_opts = (HeapInspectArgs*)args;
 305     return process_heap_inspect_options(argline, out, insp_opts);
 306   }
 307   // Command not match
 308   return JNI_ERR;
 309 }
 310 
 311 // Implementation of "inspectheap" command
 312 // See also: ClassHistogramDCmd class
 313 //
 314 // Input arguments :-
 315 //   all arguments in op->arg(0);
 316 static jint heap_inspection(AttachOperation* op, outputStream* out) {
 317   bool live_objects_only = true;   // default is true to retain the behavior before this change is made
 318   outputStream* os = out;   // if path not specified or path is NULL, use out
 319   const char* arg0 = op->arg(0);
 320   size_t parallel_thread_num = os::processor_count() * 3 / 8; // default is less than half of processors.
 321   HeapInspectArgs args;
 322   // Parse arguments
 323   if (arg0 != NULL) {
 324     if (JNI_ERR == parse_cmd_options("heap_inspection", arg0, out, (void*)(&args))) {
 325       return JNI_ERR;
 326     }
 327     live_objects_only = args._live_object_only;
 328     os = args._fs == NULL ? out : args._fs;
 329     parallel_thread_num = args._parallel_thread_num == 0 ? parallel_thread_num : args._parallel_thread_num;
 330     if (parallel_thread_num == 0) {
 331       // processor_count() <= 2, disable parallel.
 332       parallel_thread_num = 1;
 333     }
 334   }
 335 
 336   VM_GC_HeapInspection heapop(os, live_objects_only /* request full gc */, parallel_thread_num);
 337   VMThread::execute(&heapop);
 338   if (args._path != NULL) {
 339     out->print_cr("Heap inspection file created: %s", args._path);
 340   }
 341   return JNI_OK;
 342 }
 343 
 344 // Implementation of "setflag" command
 345 static jint set_flag(AttachOperation* op, outputStream* out) {
 346 
 347   const char* name = NULL;
 348   if ((name = op->arg(0)) == NULL) {
 349     out->print_cr("flag name is missing");
 350     return JNI_ERR;
 351   }
 352 
 353   FormatBuffer<80> err_msg("%s", "");
 354 
 355   int ret = WriteableFlags::set_flag(op->arg(0), op->arg(1), JVMFlag::ATTACH_ON_DEMAND, err_msg);
 356   if (ret != JVMFlag::SUCCESS) {
 357     if (ret == JVMFlag::NON_WRITABLE) {
 358       // if the flag is not manageable try to change it through
 359       // the platform dependent implementation
 360       return AttachListener::pd_set_flag(op, out);
 361     } else {
 362       out->print_cr("%s", err_msg.buffer());
 363     }
 364 
 365     return JNI_ERR;
 366   }
 367   return JNI_OK;
 368 }
 369 
 370 // Implementation of "printflag" command
 371 // See also: PrintVMFlagsDCmd class
 372 static jint print_flag(AttachOperation* op, outputStream* out) {
 373   const char* name = NULL;
 374   if ((name = op->arg(0)) == NULL) {
 375     out->print_cr("flag name is missing");
 376     return JNI_ERR;
 377   }
 378   JVMFlag* f = JVMFlag::find_flag(name);
 379   if (f) {
 380     f->print_as_flag(out);
 381     out->cr();
 382   } else {
 383     out->print_cr("no such flag '%s'", name);
 384   }
 385   return JNI_OK;
 386 }
 387 
 388 // Table to map operation names to functions.
 389 
 390 // names must be of length <= AttachOperation::name_length_max
 391 static AttachOperationFunctionInfo funcs[] = {
 392   { "agentProperties",  get_agent_properties },
 393   { "datadump",         data_dump },
 394   { "dumpheap",         dump_heap },
 395   { "load",             load_agent },
 396   { "properties",       get_system_properties },
 397   { "threaddump",       thread_dump },
 398   { "inspectheap",      heap_inspection },
 399   { "setflag",          set_flag },
 400   { "printflag",        print_flag },
 401   { "jcmd",             jcmd },
 402   { NULL,               NULL }
 403 };
 404 
 405 
 406 
 407 // The Attach Listener threads services a queue. It dequeues an operation
 408 // from the queue, examines the operation name (command), and dispatches
 409 // to the corresponding function to perform the operation.
 410 
 411 static void attach_listener_thread_entry(JavaThread* thread, TRAPS) {
 412   os::set_priority(thread, NearMaxPriority);
 413 
 414   assert(thread == Thread::current(), "Must be");
 415   assert(thread->stack_base() != NULL && thread->stack_size() > 0,
 416          "Should already be setup");
 417 
 418   if (AttachListener::pd_init() != 0) {
 419     AttachListener::set_state(AL_NOT_INITIALIZED);
 420     return;
 421   }
 422   AttachListener::set_initialized();
 423 
 424   for (;;) {
 425     AttachOperation* op = AttachListener::dequeue();
 426     if (op == NULL) {
 427       AttachListener::set_state(AL_NOT_INITIALIZED);
 428       return;   // dequeue failed or shutdown
 429     }
 430 
 431     ResourceMark rm;
 432     bufferedStream st;
 433     jint res = JNI_OK;
 434 
 435     // handle special detachall operation
 436     if (strcmp(op->name(), AttachOperation::detachall_operation_name()) == 0) {
 437       AttachListener::detachall();
 438     } else if (!EnableDynamicAgentLoading && strcmp(op->name(), "load") == 0) {
 439       st.print("Dynamic agent loading is not enabled. "
 440                "Use -XX:+EnableDynamicAgentLoading to launch target VM.");
 441       res = JNI_ERR;
 442     } else {
 443       // find the function to dispatch too
 444       AttachOperationFunctionInfo* info = NULL;
 445       for (int i=0; funcs[i].name != NULL; i++) {
 446         const char* name = funcs[i].name;
 447         assert(strlen(name) <= AttachOperation::name_length_max, "operation <= name_length_max");
 448         if (strcmp(op->name(), name) == 0) {
 449           info = &(funcs[i]);
 450           break;
 451         }
 452       }
 453 
 454       // check for platform dependent attach operation
 455       if (info == NULL) {
 456         info = AttachListener::pd_find_operation(op->name());
 457       }
 458 
 459       if (info != NULL) {
 460         // dispatch to the function that implements this operation
 461         res = (info->func)(op, &st);
 462       } else {
 463         st.print("Operation %s not recognized!", op->name());
 464         res = JNI_ERR;
 465       }
 466     }
 467 
 468     // operation complete - send result and output to client
 469     op->complete(res, &st);
 470   }
 471 
 472   ShouldNotReachHere();
 473 }
 474 
 475 bool AttachListener::has_init_error(TRAPS) {
 476   if (HAS_PENDING_EXCEPTION) {
 477     tty->print_cr("Exception in VM (AttachListener::init) : ");
 478     java_lang_Throwable::print(PENDING_EXCEPTION, tty);
 479     tty->cr();
 480 
 481     CLEAR_PENDING_EXCEPTION;
 482 
 483     return true;
 484   } else {
 485     return false;
 486   }
 487 }
 488 
 489 // Starts the Attach Listener thread
 490 void AttachListener::init() {
 491   EXCEPTION_MARK;
 492 
 493   const char thread_name[] = "Attach Listener";
 494   Handle string = java_lang_String::create_from_str(thread_name, THREAD);
 495   if (has_init_error(THREAD)) {
 496     set_state(AL_NOT_INITIALIZED);
 497     return;
 498   }
 499 
 500   // Initialize thread_oop to put it into the system threadGroup
 501   Handle thread_group (THREAD, Universe::system_thread_group());
 502   Handle thread_oop = JavaCalls::construct_new_instance(SystemDictionary::Thread_klass(),
 503                        vmSymbols::threadgroup_string_void_signature(),
 504                        thread_group,
 505                        string,
 506                        THREAD);
 507   if (has_init_error(THREAD)) {
 508     set_state(AL_NOT_INITIALIZED);
 509     return;
 510   }
 511 
 512   Klass* group = SystemDictionary::ThreadGroup_klass();
 513   JavaValue result(T_VOID);
 514   JavaCalls::call_special(&result,
 515                         thread_group,
 516                         group,
 517                         vmSymbols::add_method_name(),
 518                         vmSymbols::thread_void_signature(),
 519                         thread_oop,
 520                         THREAD);
 521   if (has_init_error(THREAD)) {
 522     set_state(AL_NOT_INITIALIZED);
 523     return;
 524   }
 525 
 526   { MutexLocker mu(THREAD, Threads_lock);
 527     JavaThread* listener_thread = new JavaThread(&attach_listener_thread_entry);
 528 
 529     // Check that thread and osthread were created
 530     if (listener_thread == NULL || listener_thread->osthread() == NULL) {
 531       vm_exit_during_initialization("java.lang.OutOfMemoryError",
 532                                     os::native_thread_creation_failed_msg());
 533     }
 534 
 535     java_lang_Thread::set_thread(thread_oop(), listener_thread);
 536     java_lang_Thread::set_daemon(thread_oop());
 537 
 538     listener_thread->set_threadObj(thread_oop());
 539     Threads::add(listener_thread);
 540     Thread::start(listener_thread);
 541   }
 542 }
 543 
 544 // Performs clean-up tasks on platforms where we can detect that the last
 545 // client has detached
 546 void AttachListener::detachall() {
 547   // call the platform dependent clean-up
 548   pd_detachall();
 549 }