1 /*
   2  * Copyright (c) 2005, 2015, 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 "properties" command.
 103 // See also: PrintSystemPropertiesDCmd class
 104 static jint get_system_properties(AttachOperation* op, outputStream* out) {
 105   return get_properties(op, out, vmSymbols::serializePropertiesToByteArray_name());
 106 }
 107 
 108 // Implementation of "agent_properties" command.
 109 static jint get_agent_properties(AttachOperation* op, outputStream* out) {
 110   return get_properties(op, out, vmSymbols::serializeAgentPropertiesToByteArray_name());
 111 }
 112 
 113 // Implementation of "datadump" command.
 114 //
 115 // Raises a SIGBREAK signal so that VM dump threads, does deadlock detection,
 116 // etc. In theory this command should only post a DataDumpRequest to any
 117 // JVMTI environment that has enabled this event. However it's useful to
 118 // trigger the SIGBREAK handler.
 119 
 120 static jint data_dump(AttachOperation* op, outputStream* out) {
 121   if (!ReduceSignalUsage) {
 122     AttachListener::pd_data_dump();
 123   } else {
 124     if (JvmtiExport::should_post_data_dump()) {
 125       JvmtiExport::post_data_dump();
 126     }
 127   }
 128   return JNI_OK;
 129 }
 130 
 131 // Implementation of "threaddump" command - essentially a remote ctrl-break
 132 // See also: ThreadDumpDCmd class
 133 //
 134 static jint thread_dump(AttachOperation* op, outputStream* out) {
 135   bool print_concurrent_locks = false;
 136   if (op->arg(0) != NULL && strcmp(op->arg(0), "-l") == 0) {
 137     print_concurrent_locks = true;
 138   }
 139 
 140   // thread stacks
 141   VM_PrintThreads op1(out, print_concurrent_locks);
 142   VMThread::execute(&op1);
 143 
 144   // JNI global handles
 145   VM_PrintJNI op2(out);
 146   VMThread::execute(&op2);
 147 
 148   // Deadlock detection
 149   VM_FindDeadlocks op3(out);
 150   VMThread::execute(&op3);
 151 
 152   return JNI_OK;
 153 }
 154 
 155 // A jcmd attach operation request was received, which will now
 156 // dispatch to the diagnostic commands used for serviceability functions.
 157 static jint jcmd(AttachOperation* op, outputStream* out) {
 158   Thread* THREAD = Thread::current();
 159   // All the supplied jcmd arguments are stored as a single
 160   // string (op->arg(0)). This is parsed by the Dcmd framework.
 161   DCmd::parse_and_execute(DCmd_Source_AttachAPI, out, op->arg(0), ' ', THREAD);
 162   if (HAS_PENDING_EXCEPTION) {
 163     java_lang_Throwable::print(PENDING_EXCEPTION, out);
 164     out->cr();
 165     CLEAR_PENDING_EXCEPTION;
 166     return JNI_ERR;
 167   }
 168   return JNI_OK;
 169 }
 170 
 171 // Implementation of "dumpheap" command.
 172 // See also: HeapDumpDCmd class
 173 //
 174 // Input arguments :-
 175 //   arg0: Name of the dump file
 176 //   arg1: "-live" or "-all"
 177 jint dump_heap(AttachOperation* op, outputStream* out) {
 178   const char* path = op->arg(0);
 179   if (path == NULL || path[0] == '\0') {
 180     out->print_cr("No dump file specified");
 181   } else {
 182     bool live_objects_only = true;   // default is true to retain the behavior before this change is made
 183     const char* arg1 = op->arg(1);
 184     if (arg1 != NULL && (strlen(arg1) > 0)) {
 185       if (strcmp(arg1, "-all") != 0 && strcmp(arg1, "-live") != 0) {
 186         out->print_cr("Invalid argument to dumpheap operation: %s", arg1);
 187         return JNI_ERR;
 188       }
 189       live_objects_only = strcmp(arg1, "-live") == 0;
 190     }
 191 
 192     // Request a full GC before heap dump if live_objects_only = true
 193     // This helps reduces the amount of unreachable objects in the dump
 194     // and makes it easier to browse.
 195     HeapDumper dumper(live_objects_only /* request GC */);
 196     int res = dumper.dump(op->arg(0));
 197     if (res == 0) {
 198       out->print_cr("Heap dump file created");
 199     } else {
 200       // heap dump failed
 201       ResourceMark rm;
 202       char* error = dumper.error_as_C_string();
 203       if (error == NULL) {
 204         out->print_cr("Dump failed - reason unknown");
 205       } else {
 206         out->print_cr("%s", error);
 207       }
 208     }
 209   }
 210   return JNI_OK;
 211 }
 212 
 213 // Implementation of "inspectheap" command
 214 // See also: ClassHistogramDCmd class
 215 //
 216 // Input arguments :-
 217 //   arg0: "-live" or "-all"
 218 static jint heap_inspection(AttachOperation* op, outputStream* out) {
 219   bool live_objects_only = true;   // default is true to retain the behavior before this change is made
 220   const char* arg0 = op->arg(0);
 221   if (arg0 != NULL && (strlen(arg0) > 0)) {
 222     if (strcmp(arg0, "-all") != 0 && strcmp(arg0, "-live") != 0) {
 223       out->print_cr("Invalid argument to inspectheap operation: %s", arg0);
 224       return JNI_ERR;
 225     }
 226     live_objects_only = strcmp(arg0, "-live") == 0;
 227   }
 228   VM_GC_HeapInspection heapop(out, live_objects_only /* request full gc */);
 229   VMThread::execute(&heapop);
 230   return JNI_OK;
 231 }
 232 
 233 // Implementation of "setflag" command
 234 static jint set_flag(AttachOperation* op, outputStream* out) {
 235 
 236   const char* name = NULL;
 237   if ((name = op->arg(0)) == NULL) {
 238     out->print_cr("flag name is missing");
 239     return JNI_ERR;
 240   }
 241 
 242   FormatBuffer<80> err_msg("%s", "");
 243 
 244   int ret = WriteableFlags::set_flag(op->arg(0), op->arg(1), Flag::ATTACH_ON_DEMAND, err_msg);
 245   if (ret != Flag::SUCCESS) {
 246     if (ret == Flag::NON_WRITABLE) {
 247       // if the flag is not manageable try to change it through
 248       // the platform dependent implementation
 249       return AttachListener::pd_set_flag(op, out);
 250     } else {
 251       out->print_cr("%s", err_msg.buffer());
 252     }
 253 
 254     return JNI_ERR;
 255   }
 256   return JNI_OK;
 257 }
 258 
 259 // Implementation of "printflag" command
 260 // See also: PrintVMFlagsDCmd class
 261 static jint print_flag(AttachOperation* op, outputStream* out) {
 262   const char* name = NULL;
 263   if ((name = op->arg(0)) == NULL) {
 264     out->print_cr("flag name is missing");
 265     return JNI_ERR;
 266   }
 267   Flag* f = Flag::find_flag((char*)name, strlen(name));
 268   if (f) {
 269     f->print_as_flag(out);
 270     out->cr();
 271   } else {
 272     out->print_cr("no such flag '%s'", name);
 273   }
 274   return JNI_OK;
 275 }
 276 
 277 // Table to map operation names to functions.
 278 
 279 // names must be of length <= AttachOperation::name_length_max
 280 static AttachOperationFunctionInfo funcs[] = {
 281   { "agentProperties",  get_agent_properties },
 282   { "datadump",         data_dump },
 283   { "dumpheap",         dump_heap },
 284   { "load",             JvmtiExport::load_agent_library },
 285   { "properties",       get_system_properties },
 286   { "threaddump",       thread_dump },
 287   { "inspectheap",      heap_inspection },
 288   { "setflag",          set_flag },
 289   { "printflag",        print_flag },
 290   { "jcmd",             jcmd },
 291   { NULL,               NULL }
 292 };
 293 
 294 
 295 
 296 // The Attach Listener threads services a queue. It dequeues an operation
 297 // from the queue, examines the operation name (command), and dispatches
 298 // to the corresponding function to perform the operation.
 299 
 300 static void attach_listener_thread_entry(JavaThread* thread, TRAPS) {
 301   os::set_priority(thread, NearMaxPriority);
 302 
 303   thread->record_stack_base_and_size();
 304 
 305   if (AttachListener::pd_init() != 0) {
 306     return;
 307   }
 308   AttachListener::set_initialized();
 309 
 310   for (;;) {
 311     AttachOperation* op = AttachListener::dequeue();
 312     if (op == NULL) {
 313       return;   // dequeue failed or shutdown
 314     }
 315 
 316     ResourceMark rm;
 317     bufferedStream st;
 318     jint res = JNI_OK;
 319 
 320     // handle special detachall operation
 321     if (strcmp(op->name(), AttachOperation::detachall_operation_name()) == 0) {
 322       AttachListener::detachall();
 323     } else {
 324       // find the function to dispatch too
 325       AttachOperationFunctionInfo* info = NULL;
 326       for (int i=0; funcs[i].name != NULL; i++) {
 327         const char* name = funcs[i].name;
 328         assert(strlen(name) <= AttachOperation::name_length_max, "operation <= name_length_max");
 329         if (strcmp(op->name(), name) == 0) {
 330           info = &(funcs[i]);
 331           break;
 332         }
 333       }
 334 
 335       // check for platform dependent attach operation
 336       if (info == NULL) {
 337         info = AttachListener::pd_find_operation(op->name());
 338       }
 339 
 340       if (info != NULL) {
 341         // dispatch to the function that implements this operation
 342         res = (info->func)(op, &st);
 343       } else {
 344         st.print("Operation %s not recognized!", op->name());
 345         res = JNI_ERR;
 346       }
 347     }
 348 
 349     // operation complete - send result and output to client
 350     op->complete(res, &st);
 351   }
 352 }
 353 
 354 bool AttachListener::has_init_error(TRAPS) {
 355   if (HAS_PENDING_EXCEPTION) {
 356     tty->print_cr("Exception in VM (AttachListener::init) : ");
 357     java_lang_Throwable::print(PENDING_EXCEPTION, tty);
 358     tty->cr();
 359 
 360     CLEAR_PENDING_EXCEPTION;
 361 
 362     return true;
 363   } else {
 364     return false;
 365   }
 366 }
 367 
 368 // Starts the Attach Listener thread
 369 void AttachListener::init() {
 370   EXCEPTION_MARK;
 371   Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, THREAD);
 372   if (has_init_error(THREAD)) {
 373     return;
 374   }
 375 
 376   InstanceKlass* klass = InstanceKlass::cast(k);
 377   instanceHandle thread_oop = klass->allocate_instance_handle(THREAD);
 378   if (has_init_error(THREAD)) {
 379     return;
 380   }
 381 
 382   const char thread_name[] = "Attach Listener";
 383   Handle string = java_lang_String::create_from_str(thread_name, THREAD);
 384   if (has_init_error(THREAD)) {
 385     return;
 386   }
 387 
 388   // Initialize thread_oop to put it into the system threadGroup
 389   Handle thread_group (THREAD, Universe::system_thread_group());
 390   JavaValue result(T_VOID);
 391   JavaCalls::call_special(&result, thread_oop,
 392                        klass,
 393                        vmSymbols::object_initializer_name(),
 394                        vmSymbols::threadgroup_string_void_signature(),
 395                        thread_group,
 396                        string,
 397                        THREAD);
 398 
 399   if (has_init_error(THREAD)) {
 400     return;
 401   }
 402 
 403   Klass* group = SystemDictionary::ThreadGroup_klass();
 404   JavaCalls::call_special(&result,
 405                         thread_group,
 406                         group,
 407                         vmSymbols::add_method_name(),
 408                         vmSymbols::thread_void_signature(),
 409                         thread_oop,             // ARG 1
 410                         THREAD);
 411   if (has_init_error(THREAD)) {
 412     return;
 413   }
 414 
 415   { MutexLocker mu(Threads_lock);
 416     JavaThread* listener_thread = new JavaThread(&attach_listener_thread_entry);
 417 
 418     // Check that thread and osthread were created
 419     if (listener_thread == NULL || listener_thread->osthread() == NULL) {
 420       vm_exit_during_initialization("java.lang.OutOfMemoryError",
 421                                     os::native_thread_creation_failed_msg());
 422     }
 423 
 424     java_lang_Thread::set_thread(thread_oop(), listener_thread);
 425     java_lang_Thread::set_daemon(thread_oop());
 426 
 427     listener_thread->set_threadObj(thread_oop());
 428     Threads::add(listener_thread);
 429     Thread::start(listener_thread);
 430   }
 431 }
 432 
 433 // Performs clean-up tasks on platforms where we can detect that the last
 434 // client has detached
 435 void AttachListener::detachall() {
 436   // call the platform dependent clean-up
 437   pd_detachall();
 438 }