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/instanceKlass.inline.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/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), Flag::ATTACH_ON_DEMAND, err_msg);
 280   if (ret != Flag::SUCCESS) {
 281     if (ret == Flag::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   Flag* f = Flag::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   thread->record_stack_base_and_size();
 339 
 340   if (AttachListener::pd_init() != 0) {
 341     return;
 342   }
 343   AttachListener::set_initialized();
 344 
 345   for (;;) {
 346     AttachOperation* op = AttachListener::dequeue();
 347     if (op == NULL) {
 348       return;   // dequeue failed or shutdown
 349     }
 350 
 351     ResourceMark rm;
 352     bufferedStream st;
 353     jint res = JNI_OK;
 354 
 355     // handle special detachall operation
 356     if (strcmp(op->name(), AttachOperation::detachall_operation_name()) == 0) {
 357       AttachListener::detachall();
 358     } else if (!EnableDynamicAgentLoading && strcmp(op->name(), "load") == 0) {
 359       st.print("Dynamic agent loading is not enabled. "
 360                "Use -XX:+EnableDynamicAgentLoading to launch target VM.");
 361       res = JNI_ERR;
 362     } else {
 363       // find the function to dispatch too
 364       AttachOperationFunctionInfo* info = NULL;
 365       for (int i=0; funcs[i].name != NULL; i++) {
 366         const char* name = funcs[i].name;
 367         assert(strlen(name) <= AttachOperation::name_length_max, "operation <= name_length_max");
 368         if (strcmp(op->name(), name) == 0) {
 369           info = &(funcs[i]);
 370           break;
 371         }
 372       }
 373 
 374       // check for platform dependent attach operation
 375       if (info == NULL) {
 376         info = AttachListener::pd_find_operation(op->name());
 377       }
 378 
 379       if (info != NULL) {
 380         // dispatch to the function that implements this operation
 381         res = (info->func)(op, &st);
 382       } else {
 383         st.print("Operation %s not recognized!", op->name());
 384         res = JNI_ERR;
 385       }
 386     }
 387 
 388     // operation complete - send result and output to client
 389     op->complete(res, &st);
 390   }
 391 }
 392 
 393 bool AttachListener::has_init_error(TRAPS) {
 394   if (HAS_PENDING_EXCEPTION) {
 395     tty->print_cr("Exception in VM (AttachListener::init) : ");
 396     java_lang_Throwable::print(PENDING_EXCEPTION, tty);
 397     tty->cr();
 398 
 399     CLEAR_PENDING_EXCEPTION;
 400 
 401     return true;
 402   } else {
 403     return false;
 404   }
 405 }
 406 
 407 // Starts the Attach Listener thread
 408 void AttachListener::init() {
 409   EXCEPTION_MARK;
 410   Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, THREAD);
 411   if (has_init_error(THREAD)) {
 412     return;
 413   }
 414 
 415   InstanceKlass* klass = InstanceKlass::cast(k);
 416   instanceHandle thread_oop = klass->allocate_instance_handle(THREAD);
 417   if (has_init_error(THREAD)) {
 418     return;
 419   }
 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   JavaValue result(T_VOID);
 430   JavaCalls::call_special(&result, thread_oop,
 431                        klass,
 432                        vmSymbols::object_initializer_name(),
 433                        vmSymbols::threadgroup_string_void_signature(),
 434                        thread_group,
 435                        string,
 436                        THREAD);
 437 
 438   if (has_init_error(THREAD)) {
 439     return;
 440   }
 441 
 442   Klass* group = SystemDictionary::ThreadGroup_klass();
 443   JavaCalls::call_special(&result,
 444                         thread_group,
 445                         group,
 446                         vmSymbols::add_method_name(),
 447                         vmSymbols::thread_void_signature(),
 448                         thread_oop,             // ARG 1
 449                         THREAD);
 450   if (has_init_error(THREAD)) {
 451     return;
 452   }
 453 
 454   { MutexLocker mu(Threads_lock);
 455     JavaThread* listener_thread = new JavaThread(&attach_listener_thread_entry);
 456 
 457     // Check that thread and osthread were created
 458     if (listener_thread == NULL || listener_thread->osthread() == NULL) {
 459       vm_exit_during_initialization("java.lang.OutOfMemoryError",
 460                                     os::native_thread_creation_failed_msg());
 461     }
 462 
 463     java_lang_Thread::set_thread(thread_oop(), listener_thread);
 464     java_lang_Thread::set_daemon(thread_oop());
 465 
 466     listener_thread->set_threadObj(thread_oop());
 467     Threads::add(listener_thread);
 468     Thread::start(listener_thread);
 469   }
 470 }
 471 
 472 // Performs clean-up tasks on platforms where we can detect that the last
 473 // client has detached
 474 void AttachListener::detachall() {
 475   // call the platform dependent clean-up
 476   pd_detachall();
 477 }