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 // "parallel=<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, "parallel=", 9) == 0) { 266 char* num_str = &arg[9]; 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 parallel_thread_num = 1; 332 } 333 } 334 335 VM_GC_HeapInspection heapop(os, live_objects_only /* request full gc */, parallel_thread_num); 336 VMThread::execute(&heapop); 337 if (args._path != NULL) { 338 out->print_cr("Heap inspection file created: %s", args._path); 339 } 340 return JNI_OK; 341 } 342 343 // Implementation of "setflag" command 344 static jint set_flag(AttachOperation* op, outputStream* out) { 345 346 const char* name = NULL; 347 if ((name = op->arg(0)) == NULL) { 348 out->print_cr("flag name is missing"); 349 return JNI_ERR; 350 } 351 352 FormatBuffer<80> err_msg("%s", ""); 353 354 int ret = WriteableFlags::set_flag(op->arg(0), op->arg(1), JVMFlag::ATTACH_ON_DEMAND, err_msg); 355 if (ret != JVMFlag::SUCCESS) { 356 if (ret == JVMFlag::NON_WRITABLE) { 357 // if the flag is not manageable try to change it through 358 // the platform dependent implementation 359 return AttachListener::pd_set_flag(op, out); 360 } else { 361 out->print_cr("%s", err_msg.buffer()); 362 } 363 364 return JNI_ERR; 365 } 366 return JNI_OK; 367 } 368 369 // Implementation of "printflag" command 370 // See also: PrintVMFlagsDCmd class 371 static jint print_flag(AttachOperation* op, outputStream* out) { 372 const char* name = NULL; 373 if ((name = op->arg(0)) == NULL) { 374 out->print_cr("flag name is missing"); 375 return JNI_ERR; 376 } 377 JVMFlag* f = JVMFlag::find_flag(name); 378 if (f) { 379 f->print_as_flag(out); 380 out->cr(); 381 } else { 382 out->print_cr("no such flag '%s'", name); 383 } 384 return JNI_OK; 385 } 386 387 // Table to map operation names to functions. 388 389 // names must be of length <= AttachOperation::name_length_max 390 static AttachOperationFunctionInfo funcs[] = { 391 { "agentProperties", get_agent_properties }, 392 { "datadump", data_dump }, 393 { "dumpheap", dump_heap }, 394 { "load", load_agent }, 395 { "properties", get_system_properties }, 396 { "threaddump", thread_dump }, 397 { "inspectheap", heap_inspection }, 398 { "setflag", set_flag }, 399 { "printflag", print_flag }, 400 { "jcmd", jcmd }, 401 { NULL, NULL } 402 }; 403 404 405 406 // The Attach Listener threads services a queue. It dequeues an operation 407 // from the queue, examines the operation name (command), and dispatches 408 // to the corresponding function to perform the operation. 409 410 static void attach_listener_thread_entry(JavaThread* thread, TRAPS) { 411 os::set_priority(thread, NearMaxPriority); 412 413 assert(thread == Thread::current(), "Must be"); 414 assert(thread->stack_base() != NULL && thread->stack_size() > 0, 415 "Should already be setup"); 416 417 if (AttachListener::pd_init() != 0) { 418 AttachListener::set_state(AL_NOT_INITIALIZED); 419 return; 420 } 421 AttachListener::set_initialized(); 422 423 for (;;) { 424 AttachOperation* op = AttachListener::dequeue(); 425 if (op == NULL) { 426 AttachListener::set_state(AL_NOT_INITIALIZED); 427 return; // dequeue failed or shutdown 428 } 429 430 ResourceMark rm; 431 bufferedStream st; 432 jint res = JNI_OK; 433 434 // handle special detachall operation 435 if (strcmp(op->name(), AttachOperation::detachall_operation_name()) == 0) { 436 AttachListener::detachall(); 437 } else if (!EnableDynamicAgentLoading && strcmp(op->name(), "load") == 0) { 438 st.print("Dynamic agent loading is not enabled. " 439 "Use -XX:+EnableDynamicAgentLoading to launch target VM."); 440 res = JNI_ERR; 441 } else { 442 // find the function to dispatch too 443 AttachOperationFunctionInfo* info = NULL; 444 for (int i=0; funcs[i].name != NULL; i++) { 445 const char* name = funcs[i].name; 446 assert(strlen(name) <= AttachOperation::name_length_max, "operation <= name_length_max"); 447 if (strcmp(op->name(), name) == 0) { 448 info = &(funcs[i]); 449 break; 450 } 451 } 452 453 // check for platform dependent attach operation 454 if (info == NULL) { 455 info = AttachListener::pd_find_operation(op->name()); 456 } 457 458 if (info != NULL) { 459 // dispatch to the function that implements this operation 460 res = (info->func)(op, &st); 461 } else { 462 st.print("Operation %s not recognized!", op->name()); 463 res = JNI_ERR; 464 } 465 } 466 467 // operation complete - send result and output to client 468 op->complete(res, &st); 469 } 470 471 ShouldNotReachHere(); 472 } 473 474 bool AttachListener::has_init_error(TRAPS) { 475 if (HAS_PENDING_EXCEPTION) { 476 tty->print_cr("Exception in VM (AttachListener::init) : "); 477 java_lang_Throwable::print(PENDING_EXCEPTION, tty); 478 tty->cr(); 479 480 CLEAR_PENDING_EXCEPTION; 481 482 return true; 483 } else { 484 return false; 485 } 486 } 487 488 // Starts the Attach Listener thread 489 void AttachListener::init() { 490 EXCEPTION_MARK; 491 492 const char thread_name[] = "Attach Listener"; 493 Handle string = java_lang_String::create_from_str(thread_name, THREAD); 494 if (has_init_error(THREAD)) { 495 set_state(AL_NOT_INITIALIZED); 496 return; 497 } 498 499 // Initialize thread_oop to put it into the system threadGroup 500 Handle thread_group (THREAD, Universe::system_thread_group()); 501 Handle thread_oop = JavaCalls::construct_new_instance(SystemDictionary::Thread_klass(), 502 vmSymbols::threadgroup_string_void_signature(), 503 thread_group, 504 string, 505 THREAD); 506 if (has_init_error(THREAD)) { 507 set_state(AL_NOT_INITIALIZED); 508 return; 509 } 510 511 Klass* group = SystemDictionary::ThreadGroup_klass(); 512 JavaValue result(T_VOID); 513 JavaCalls::call_special(&result, 514 thread_group, 515 group, 516 vmSymbols::add_method_name(), 517 vmSymbols::thread_void_signature(), 518 thread_oop, 519 THREAD); 520 if (has_init_error(THREAD)) { 521 set_state(AL_NOT_INITIALIZED); 522 return; 523 } 524 525 { MutexLocker mu(THREAD, Threads_lock); 526 JavaThread* listener_thread = new JavaThread(&attach_listener_thread_entry); 527 528 // Check that thread and osthread were created 529 if (listener_thread == NULL || listener_thread->osthread() == NULL) { 530 vm_exit_during_initialization("java.lang.OutOfMemoryError", 531 os::native_thread_creation_failed_msg()); 532 } 533 534 java_lang_Thread::set_thread(thread_oop(), listener_thread); 535 java_lang_Thread::set_daemon(thread_oop()); 536 537 listener_thread->set_threadObj(thread_oop()); 538 Threads::add(listener_thread); 539 Thread::start(listener_thread); 540 } 541 } 542 543 // Performs clean-up tasks on platforms where we can detect that the last 544 // client has detached 545 void AttachListener::detachall() { 546 // call the platform dependent clean-up 547 pd_detachall(); 548 }