1 /*
   2  * Copyright (c) 2005, 2014, 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_implementation/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 
  41 volatile bool AttachListener::_initialized;
  42 
  43 // Implementation of "properties" command.
  44 //
  45 // Invokes sun.misc.VMSupport.serializePropertiesToByteArray to serialize
  46 // the system properties into a byte array.
  47 
  48 static Klass* load_and_initialize_klass(Symbol* sh, TRAPS) {
  49   Klass* k = SystemDictionary::resolve_or_fail(sh, true, CHECK_NULL);
  50   instanceKlassHandle ik (THREAD, k);
  51   if (ik->should_be_initialized()) {
  52     ik->initialize(CHECK_NULL);
  53   }
  54   return ik();
  55 }
  56 
  57 static jint get_properties(AttachOperation* op, outputStream* out, Symbol* serializePropertiesMethod) {
  58   Thread* THREAD = Thread::current();
  59   HandleMark hm;
  60 
  61   // load sun.misc.VMSupport
  62   Symbol* klass = vmSymbols::sun_misc_VMSupport();
  63   Klass* k = load_and_initialize_klass(klass, THREAD);
  64   if (HAS_PENDING_EXCEPTION) {
  65     java_lang_Throwable::print(PENDING_EXCEPTION, out);
  66     CLEAR_PENDING_EXCEPTION;
  67     return JNI_ERR;
  68   }
  69   instanceKlassHandle ik(THREAD, k);
  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                            ik,
  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 // set a boolean global flag using value from AttachOperation
 234 static jint set_bool_flag(const char* name, AttachOperation* op, outputStream* out) {
 235   bool value = true;
 236   const char* arg1;
 237   if ((arg1 = op->arg(1)) != NULL) {
 238     int tmp;
 239     int n = sscanf(arg1, "%d", &tmp);
 240     if (n != 1) {
 241       out->print_cr("flag value must be a boolean (1 or 0)");
 242       return JNI_ERR;
 243     }
 244     value = (tmp != 0);
 245   }
 246   bool res = CommandLineFlags::boolAtPut((char*)name, &value, Flag::ATTACH_ON_DEMAND);
 247   if (! res) {
 248     out->print_cr("setting flag %s failed", name);
 249   }
 250   return res? JNI_OK : JNI_ERR;
 251 }
 252 
 253 // set a intx global flag using value from AttachOperation
 254 static jint set_intx_flag(const char* name, AttachOperation* op, outputStream* out) {
 255   intx value;
 256   const char* arg1;
 257   if ((arg1 = op->arg(1)) != NULL) {
 258     int n = sscanf(arg1, INTX_FORMAT, &value);
 259     if (n != 1) {
 260       out->print_cr("flag value must be an integer");
 261       return JNI_ERR;
 262     }
 263   }
 264   bool res = CommandLineFlags::intxAtPut((char*)name, &value, Flag::ATTACH_ON_DEMAND);
 265   if (! res) {
 266     out->print_cr("setting flag %s failed", name);
 267   }
 268 
 269   return res? JNI_OK : JNI_ERR;
 270 }
 271 
 272 // set a uintx global flag using value from AttachOperation
 273 static jint set_uintx_flag(const char* name, AttachOperation* op, outputStream* out) {
 274   uintx value;
 275   const char* arg1;
 276   if ((arg1 = op->arg(1)) != NULL) {
 277     int n = sscanf(arg1, UINTX_FORMAT, &value);
 278     if (n != 1) {
 279       out->print_cr("flag value must be an unsigned integer");
 280       return JNI_ERR;
 281     }
 282   }
 283 
 284   if (strncmp(name, "MaxHeapFreeRatio", 17) == 0) {
 285     FormatBuffer<80> err_msg("%s", "");
 286     if (!Arguments::verify_MaxHeapFreeRatio(err_msg, value)) {
 287       out->print_cr("%s", err_msg.buffer());
 288       return JNI_ERR;
 289     }
 290   } else if (strncmp(name, "MinHeapFreeRatio", 17) == 0) {
 291     FormatBuffer<80> err_msg("%s", "");
 292     if (!Arguments::verify_MinHeapFreeRatio(err_msg, value)) {
 293       out->print_cr("%s", err_msg.buffer());
 294       return JNI_ERR;
 295     }
 296   }
 297   bool res = CommandLineFlags::uintxAtPut((char*)name, &value, Flag::ATTACH_ON_DEMAND);
 298   if (! res) {
 299     out->print_cr("setting flag %s failed", name);
 300   }
 301 
 302   return res? JNI_OK : JNI_ERR;
 303 }
 304 
 305 // set a uint64_t global flag using value from AttachOperation
 306 static jint set_uint64_t_flag(const char* name, AttachOperation* op, outputStream* out) {
 307   uint64_t value;
 308   const char* arg1;
 309   if ((arg1 = op->arg(1)) != NULL) {
 310     int n = sscanf(arg1, UINT64_FORMAT, &value);
 311     if (n != 1) {
 312       out->print_cr("flag value must be an unsigned 64-bit integer");
 313       return JNI_ERR;
 314     }
 315   }
 316   bool res = CommandLineFlags::uint64_tAtPut((char*)name, &value, Flag::ATTACH_ON_DEMAND);
 317   if (! res) {
 318     out->print_cr("setting flag %s failed", name);
 319   }
 320 
 321   return res? JNI_OK : JNI_ERR;
 322 }
 323 
 324 // set a size_t global flag using value from AttachOperation
 325 static jint set_size_t_flag(const char* name, AttachOperation* op, outputStream* out) {
 326   size_t value;
 327   const char* arg1;
 328   if ((arg1 = op->arg(1)) != NULL) {
 329     int n = sscanf(arg1, SIZE_FORMAT, &value);
 330     if (n != 1) {
 331       out->print_cr("flag value must be an unsigned integer");
 332       return JNI_ERR;
 333     }
 334   }
 335   bool res = CommandLineFlags::size_tAtPut((char*)name, &value, Flag::ATTACH_ON_DEMAND);
 336   if (! res) {
 337     out->print_cr("setting flag %s failed", name);
 338   }
 339 
 340   return res? JNI_OK : JNI_ERR;
 341 }
 342 
 343 // set a string global flag using value from AttachOperation
 344 static jint set_ccstr_flag(const char* name, AttachOperation* op, outputStream* out) {
 345   const char* value;
 346   if ((value = op->arg(1)) == NULL) {
 347     out->print_cr("flag value must be a string");
 348     return JNI_ERR;
 349   }
 350   bool res = CommandLineFlags::ccstrAtPut((char*)name, &value, Flag::ATTACH_ON_DEMAND);
 351   if (res) {
 352     FREE_C_HEAP_ARRAY(char, value);
 353   } else {
 354     out->print_cr("setting flag %s failed", name);
 355   }
 356 
 357   return res? JNI_OK : JNI_ERR;
 358 }
 359 
 360 // Implementation of "setflag" command
 361 static jint set_flag(AttachOperation* op, outputStream* out) {
 362 
 363   const char* name = NULL;
 364   if ((name = op->arg(0)) == NULL) {
 365     out->print_cr("flag name is missing");
 366     return JNI_ERR;
 367   }
 368 
 369   Flag* f = Flag::find_flag((char*)name, strlen(name));
 370   if (f && f->is_external() && f->is_writeable()) {
 371     if (f->is_bool()) {
 372       return set_bool_flag(name, op, out);
 373     } else if (f->is_intx()) {
 374       return set_intx_flag(name, op, out);
 375     } else if (f->is_uintx()) {
 376       return set_uintx_flag(name, op, out);
 377     } else if (f->is_uint64_t()) {
 378       return set_uint64_t_flag(name, op, out);
 379     } else if (f->is_size_t()) {
 380       return set_size_t_flag(name, op, out);
 381     } else if (f->is_ccstr()) {
 382       return set_ccstr_flag(name, op, out);
 383     } else {
 384       ShouldNotReachHere();
 385       return JNI_ERR;
 386     }
 387   } else {
 388     return AttachListener::pd_set_flag(op, out);
 389   }
 390 }
 391 
 392 // Implementation of "printflag" command
 393 // See also: PrintVMFlagsDCmd class
 394 static jint print_flag(AttachOperation* op, outputStream* out) {
 395   const char* name = NULL;
 396   if ((name = op->arg(0)) == NULL) {
 397     out->print_cr("flag name is missing");
 398     return JNI_ERR;
 399   }
 400   Flag* f = Flag::find_flag((char*)name, strlen(name));
 401   if (f) {
 402     f->print_as_flag(out);
 403     out->cr();
 404   } else {
 405     out->print_cr("no such flag '%s'", name);
 406   }
 407   return JNI_OK;
 408 }
 409 
 410 // Table to map operation names to functions.
 411 
 412 // names must be of length <= AttachOperation::name_length_max
 413 static AttachOperationFunctionInfo funcs[] = {
 414   { "agentProperties",  get_agent_properties },
 415   { "datadump",         data_dump },
 416   { "dumpheap",         dump_heap },
 417   { "load",             JvmtiExport::load_agent_library },
 418   { "properties",       get_system_properties },
 419   { "threaddump",       thread_dump },
 420   { "inspectheap",      heap_inspection },
 421   { "setflag",          set_flag },
 422   { "printflag",        print_flag },
 423   { "jcmd",             jcmd },
 424   { NULL,               NULL }
 425 };
 426 
 427 
 428 
 429 // The Attach Listener threads services a queue. It dequeues an operation
 430 // from the queue, examines the operation name (command), and dispatches
 431 // to the corresponding function to perform the operation.
 432 
 433 static void attach_listener_thread_entry(JavaThread* thread, TRAPS) {
 434   os::set_priority(thread, NearMaxPriority);
 435 
 436   thread->record_stack_base_and_size();
 437 
 438   if (AttachListener::pd_init() != 0) {
 439     return;
 440   }
 441   AttachListener::set_initialized();
 442 
 443   for (;;) {
 444     AttachOperation* op = AttachListener::dequeue();
 445     if (op == NULL) {
 446       return;   // dequeue failed or shutdown
 447     }
 448 
 449     ResourceMark rm;
 450     bufferedStream st;
 451     jint res = JNI_OK;
 452 
 453     // handle special detachall operation
 454     if (strcmp(op->name(), AttachOperation::detachall_operation_name()) == 0) {
 455       AttachListener::detachall();
 456     } else {
 457       // find the function to dispatch too
 458       AttachOperationFunctionInfo* info = NULL;
 459       for (int i=0; funcs[i].name != NULL; i++) {
 460         const char* name = funcs[i].name;
 461         assert(strlen(name) <= AttachOperation::name_length_max, "operation <= name_length_max");
 462         if (strcmp(op->name(), name) == 0) {
 463           info = &(funcs[i]);
 464           break;
 465         }
 466       }
 467 
 468       // check for platform dependent attach operation
 469       if (info == NULL) {
 470         info = AttachListener::pd_find_operation(op->name());
 471       }
 472 
 473       if (info != NULL) {
 474         // dispatch to the function that implements this operation
 475         res = (info->func)(op, &st);
 476       } else {
 477         st.print("Operation %s not recognized!", op->name());
 478         res = JNI_ERR;
 479       }
 480     }
 481 
 482     // operation complete - send result and output to client
 483     op->complete(res, &st);
 484   }
 485 }
 486 
 487 bool AttachListener::has_init_error(TRAPS) {
 488   if (HAS_PENDING_EXCEPTION) {
 489     tty->print_cr("Exception in VM (AttachListener::init) : ");
 490     java_lang_Throwable::print(PENDING_EXCEPTION, tty);
 491     tty->cr();
 492 
 493     CLEAR_PENDING_EXCEPTION;
 494 
 495     return true;
 496   } else {
 497     return false;
 498   }
 499 }
 500 
 501 // Starts the Attach Listener thread
 502 void AttachListener::init() {
 503   EXCEPTION_MARK;
 504   Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, THREAD);
 505   if (has_init_error(THREAD)) {
 506     return;
 507   }
 508 
 509   instanceKlassHandle klass (THREAD, k);
 510   instanceHandle thread_oop = klass->allocate_instance_handle(THREAD);
 511   if (has_init_error(THREAD)) {
 512     return;
 513   }
 514 
 515   const char thread_name[] = "Attach Listener";
 516   Handle string = java_lang_String::create_from_str(thread_name, THREAD);
 517   if (has_init_error(THREAD)) {
 518     return;
 519   }
 520 
 521   // Initialize thread_oop to put it into the system threadGroup
 522   Handle thread_group (THREAD, Universe::system_thread_group());
 523   JavaValue result(T_VOID);
 524   JavaCalls::call_special(&result, thread_oop,
 525                        klass,
 526                        vmSymbols::object_initializer_name(),
 527                        vmSymbols::threadgroup_string_void_signature(),
 528                        thread_group,
 529                        string,
 530                        THREAD);
 531 
 532   if (has_init_error(THREAD)) {
 533     return;
 534   }
 535 
 536   KlassHandle group(THREAD, SystemDictionary::ThreadGroup_klass());
 537   JavaCalls::call_special(&result,
 538                         thread_group,
 539                         group,
 540                         vmSymbols::add_method_name(),
 541                         vmSymbols::thread_void_signature(),
 542                         thread_oop,             // ARG 1
 543                         THREAD);
 544   if (has_init_error(THREAD)) {
 545     return;
 546   }
 547 
 548   { MutexLocker mu(Threads_lock);
 549     JavaThread* listener_thread = new JavaThread(&attach_listener_thread_entry);
 550 
 551     // Check that thread and osthread were created
 552     if (listener_thread == NULL || listener_thread->osthread() == NULL) {
 553       vm_exit_during_initialization("java.lang.OutOfMemoryError",
 554                                     os::native_thread_creation_failed_msg());
 555     }
 556 
 557     java_lang_Thread::set_thread(thread_oop(), listener_thread);
 558     java_lang_Thread::set_daemon(thread_oop());
 559 
 560     listener_thread->set_threadObj(thread_oop());
 561     Threads::add(listener_thread);
 562     Thread::start(listener_thread);
 563   }
 564 }
 565 
 566 // Performs clean-up tasks on platforms where we can detect that the last
 567 // client has detached
 568 void AttachListener::detachall() {
 569   // call the platform dependent clean-up
 570   pd_detachall();
 571 }