1 /*
   2  * Copyright (c) 1997, 2016, 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/symbolTable.hpp"
  27 #include "classfile/vmSymbols.hpp"
  28 #include "code/codeCache.hpp"
  29 #include "compiler/compileBroker.hpp"
  30 #include "gc/shared/isGCActiveMark.hpp"
  31 #include "logging/log.hpp"
  32 #include "memory/heapInspection.hpp"
  33 #include "memory/resourceArea.hpp"
  34 #include "oops/symbol.hpp"
  35 #include "runtime/arguments.hpp"
  36 #include "runtime/deoptimization.hpp"
  37 #include "runtime/interfaceSupport.hpp"
  38 #include "runtime/sweeper.hpp"
  39 #include "runtime/thread.inline.hpp"
  40 #include "runtime/vm_operations.hpp"
  41 #include "services/threadService.hpp"
  42 #include "trace/tracing.hpp"
  43 
  44 #define VM_OP_NAME_INITIALIZE(name) #name,
  45 
  46 const char* VM_Operation::_names[VM_Operation::VMOp_Terminating] = \
  47   { VM_OPS_DO(VM_OP_NAME_INITIALIZE) };
  48 
  49 void VM_Operation::set_calling_thread(Thread* thread, ThreadPriority priority) {
  50   _calling_thread = thread;
  51   assert(MinPriority <= priority && priority <= MaxPriority, "sanity check");
  52   _priority = priority;
  53 }
  54 
  55 
  56 void VM_Operation::evaluate() {
  57   ResourceMark rm;
  58   outputStream* debugstream;
  59   bool enabled = log_is_enabled(Debug, vmoperation);
  60   if (enabled) {
  61     debugstream = Log(vmoperation)::debug_stream();
  62     debugstream->print("begin ");
  63     print_on_error(debugstream);
  64     debugstream->cr();
  65   }
  66   doit();
  67   if (enabled) {
  68     debugstream->print("end ");
  69     print_on_error(debugstream);
  70     debugstream->cr();
  71   }
  72 }
  73 
  74 const char* VM_Operation::mode_to_string(Mode mode) {
  75   switch(mode) {
  76     case _safepoint      : return "safepoint";
  77     case _no_safepoint   : return "no safepoint";
  78     case _concurrent     : return "concurrent";
  79     case _async_safepoint: return "async safepoint";
  80     default              : return "unknown";
  81   }
  82 }
  83 // Called by fatal error handler.
  84 void VM_Operation::print_on_error(outputStream* st) const {
  85   st->print("VM_Operation (" PTR_FORMAT "): ", p2i(this));
  86   st->print("%s", name());
  87 
  88   const char* mode = mode_to_string(evaluation_mode());
  89   st->print(", mode: %s", mode);
  90 
  91   if (calling_thread()) {
  92     st->print(", requested by thread " PTR_FORMAT, p2i(calling_thread()));
  93   }
  94 }
  95 
  96 void VM_ThreadStop::doit() {
  97   assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint");
  98   JavaThread* target = java_lang_Thread::thread(target_thread());
  99   // Note that this now allows multiple ThreadDeath exceptions to be
 100   // thrown at a thread.
 101   if (target != NULL) {
 102     // the thread has run and is not already in the process of exiting
 103     target->send_thread_stop(throwable());
 104   }
 105 }
 106 
 107 void VM_ClearICs::doit() {
 108   if (_preserve_static_stubs) {
 109     CodeCache::cleanup_inline_caches();
 110   } else {
 111     CodeCache::clear_inline_caches();
 112   }
 113 }
 114 
 115 void VM_Deoptimize::doit() {
 116   // We do not want any GCs to happen while we are in the middle of this VM operation
 117   ResourceMark rm;
 118   DeoptimizationMarker dm;
 119 
 120   // Deoptimize all activations depending on marked nmethods
 121   Deoptimization::deoptimize_dependents();
 122 
 123   // Make the dependent methods not entrant
 124   CodeCache::make_marked_nmethods_not_entrant();
 125 }
 126 
 127 void VM_MarkActiveNMethods::doit() {
 128   NMethodSweeper::mark_active_nmethods();
 129 }
 130 
 131 VM_DeoptimizeFrame::VM_DeoptimizeFrame(JavaThread* thread, intptr_t* id, int reason) {
 132   _thread = thread;
 133   _id     = id;
 134   _reason = reason;
 135 }
 136 
 137 
 138 void VM_DeoptimizeFrame::doit() {
 139   assert(_reason > Deoptimization::Reason_none && _reason < Deoptimization::Reason_LIMIT, "invalid deopt reason");
 140   Deoptimization::deoptimize_frame_internal(_thread, _id, (Deoptimization::DeoptReason)_reason);
 141 }
 142 
 143 
 144 #ifndef PRODUCT
 145 
 146 void VM_DeoptimizeAll::doit() {
 147   DeoptimizationMarker dm;
 148   // deoptimize all java threads in the system
 149   if (DeoptimizeALot) {
 150     for (JavaThread* thread = Threads::first(); thread != NULL; thread = thread->next()) {
 151       if (thread->has_last_Java_frame()) {
 152         thread->deoptimize();
 153       }
 154     }
 155   } else if (DeoptimizeRandom) {
 156 
 157     // Deoptimize some selected threads and frames
 158     int tnum = os::random() & 0x3;
 159     int fnum =  os::random() & 0x3;
 160     int tcount = 0;
 161     for (JavaThread* thread = Threads::first(); thread != NULL; thread = thread->next()) {
 162       if (thread->has_last_Java_frame()) {
 163         if (tcount++ == tnum)  {
 164         tcount = 0;
 165           int fcount = 0;
 166           // Deoptimize some selected frames.
 167           // Biased llocking wants a updated register map
 168           for(StackFrameStream fst(thread, UseBiasedLocking); !fst.is_done(); fst.next()) {
 169             if (fst.current()->can_be_deoptimized()) {
 170               if (fcount++ == fnum) {
 171                 fcount = 0;
 172                 Deoptimization::deoptimize(thread, *fst.current(), fst.register_map());
 173               }
 174             }
 175           }
 176         }
 177       }
 178     }
 179   }
 180 }
 181 
 182 
 183 void VM_ZombieAll::doit() {
 184   JavaThread *thread = (JavaThread *)calling_thread();
 185   assert(thread->is_Java_thread(), "must be a Java thread");
 186   thread->make_zombies();
 187 }
 188 
 189 #endif // !PRODUCT
 190 
 191 void VM_UnlinkSymbols::doit() {
 192   JavaThread *thread = (JavaThread *)calling_thread();
 193   assert(thread->is_Java_thread(), "must be a Java thread");
 194   SymbolTable::unlink();
 195 }
 196 
 197 void VM_Verify::doit() {
 198   Universe::heap()->prepare_for_verify();
 199   Universe::verify();
 200 }
 201 
 202 bool VM_PrintThreads::doit_prologue() {
 203   // Make sure AbstractOwnableSynchronizer is loaded
 204   JavaThread* jt = JavaThread::current();
 205   java_util_concurrent_locks_AbstractOwnableSynchronizer::initialize(jt);
 206   if (jt->has_pending_exception()) {
 207     return false;
 208   }
 209 
 210   // Get Heap_lock if concurrent locks will be dumped
 211   if (_print_concurrent_locks) {
 212     Heap_lock->lock();
 213   }
 214   return true;
 215 }
 216 
 217 void VM_PrintThreads::doit() {
 218   Threads::print_on(_out, true, false, _print_concurrent_locks);
 219 }
 220 
 221 void VM_PrintThreads::doit_epilogue() {
 222   if (_print_concurrent_locks) {
 223     // Release Heap_lock
 224     Heap_lock->unlock();
 225   }
 226 }
 227 
 228 void VM_PrintJNI::doit() {
 229   JNIHandles::print_on(_out);
 230 }
 231 
 232 VM_FindDeadlocks::~VM_FindDeadlocks() {
 233   if (_deadlocks != NULL) {
 234     DeadlockCycle* cycle = _deadlocks;
 235     while (cycle != NULL) {
 236       DeadlockCycle* d = cycle;
 237       cycle = cycle->next();
 238       delete d;
 239     }
 240   }
 241 }
 242 
 243 bool VM_FindDeadlocks::doit_prologue() {
 244   if (_concurrent_locks) {
 245     // Make sure AbstractOwnableSynchronizer is loaded
 246     JavaThread* jt = JavaThread::current();
 247     java_util_concurrent_locks_AbstractOwnableSynchronizer::initialize(jt);
 248     if (jt->has_pending_exception()) {
 249       return false;
 250     }
 251   }
 252 
 253   return true;
 254 }
 255 
 256 void VM_FindDeadlocks::doit() {
 257   _deadlocks = ThreadService::find_deadlocks_at_safepoint(_concurrent_locks);
 258   if (_out != NULL) {
 259     int num_deadlocks = 0;
 260     for (DeadlockCycle* cycle = _deadlocks; cycle != NULL; cycle = cycle->next()) {
 261       num_deadlocks++;
 262       cycle->print_on(_out);
 263     }
 264 
 265     if (num_deadlocks == 1) {
 266       _out->print_cr("\nFound 1 deadlock.\n");
 267       _out->flush();
 268     } else if (num_deadlocks > 1) {
 269       _out->print_cr("\nFound %d deadlocks.\n", num_deadlocks);
 270       _out->flush();
 271     }
 272   }
 273 }
 274 
 275 VM_ThreadDump::VM_ThreadDump(ThreadDumpResult* result,
 276                              int max_depth,
 277                              bool with_locked_monitors,
 278                              bool with_locked_synchronizers) {
 279   _result = result;
 280   _num_threads = 0; // 0 indicates all threads
 281   _threads = NULL;
 282   _result = result;
 283   _max_depth = max_depth;
 284   _with_locked_monitors = with_locked_monitors;
 285   _with_locked_synchronizers = with_locked_synchronizers;
 286 }
 287 
 288 VM_ThreadDump::VM_ThreadDump(ThreadDumpResult* result,
 289                              GrowableArray<instanceHandle>* threads,
 290                              int num_threads,
 291                              int max_depth,
 292                              bool with_locked_monitors,
 293                              bool with_locked_synchronizers) {
 294   _result = result;
 295   _num_threads = num_threads;
 296   _threads = threads;
 297   _result = result;
 298   _max_depth = max_depth;
 299   _with_locked_monitors = with_locked_monitors;
 300   _with_locked_synchronizers = with_locked_synchronizers;
 301 }
 302 
 303 bool VM_ThreadDump::doit_prologue() {
 304   // Make sure AbstractOwnableSynchronizer is loaded
 305   JavaThread* jt = JavaThread::current();
 306   java_util_concurrent_locks_AbstractOwnableSynchronizer::initialize(jt);
 307   if (jt->has_pending_exception()) {
 308     return false;
 309   }
 310 
 311   if (_with_locked_synchronizers) {
 312     // Acquire Heap_lock to dump concurrent locks
 313     Heap_lock->lock();
 314   }
 315 
 316   return true;
 317 }
 318 
 319 void VM_ThreadDump::doit_epilogue() {
 320   if (_with_locked_synchronizers) {
 321     // Release Heap_lock
 322     Heap_lock->unlock();
 323   }
 324 }
 325 
 326 void VM_ThreadDump::doit() {
 327   ResourceMark rm;
 328 
 329   ConcurrentLocksDump concurrent_locks(true);
 330   if (_with_locked_synchronizers) {
 331     concurrent_locks.dump_at_safepoint();
 332   }
 333 
 334   if (_num_threads == 0) {
 335     // Snapshot all live threads
 336     for (JavaThread* jt = Threads::first(); jt != NULL; jt = jt->next()) {
 337       if (jt->is_exiting() ||
 338           jt->is_hidden_from_external_view())  {
 339         // skip terminating threads and hidden threads
 340         continue;
 341       }
 342       ThreadConcurrentLocks* tcl = NULL;
 343       if (_with_locked_synchronizers) {
 344         tcl = concurrent_locks.thread_concurrent_locks(jt);
 345       }
 346       ThreadSnapshot* ts = snapshot_thread(jt, tcl);
 347       _result->add_thread_snapshot(ts);
 348     }
 349   } else {
 350     // Snapshot threads in the given _threads array
 351     // A dummy snapshot is created if a thread doesn't exist
 352     for (int i = 0; i < _num_threads; i++) {
 353       instanceHandle th = _threads->at(i);
 354       if (th() == NULL) {
 355         // skip if the thread doesn't exist
 356         // Add a dummy snapshot
 357         _result->add_thread_snapshot(new ThreadSnapshot());
 358         continue;
 359       }
 360 
 361       // Dump thread stack only if the thread is alive and not exiting
 362       // and not VM internal thread.
 363       JavaThread* jt = java_lang_Thread::thread(th());
 364       if (jt == NULL || /* thread not alive */
 365           jt->is_exiting() ||
 366           jt->is_hidden_from_external_view())  {
 367         // add a NULL snapshot if skipped
 368         _result->add_thread_snapshot(new ThreadSnapshot());
 369         continue;
 370       }
 371       ThreadConcurrentLocks* tcl = NULL;
 372       if (_with_locked_synchronizers) {
 373         tcl = concurrent_locks.thread_concurrent_locks(jt);
 374       }
 375       ThreadSnapshot* ts = snapshot_thread(jt, tcl);
 376       _result->add_thread_snapshot(ts);
 377     }
 378   }
 379 }
 380 
 381 ThreadSnapshot* VM_ThreadDump::snapshot_thread(JavaThread* java_thread, ThreadConcurrentLocks* tcl) {
 382   ThreadSnapshot* snapshot = new ThreadSnapshot(java_thread);
 383   snapshot->dump_stack_at_safepoint(_max_depth, _with_locked_monitors);
 384   snapshot->set_concurrent_locks(tcl);
 385   return snapshot;
 386 }
 387 
 388 volatile bool VM_Exit::_vm_exited = false;
 389 Thread * VM_Exit::_shutdown_thread = NULL;
 390 
 391 int VM_Exit::set_vm_exited() {
 392 
 393   Thread * thr_cur = Thread::current();
 394 
 395   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint already");
 396 
 397   int num_active = 0;
 398 
 399   _shutdown_thread = thr_cur;
 400   _vm_exited = true;                                // global flag
 401   for(JavaThread *thr = Threads::first(); thr != NULL; thr = thr->next())
 402     if (thr!=thr_cur && thr->thread_state() == _thread_in_native) {
 403       ++num_active;
 404       thr->set_terminated(JavaThread::_vm_exited);  // per-thread flag
 405     }
 406 
 407   return num_active;
 408 }
 409 
 410 int VM_Exit::wait_for_threads_in_native_to_block() {
 411   // VM exits at safepoint. This function must be called at the final safepoint
 412   // to wait for threads in _thread_in_native state to be quiescent.
 413   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint already");
 414 
 415   Thread * thr_cur = Thread::current();
 416   Monitor timer(Mutex::leaf, "VM_Exit timer", true,
 417                 Monitor::_safepoint_check_never);
 418 
 419   // Compiler threads need longer wait because they can access VM data directly
 420   // while in native. If they are active and some structures being used are
 421   // deleted by the shutdown sequence, they will crash. On the other hand, user
 422   // threads must go through native=>Java/VM transitions first to access VM
 423   // data, and they will be stopped during state transition. In theory, we
 424   // don't have to wait for user threads to be quiescent, but it's always
 425   // better to terminate VM when current thread is the only active thread, so
 426   // wait for user threads too. Numbers are in 10 milliseconds.
 427   int max_wait_user_thread = 30;                  // at least 300 milliseconds
 428   int max_wait_compiler_thread = 1000;            // at least 10 seconds
 429 
 430   int max_wait = max_wait_compiler_thread;
 431 
 432   int attempts = 0;
 433   while (true) {
 434     int num_active = 0;
 435     int num_active_compiler_thread = 0;
 436 
 437     for(JavaThread *thr = Threads::first(); thr != NULL; thr = thr->next()) {
 438       if (thr!=thr_cur && thr->thread_state() == _thread_in_native) {
 439         num_active++;
 440         if (thr->is_Compiler_thread()) {
 441           num_active_compiler_thread++;
 442         }
 443       }
 444     }
 445 
 446     if (num_active == 0) {
 447        return 0;
 448     } else if (attempts > max_wait) {
 449        return num_active;
 450     } else if (num_active_compiler_thread == 0 && attempts > max_wait_user_thread) {
 451        return num_active;
 452     }
 453 
 454     attempts++;
 455 
 456     MutexLockerEx ml(&timer, Mutex::_no_safepoint_check_flag);
 457     timer.wait(Mutex::_no_safepoint_check_flag, 10);
 458   }
 459 }
 460 
 461 void VM_Exit::doit() {
 462   CompileBroker::set_should_block();
 463 
 464   // Wait for a short period for threads in native to block. Any thread
 465   // still executing native code after the wait will be stopped at
 466   // native==>Java/VM barriers.
 467   // Among 16276 JCK tests, 94% of them come here without any threads still
 468   // running in native; the other 6% are quiescent within 250ms (Ultra 80).
 469   wait_for_threads_in_native_to_block();
 470 
 471   set_vm_exited();
 472 
 473   // cleanup globals resources before exiting. exit_globals() currently
 474   // cleans up outputStream resources and PerfMemory resources.
 475   exit_globals();
 476 
 477   // Check for exit hook
 478   exit_hook_t exit_hook = Arguments::exit_hook();
 479   if (exit_hook != NULL) {
 480     // exit hook should exit.
 481     exit_hook(_exit_code);
 482     // ... but if it didn't, we must do it here
 483     vm_direct_exit(_exit_code);
 484   } else {
 485     vm_direct_exit(_exit_code);
 486   }
 487 }
 488 
 489 
 490 void VM_Exit::wait_if_vm_exited() {
 491   if (_vm_exited &&
 492       Thread::current_or_null() != _shutdown_thread) {
 493     // _vm_exited is set at safepoint, and the Threads_lock is never released
 494     // we will block here until the process dies
 495     Threads_lock->lock_without_safepoint_check();
 496     ShouldNotReachHere();
 497   }
 498 }
 499 
 500 void VM_PrintCompileQueue::doit() {
 501   CompileBroker::print_compile_queues(_out);
 502 }
 503 
 504 #if INCLUDE_SERVICES
 505 void VM_PrintClassHierarchy::doit() {
 506   KlassHierarchy::print_class_hierarchy(_out, _print_interfaces, _print_subclasses, _classname);
 507 }
 508 #endif