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