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