1 /* 2 * Copyright (c) 2005, 2019, 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/mutexLocker.inline.hpp" 41 #include "runtime/os.hpp" 42 #include "services/attachListener.hpp" 43 #include "services/diagnosticCommand.hpp" 44 #include "services/heapDumper.hpp" 45 #include "services/writeableFlags.hpp" 46 #include "utilities/debug.hpp" 47 #include "utilities/formatBuffer.hpp" 48 49 volatile AttachListenerState AttachListener::_state = AL_NOT_INITIALIZED; 50 51 // Implementation of "properties" command. 52 // 53 // Invokes VMSupport.serializePropertiesToByteArray to serialize 54 // the system properties into a byte array. 55 56 static InstanceKlass* load_and_initialize_klass(Symbol* sh, TRAPS) { 57 Klass* k = SystemDictionary::resolve_or_fail(sh, true, CHECK_NULL); 58 InstanceKlass* ik = InstanceKlass::cast(k); 59 if (ik->should_be_initialized()) { 60 ik->initialize(CHECK_NULL); 61 } 62 return ik; 63 } 64 65 static jint get_properties(AttachOperation* op, outputStream* out, Symbol* serializePropertiesMethod) { 66 Thread* THREAD = Thread::current(); 67 HandleMark hm; 68 69 // load VMSupport 70 Symbol* klass = vmSymbols::jdk_internal_vm_VMSupport(); 71 InstanceKlass* k = load_and_initialize_klass(klass, THREAD); 72 if (HAS_PENDING_EXCEPTION) { 73 java_lang_Throwable::print(PENDING_EXCEPTION, out); 74 CLEAR_PENDING_EXCEPTION; 75 return JNI_ERR; 76 } 77 78 // invoke the serializePropertiesToByteArray method 79 JavaValue result(T_OBJECT); 80 JavaCallArguments args; 81 82 83 Symbol* signature = vmSymbols::serializePropertiesToByteArray_signature(); 84 JavaCalls::call_static(&result, 85 k, 86 serializePropertiesMethod, 87 signature, 88 &args, 89 THREAD); 90 if (HAS_PENDING_EXCEPTION) { 91 java_lang_Throwable::print(PENDING_EXCEPTION, out); 92 CLEAR_PENDING_EXCEPTION; 93 return JNI_ERR; 94 } 95 96 // The result should be a [B 97 oop res = (oop)result.get_jobject(); 98 assert(res->is_typeArray(), "just checking"); 99 assert(TypeArrayKlass::cast(res->klass())->element_type() == T_BYTE, "just checking"); 100 101 // copy the bytes to the output stream 102 typeArrayOop ba = typeArrayOop(res); 103 jbyte* addr = typeArrayOop(res)->byte_at_addr(0); 104 out->print_raw((const char*)addr, ba->length()); 105 106 return JNI_OK; 107 } 108 109 // Implementation of "load" command. 110 static jint load_agent(AttachOperation* op, outputStream* out) { 111 // get agent name and options 112 const char* agent = op->arg(0); 113 const char* absParam = op->arg(1); 114 const char* options = op->arg(2); 115 116 // If loading a java agent then need to ensure that the java.instrument module is loaded 117 if (strcmp(agent, "instrument") == 0) { 118 Thread* THREAD = Thread::current(); 119 ResourceMark rm(THREAD); 120 HandleMark hm(THREAD); 121 JavaValue result(T_OBJECT); 122 Handle h_module_name = java_lang_String::create_from_str("java.instrument", THREAD); 123 JavaCalls::call_static(&result, 124 SystemDictionary::module_Modules_klass(), 125 vmSymbols::loadModule_name(), 126 vmSymbols::loadModule_signature(), 127 h_module_name, 128 THREAD); 129 if (HAS_PENDING_EXCEPTION) { 130 java_lang_Throwable::print(PENDING_EXCEPTION, out); 131 CLEAR_PENDING_EXCEPTION; 132 return JNI_ERR; 133 } 134 } 135 136 return JvmtiExport::load_agent_library(agent, absParam, options, out); 137 } 138 139 // Implementation of "properties" command. 140 // See also: PrintSystemPropertiesDCmd class 141 static jint get_system_properties(AttachOperation* op, outputStream* out) { 142 return get_properties(op, out, vmSymbols::serializePropertiesToByteArray_name()); 143 } 144 145 // Implementation of "agent_properties" command. 146 static jint get_agent_properties(AttachOperation* op, outputStream* out) { 147 return get_properties(op, out, vmSymbols::serializeAgentPropertiesToByteArray_name()); 148 } 149 150 // Implementation of "datadump" command. 151 // 152 // Raises a SIGBREAK signal so that VM dump threads, does deadlock detection, 153 // etc. In theory this command should only post a DataDumpRequest to any 154 // JVMTI environment that has enabled this event. However it's useful to 155 // trigger the SIGBREAK handler. 156 157 static jint data_dump(AttachOperation* op, outputStream* out) { 158 if (!ReduceSignalUsage) { 159 AttachListener::pd_data_dump(); 160 } else { 161 if (JvmtiExport::should_post_data_dump()) { 162 JvmtiExport::post_data_dump(); 163 } 164 } 165 return JNI_OK; 166 } 167 168 // Implementation of "threaddump" command - essentially a remote ctrl-break 169 // See also: ThreadDumpDCmd class 170 // 171 static jint thread_dump(AttachOperation* op, outputStream* out) { 172 bool print_concurrent_locks = false; 173 bool print_extended_info = false; 174 if (op->arg(0) != NULL) { 175 for (int i = 0; op->arg(0)[i] != 0; ++i) { 176 if (op->arg(0)[i] == 'l') { 177 print_concurrent_locks = true; 178 } 179 if (op->arg(0)[i] == 'e') { 180 print_extended_info = true; 181 } 182 } 183 } 184 185 // thread stacks 186 VM_PrintThreads op1(out, print_concurrent_locks, print_extended_info); 187 VMThread::execute(&op1); 188 189 // JNI global handles 190 VM_PrintJNI op2(out); 191 VMThread::execute(&op2); 192 193 // Deadlock detection 194 VM_FindDeadlocks op3(out); 195 VMThread::execute(&op3); 196 197 return JNI_OK; 198 } 199 200 // A jcmd attach operation request was received, which will now 201 // dispatch to the diagnostic commands used for serviceability functions. 202 static jint jcmd(AttachOperation* op, outputStream* out) { 203 Thread* THREAD = Thread::current(); 204 // All the supplied jcmd arguments are stored as a single 205 // string (op->arg(0)). This is parsed by the Dcmd framework. 206 DCmd::parse_and_execute(DCmd_Source_AttachAPI, out, op->arg(0), ' ', THREAD); 207 if (HAS_PENDING_EXCEPTION) { 208 java_lang_Throwable::print(PENDING_EXCEPTION, out); 209 out->cr(); 210 CLEAR_PENDING_EXCEPTION; 211 return JNI_ERR; 212 } 213 return JNI_OK; 214 } 215 216 // Implementation of "dumpheap" command. 217 // See also: HeapDumpDCmd class 218 // 219 // Input arguments :- 220 // arg0: Name of the dump file 221 // arg1: "-live" or "-all" 222 jint dump_heap(AttachOperation* op, outputStream* out) { 223 const char* path = op->arg(0); 224 if (path == NULL || path[0] == '\0') { 225 out->print_cr("No dump file specified"); 226 } else { 227 bool live_objects_only = true; // default is true to retain the behavior before this change is made 228 const char* arg1 = op->arg(1); 229 if (arg1 != NULL && (strlen(arg1) > 0)) { 230 if (strcmp(arg1, "-all") != 0 && strcmp(arg1, "-live") != 0) { 231 out->print_cr("Invalid argument to dumpheap operation: %s", arg1); 232 return JNI_ERR; 233 } 234 live_objects_only = strcmp(arg1, "-live") == 0; 235 } 236 237 // Request a full GC before heap dump if live_objects_only = true 238 // This helps reduces the amount of unreachable objects in the dump 239 // and makes it easier to browse. 240 HeapDumper dumper(live_objects_only /* request GC */); 241 int res = dumper.dump(op->arg(0)); 242 if (res == 0) { 243 out->print_cr("Heap dump file created"); 244 } else { 245 // heap dump failed 246 ResourceMark rm; 247 char* error = dumper.error_as_C_string(); 248 if (error == NULL) { 249 out->print_cr("Dump failed - reason unknown"); 250 } else { 251 out->print_cr("%s", error); 252 } 253 } 254 } 255 return JNI_OK; 256 } 257 258 // Implementation of "inspectheap" command 259 // See also: ClassHistogramDCmd class 260 // 261 // Input arguments :- 262 // arg0: "-live" or "-all" 263 // arg1: Name of the dump file or NULL 264 static jint heap_inspection(AttachOperation* op, outputStream* out) { 265 bool live_objects_only = true; // default is true to retain the behavior before this change is made 266 outputStream* os = out; // if path not specified or path is NULL, use out 267 fileStream* fs = NULL; 268 const char* arg0 = op->arg(0); 269 if (arg0 != NULL && (strlen(arg0) > 0)) { 270 if (strcmp(arg0, "-all") != 0 && strcmp(arg0, "-live") != 0) { 271 out->print_cr("Invalid argument to inspectheap operation: %s", arg0); 272 return JNI_ERR; 273 } 274 live_objects_only = strcmp(arg0, "-live") == 0; 275 } 276 277 const char* path = op->arg(1); 278 if (path != NULL) { 279 if (path[0] == '\0') { 280 out->print_cr("No dump file specified"); 281 } else { 282 // create file 283 fs = new (ResourceObj::C_HEAP, mtInternal) fileStream(path); 284 if (fs == NULL) { 285 out->print_cr("Failed to allocate space for file: %s", path); 286 return JNI_ERR; 287 } 288 os = fs; 289 } 290 } 291 292 VM_GC_HeapInspection heapop(os, live_objects_only /* request full gc */); 293 VMThread::execute(&heapop); 294 if (os != NULL && os != out) { 295 out->print_cr("Heap inspection file created: %s", path); 296 delete fs; 297 } 298 return JNI_OK; 299 } 300 301 // Implementation of "setflag" command 302 static jint set_flag(AttachOperation* op, outputStream* out) { 303 304 const char* name = NULL; 305 if ((name = op->arg(0)) == NULL) { 306 out->print_cr("flag name is missing"); 307 return JNI_ERR; 308 } 309 310 FormatBuffer<80> err_msg("%s", ""); 311 312 int ret = WriteableFlags::set_flag(op->arg(0), op->arg(1), JVMFlag::ATTACH_ON_DEMAND, err_msg); 313 if (ret != JVMFlag::SUCCESS) { 314 if (ret == JVMFlag::NON_WRITABLE) { 315 // if the flag is not manageable try to change it through 316 // the platform dependent implementation 317 return AttachListener::pd_set_flag(op, out); 318 } else { 319 out->print_cr("%s", err_msg.buffer()); 320 } 321 322 return JNI_ERR; 323 } 324 return JNI_OK; 325 } 326 327 // Implementation of "printflag" command 328 // See also: PrintVMFlagsDCmd class 329 static jint print_flag(AttachOperation* op, outputStream* out) { 330 const char* name = NULL; 331 if ((name = op->arg(0)) == NULL) { 332 out->print_cr("flag name is missing"); 333 return JNI_ERR; 334 } 335 JVMFlag* f = JVMFlag::find_flag(name); 336 if (f) { 337 f->print_as_flag(out); 338 out->cr(); 339 } else { 340 out->print_cr("no such flag '%s'", name); 341 } 342 return JNI_OK; 343 } 344 345 // Table to map operation names to functions. 346 347 // names must be of length <= AttachOperation::name_length_max 348 static AttachOperationFunctionInfo funcs[] = { 349 { "agentProperties", get_agent_properties }, 350 { "datadump", data_dump }, 351 { "dumpheap", dump_heap }, 352 { "load", load_agent }, 353 { "properties", get_system_properties }, 354 { "threaddump", thread_dump }, 355 { "inspectheap", heap_inspection }, 356 { "setflag", set_flag }, 357 { "printflag", print_flag }, 358 { "jcmd", jcmd }, 359 { NULL, NULL } 360 }; 361 362 363 364 // The Attach Listener threads services a queue. It dequeues an operation 365 // from the queue, examines the operation name (command), and dispatches 366 // to the corresponding function to perform the operation. 367 368 static void attach_listener_thread_entry(JavaThread* thread, TRAPS) { 369 os::set_priority(thread, NearMaxPriority); 370 371 assert(thread == Thread::current(), "Must be"); 372 assert(thread->stack_base() != NULL && thread->stack_size() > 0, 373 "Should already be setup"); 374 375 if (AttachListener::pd_init() != 0) { 376 AttachListener::set_state(AL_NOT_INITIALIZED); 377 return; 378 } 379 AttachListener::set_initialized(); 380 381 for (;;) { 382 AttachOperation* op = AttachListener::dequeue(); 383 if (op == NULL) { 384 AttachListener::set_state(AL_NOT_INITIALIZED); 385 return; // dequeue failed or shutdown 386 } 387 388 ResourceMark rm; 389 bufferedStream st; 390 jint res = JNI_OK; 391 392 // handle special detachall operation 393 if (strcmp(op->name(), AttachOperation::detachall_operation_name()) == 0) { 394 AttachListener::detachall(); 395 } else if (!EnableDynamicAgentLoading && strcmp(op->name(), "load") == 0) { 396 st.print("Dynamic agent loading is not enabled. " 397 "Use -XX:+EnableDynamicAgentLoading to launch target VM."); 398 res = JNI_ERR; 399 } else { 400 // find the function to dispatch too 401 AttachOperationFunctionInfo* info = NULL; 402 for (int i=0; funcs[i].name != NULL; i++) { 403 const char* name = funcs[i].name; 404 assert(strlen(name) <= AttachOperation::name_length_max, "operation <= name_length_max"); 405 if (strcmp(op->name(), name) == 0) { 406 info = &(funcs[i]); 407 break; 408 } 409 } 410 411 // check for platform dependent attach operation 412 if (info == NULL) { 413 info = AttachListener::pd_find_operation(op->name()); 414 } 415 416 if (info != NULL) { 417 // dispatch to the function that implements this operation 418 res = (info->func)(op, &st); 419 } else { 420 st.print("Operation %s not recognized!", op->name()); 421 res = JNI_ERR; 422 } 423 } 424 425 // operation complete - send result and output to client 426 op->complete(res, &st); 427 } 428 429 ShouldNotReachHere(); 430 } 431 432 bool AttachListener::has_init_error(TRAPS) { 433 if (HAS_PENDING_EXCEPTION) { 434 tty->print_cr("Exception in VM (AttachListener::init) : "); 435 java_lang_Throwable::print(PENDING_EXCEPTION, tty); 436 tty->cr(); 437 438 CLEAR_PENDING_EXCEPTION; 439 440 return true; 441 } else { 442 return false; 443 } 444 } 445 446 // Starts the Attach Listener thread 447 void AttachListener::init() { 448 EXCEPTION_MARK; 449 450 const char thread_name[] = "Attach Listener"; 451 Handle string = java_lang_String::create_from_str(thread_name, THREAD); 452 if (has_init_error(THREAD)) { 453 set_state(AL_NOT_INITIALIZED); 454 return; 455 } 456 457 // Initialize thread_oop to put it into the system threadGroup 458 Handle thread_group (THREAD, Universe::system_thread_group()); 459 Handle thread_oop = JavaCalls::construct_new_instance(SystemDictionary::Thread_klass(), 460 vmSymbols::threadgroup_string_void_signature(), 461 thread_group, 462 string, 463 THREAD); 464 if (has_init_error(THREAD)) { 465 set_state(AL_NOT_INITIALIZED); 466 return; 467 } 468 469 Klass* group = SystemDictionary::ThreadGroup_klass(); 470 JavaValue result(T_VOID); 471 JavaCalls::call_special(&result, 472 thread_group, 473 group, 474 vmSymbols::add_method_name(), 475 vmSymbols::thread_void_signature(), 476 thread_oop, 477 THREAD); 478 if (has_init_error(THREAD)) { 479 set_state(AL_NOT_INITIALIZED); 480 return; 481 } 482 483 { MutexLocker mu(Threads_lock); 484 JavaThread* listener_thread = new JavaThread(&attach_listener_thread_entry); 485 486 // Check that thread and osthread were created 487 if (listener_thread == NULL || listener_thread->osthread() == NULL) { 488 vm_exit_during_initialization("java.lang.OutOfMemoryError", 489 os::native_thread_creation_failed_msg()); 490 } 491 492 java_lang_Thread::set_thread(thread_oop(), listener_thread); 493 java_lang_Thread::set_daemon(thread_oop()); 494 495 listener_thread->set_threadObj(thread_oop()); 496 Threads::add(listener_thread); 497 Thread::start(listener_thread); 498 } 499 } 500 501 // Performs clean-up tasks on platforms where we can detect that the last 502 // client has detached 503 void AttachListener::detachall() { 504 // call the platform dependent clean-up 505 pd_detachall(); 506 }