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