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 if (op->arg(0) != NULL && strcmp(op->arg(0), "-l") == 0) { 172 print_concurrent_locks = true; 173 } 174 175 // thread stacks 176 VM_PrintThreads op1(out, print_concurrent_locks); 177 VMThread::execute(&op1); 178 179 // JNI global handles 180 VM_PrintJNI op2(out); 181 VMThread::execute(&op2); 182 183 // Deadlock detection 184 VM_FindDeadlocks op3(out); 185 VMThread::execute(&op3); 186 187 return JNI_OK; 188 } 189 190 // A jcmd attach operation request was received, which will now 191 // dispatch to the diagnostic commands used for serviceability functions. 192 static jint jcmd(AttachOperation* op, outputStream* out) { 193 Thread* THREAD = Thread::current(); 194 // All the supplied jcmd arguments are stored as a single 195 // string (op->arg(0)). This is parsed by the Dcmd framework. 196 DCmd::parse_and_execute(DCmd_Source_AttachAPI, out, op->arg(0), ' ', THREAD); 197 if (HAS_PENDING_EXCEPTION) { 198 java_lang_Throwable::print(PENDING_EXCEPTION, out); 199 out->cr(); 200 CLEAR_PENDING_EXCEPTION; 201 return JNI_ERR; 202 } 203 return JNI_OK; 204 } 205 206 // Implementation of "dumpheap" command. 207 // See also: HeapDumpDCmd class 208 // 209 // Input arguments :- 210 // arg0: Name of the dump file 211 // arg1: "-live" or "-all" 212 jint dump_heap(AttachOperation* op, outputStream* out) { 213 const char* path = op->arg(0); 214 if (path == NULL || path[0] == '\0') { 215 out->print_cr("No dump file specified"); 216 } else { 217 bool live_objects_only = true; // default is true to retain the behavior before this change is made 218 const char* arg1 = op->arg(1); 219 if (arg1 != NULL && (strlen(arg1) > 0)) { 220 if (strcmp(arg1, "-all") != 0 && strcmp(arg1, "-live") != 0) { 221 out->print_cr("Invalid argument to dumpheap operation: %s", arg1); 222 return JNI_ERR; 223 } 224 live_objects_only = strcmp(arg1, "-live") == 0; 225 } 226 227 // Request a full GC before heap dump if live_objects_only = true 228 // This helps reduces the amount of unreachable objects in the dump 229 // and makes it easier to browse. 230 HeapDumper dumper(live_objects_only /* request GC */); 231 int res = dumper.dump(op->arg(0)); 232 if (res == 0) { 233 out->print_cr("Heap dump file created"); 234 } else { 235 // heap dump failed 236 ResourceMark rm; 237 char* error = dumper.error_as_C_string(); 238 if (error == NULL) { 239 out->print_cr("Dump failed - reason unknown"); 240 } else { 241 out->print_cr("%s", error); 242 } 243 } 244 } 245 return JNI_OK; 246 } 247 248 // Implementation of "inspectheap" command 249 // See also: ClassHistogramDCmd class 250 // 251 // Input arguments :- 252 // arg0: "-live" or "-all" 253 static jint heap_inspection(AttachOperation* op, outputStream* out) { 254 bool live_objects_only = true; // default is true to retain the behavior before this change is made 255 const char* arg0 = op->arg(0); 256 if (arg0 != NULL && (strlen(arg0) > 0)) { 257 if (strcmp(arg0, "-all") != 0 && strcmp(arg0, "-live") != 0) { 258 out->print_cr("Invalid argument to inspectheap operation: %s", arg0); 259 return JNI_ERR; 260 } 261 live_objects_only = strcmp(arg0, "-live") == 0; 262 } 263 VM_GC_HeapInspection heapop(out, live_objects_only /* request full gc */); 264 VMThread::execute(&heapop); 265 return JNI_OK; 266 } 267 268 // Implementation of "setflag" command 269 static jint set_flag(AttachOperation* op, outputStream* out) { 270 271 const char* name = NULL; 272 if ((name = op->arg(0)) == NULL) { 273 out->print_cr("flag name is missing"); 274 return JNI_ERR; 275 } 276 277 FormatBuffer<80> err_msg("%s", ""); 278 279 int ret = WriteableFlags::set_flag(op->arg(0), op->arg(1), JVMFlag::ATTACH_ON_DEMAND, err_msg); 280 if (ret != JVMFlag::SUCCESS) { 281 if (ret == JVMFlag::NON_WRITABLE) { 282 // if the flag is not manageable try to change it through 283 // the platform dependent implementation 284 return AttachListener::pd_set_flag(op, out); 285 } else { 286 out->print_cr("%s", err_msg.buffer()); 287 } 288 289 return JNI_ERR; 290 } 291 return JNI_OK; 292 } 293 294 // Implementation of "printflag" command 295 // See also: PrintVMFlagsDCmd class 296 static jint print_flag(AttachOperation* op, outputStream* out) { 297 const char* name = NULL; 298 if ((name = op->arg(0)) == NULL) { 299 out->print_cr("flag name is missing"); 300 return JNI_ERR; 301 } 302 JVMFlag* f = JVMFlag::find_flag((char*)name, strlen(name)); 303 if (f) { 304 f->print_as_flag(out); 305 out->cr(); 306 } else { 307 out->print_cr("no such flag '%s'", name); 308 } 309 return JNI_OK; 310 } 311 312 // Table to map operation names to functions. 313 314 // names must be of length <= AttachOperation::name_length_max 315 static AttachOperationFunctionInfo funcs[] = { 316 { "agentProperties", get_agent_properties }, 317 { "datadump", data_dump }, 318 { "dumpheap", dump_heap }, 319 { "load", load_agent }, 320 { "properties", get_system_properties }, 321 { "threaddump", thread_dump }, 322 { "inspectheap", heap_inspection }, 323 { "setflag", set_flag }, 324 { "printflag", print_flag }, 325 { "jcmd", jcmd }, 326 { NULL, NULL } 327 }; 328 329 330 331 // The Attach Listener threads services a queue. It dequeues an operation 332 // from the queue, examines the operation name (command), and dispatches 333 // to the corresponding function to perform the operation. 334 335 static void attach_listener_thread_entry(JavaThread* thread, TRAPS) { 336 os::set_priority(thread, NearMaxPriority); 337 338 assert(thread == Thread::current(), "Must be"); 339 assert(thread->stack_base() != NULL && thread->stack_size() > 0, 340 "Should already be setup"); 341 342 if (AttachListener::pd_init() != 0) { 343 return; 344 } 345 AttachListener::set_initialized(); 346 347 for (;;) { 348 AttachOperation* op = AttachListener::dequeue(); 349 if (op == NULL) { 350 return; // dequeue failed or shutdown 351 } 352 353 ResourceMark rm; 354 bufferedStream st; 355 jint res = JNI_OK; 356 357 // handle special detachall operation 358 if (strcmp(op->name(), AttachOperation::detachall_operation_name()) == 0) { 359 AttachListener::detachall(); 360 } else if (!EnableDynamicAgentLoading && strcmp(op->name(), "load") == 0) { 361 st.print("Dynamic agent loading is not enabled. " 362 "Use -XX:+EnableDynamicAgentLoading to launch target VM."); 363 res = JNI_ERR; 364 } else { 365 // find the function to dispatch too 366 AttachOperationFunctionInfo* info = NULL; 367 for (int i=0; funcs[i].name != NULL; i++) { 368 const char* name = funcs[i].name; 369 assert(strlen(name) <= AttachOperation::name_length_max, "operation <= name_length_max"); 370 if (strcmp(op->name(), name) == 0) { 371 info = &(funcs[i]); 372 break; 373 } 374 } 375 376 // check for platform dependent attach operation 377 if (info == NULL) { 378 info = AttachListener::pd_find_operation(op->name()); 379 } 380 381 if (info != NULL) { 382 // dispatch to the function that implements this operation 383 res = (info->func)(op, &st); 384 } else { 385 st.print("Operation %s not recognized!", op->name()); 386 res = JNI_ERR; 387 } 388 } 389 390 // operation complete - send result and output to client 391 op->complete(res, &st); 392 } 393 } 394 395 bool AttachListener::has_init_error(TRAPS) { 396 if (HAS_PENDING_EXCEPTION) { 397 tty->print_cr("Exception in VM (AttachListener::init) : "); 398 java_lang_Throwable::print(PENDING_EXCEPTION, tty); 399 tty->cr(); 400 401 CLEAR_PENDING_EXCEPTION; 402 403 return true; 404 } else { 405 return false; 406 } 407 } 408 409 // Starts the Attach Listener thread 410 void AttachListener::init() { 411 EXCEPTION_MARK; 412 413 const char thread_name[] = "Attach Listener"; 414 Handle string = java_lang_String::create_from_str(thread_name, THREAD); 415 if (has_init_error(THREAD)) { 416 return; 417 } 418 419 // Initialize thread_oop to put it into the system threadGroup 420 Handle thread_group (THREAD, Universe::system_thread_group()); 421 Handle thread_oop = JavaCalls::construct_new_instance(SystemDictionary::Thread_klass(), 422 vmSymbols::threadgroup_string_void_signature(), 423 thread_group, 424 string, 425 THREAD); 426 if (has_init_error(THREAD)) { 427 return; 428 } 429 430 Klass* group = SystemDictionary::ThreadGroup_klass(); 431 JavaValue result(T_VOID); 432 JavaCalls::call_special(&result, 433 thread_group, 434 group, 435 vmSymbols::add_method_name(), 436 vmSymbols::thread_void_signature(), 437 thread_oop, 438 THREAD); 439 if (has_init_error(THREAD)) { 440 return; 441 } 442 443 { MutexLocker mu(Threads_lock); 444 JavaThread* listener_thread = new JavaThread(&attach_listener_thread_entry); 445 446 // Check that thread and osthread were created 447 if (listener_thread == NULL || listener_thread->osthread() == NULL) { 448 vm_exit_during_initialization("java.lang.OutOfMemoryError", 449 os::native_thread_creation_failed_msg()); 450 } 451 452 java_lang_Thread::set_thread(thread_oop(), listener_thread); 453 java_lang_Thread::set_daemon(thread_oop()); 454 455 listener_thread->set_threadObj(thread_oop()); 456 Threads::add(listener_thread); 457 Thread::start(listener_thread); 458 } 459 } 460 461 // Performs clean-up tasks on platforms where we can detect that the last 462 // client has detached 463 void AttachListener::detachall() { 464 // call the platform dependent clean-up 465 pd_detachall(); 466 }