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