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