1 /*
   2  * Copyright (c) 1997, 2019, 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/collectedHeap.hpp"
  31 #include "gc/shared/isGCActiveMark.hpp"
  32 #include "logging/log.hpp"
  33 #include "logging/logStream.hpp"
  34 #include "logging/logConfiguration.hpp"
  35 #include "memory/heapInspection.hpp"
  36 #include "memory/resourceArea.hpp"
  37 #include "memory/universe.hpp"
  38 #include "oops/symbol.hpp"
  39 #include "runtime/arguments.hpp"
  40 #include "runtime/deoptimization.hpp"
  41 #include "runtime/frame.inline.hpp"
  42 #include "runtime/interfaceSupport.inline.hpp"
  43 #include "runtime/sweeper.hpp"
  44 #include "runtime/synchronizer.hpp"
  45 #include "runtime/thread.inline.hpp"
  46 #include "runtime/threadSMR.inline.hpp"
  47 #include "runtime/vmOperations.hpp"
  48 #include "services/threadService.hpp"
  49 
  50 #define VM_OP_NAME_INITIALIZE(name) #name,
  51 
  52 const char* VM_Operation::_names[VM_Operation::VMOp_Terminating] = \
  53   { VM_OPS_DO(VM_OP_NAME_INITIALIZE) };
  54 
  55 void VM_Operation::set_calling_thread(Thread* thread) {
  56   _calling_thread = thread;
  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_Verify::doit() {
 197   Universe::heap()->prepare_for_verify();
 198   Universe::verify();
 199 }
 200 
 201 bool VM_PrintThreads::doit_prologue() {
 202   // Get Heap_lock if concurrent locks will be dumped
 203   if (_print_concurrent_locks) {
 204     Heap_lock->lock();
 205   }
 206   return true;
 207 }
 208 
 209 void VM_PrintThreads::doit() {
 210   Threads::print_on(_out, true, false, _print_concurrent_locks, _print_extended_info);
 211 }
 212 
 213 void VM_PrintThreads::doit_epilogue() {
 214   if (_print_concurrent_locks) {
 215     // Release Heap_lock
 216     Heap_lock->unlock();
 217   }
 218 }
 219 
 220 void VM_PrintJNI::doit() {
 221   JNIHandles::print_on(_out);
 222 }
 223 
 224 void VM_PrintMetadata::doit() {
 225   MetaspaceUtils::print_report(_out, _scale, _flags);
 226 }
 227 
 228 VM_FindDeadlocks::~VM_FindDeadlocks() {
 229   if (_deadlocks != NULL) {
 230     DeadlockCycle* cycle = _deadlocks;
 231     while (cycle != NULL) {
 232       DeadlockCycle* d = cycle;
 233       cycle = cycle->next();
 234       delete d;
 235     }
 236   }
 237 }
 238 
 239 void VM_FindDeadlocks::doit() {
 240   // Update the hazard ptr in the originating thread to the current
 241   // list of threads. This VM operation needs the current list of
 242   // threads for proper deadlock detection and those are the
 243   // JavaThreads we need to be protected when we return info to the
 244   // originating thread.
 245   _setter.set();
 246 
 247   _deadlocks = ThreadService::find_deadlocks_at_safepoint(_setter.list(), _concurrent_locks);
 248   if (_out != NULL) {
 249     int num_deadlocks = 0;
 250     for (DeadlockCycle* cycle = _deadlocks; cycle != NULL; cycle = cycle->next()) {
 251       num_deadlocks++;
 252       cycle->print_on_with(_setter.list(), _out);
 253     }
 254 
 255     if (num_deadlocks == 1) {
 256       _out->print_cr("\nFound 1 deadlock.\n");
 257       _out->flush();
 258     } else if (num_deadlocks > 1) {
 259       _out->print_cr("\nFound %d deadlocks.\n", num_deadlocks);
 260       _out->flush();
 261     }
 262   }
 263 }
 264 
 265 VM_ThreadDump::VM_ThreadDump(ThreadDumpResult* result,
 266                              int max_depth,
 267                              bool with_locked_monitors,
 268                              bool with_locked_synchronizers) {
 269   _result = result;
 270   _num_threads = 0; // 0 indicates all threads
 271   _threads = NULL;
 272   _result = result;
 273   _max_depth = max_depth;
 274   _with_locked_monitors = with_locked_monitors;
 275   _with_locked_synchronizers = with_locked_synchronizers;
 276 }
 277 
 278 VM_ThreadDump::VM_ThreadDump(ThreadDumpResult* result,
 279                              GrowableArray<instanceHandle>* threads,
 280                              int num_threads,
 281                              int max_depth,
 282                              bool with_locked_monitors,
 283                              bool with_locked_synchronizers) {
 284   _result = result;
 285   _num_threads = num_threads;
 286   _threads = threads;
 287   _result = result;
 288   _max_depth = max_depth;
 289   _with_locked_monitors = with_locked_monitors;
 290   _with_locked_synchronizers = with_locked_synchronizers;
 291 }
 292 
 293 bool VM_ThreadDump::doit_prologue() {
 294   if (_with_locked_synchronizers) {
 295     // Acquire Heap_lock to dump concurrent locks
 296     Heap_lock->lock();
 297   }
 298 
 299   return true;
 300 }
 301 
 302 void VM_ThreadDump::doit_epilogue() {
 303   if (_with_locked_synchronizers) {
 304     // Release Heap_lock
 305     Heap_lock->unlock();
 306   }
 307 }
 308 
 309 void VM_ThreadDump::doit() {
 310   ResourceMark rm;
 311 
 312   // Set the hazard ptr in the originating thread to protect the
 313   // current list of threads. This VM operation needs the current list
 314   // of threads for a proper dump and those are the JavaThreads we need
 315   // to be protected when we return info to the originating thread.
 316   _result->set_t_list();
 317 
 318   ConcurrentLocksDump concurrent_locks(true);
 319   if (_with_locked_synchronizers) {
 320     concurrent_locks.dump_at_safepoint();
 321   }
 322 
 323   if (_num_threads == 0) {
 324     // Snapshot all live threads
 325 
 326     for (uint i = 0; i < _result->t_list()->length(); i++) {
 327       JavaThread* jt = _result->t_list()->thread_at(i);
 328       if (jt->is_exiting() ||
 329           jt->is_hidden_from_external_view())  {
 330         // skip terminating threads and hidden threads
 331         continue;
 332       }
 333       ThreadConcurrentLocks* tcl = NULL;
 334       if (_with_locked_synchronizers) {
 335         tcl = concurrent_locks.thread_concurrent_locks(jt);
 336       }
 337       snapshot_thread(jt, tcl);
 338     }
 339   } else {
 340     // Snapshot threads in the given _threads array
 341     // A dummy snapshot is created if a thread doesn't exist
 342 
 343     for (int i = 0; i < _num_threads; i++) {
 344       instanceHandle th = _threads->at(i);
 345       if (th() == NULL) {
 346         // skip if the thread doesn't exist
 347         // Add a dummy snapshot
 348         _result->add_thread_snapshot();
 349         continue;
 350       }
 351 
 352       // Dump thread stack only if the thread is alive and not exiting
 353       // and not VM internal thread.
 354       JavaThread* jt = java_lang_Thread::thread(th());
 355       if (jt != NULL && !_result->t_list()->includes(jt)) {
 356         // _threads[i] doesn't refer to a valid JavaThread; this check
 357         // is primarily for JVM_DumpThreads() which doesn't have a good
 358         // way to validate the _threads array.
 359         jt = NULL;
 360       }
 361       if (jt == NULL || /* thread not alive */
 362           jt->is_exiting() ||
 363           jt->is_hidden_from_external_view())  {
 364         // add a NULL snapshot if skipped
 365         _result->add_thread_snapshot();
 366         continue;
 367       }
 368       ThreadConcurrentLocks* tcl = NULL;
 369       if (_with_locked_synchronizers) {
 370         tcl = concurrent_locks.thread_concurrent_locks(jt);
 371       }
 372       snapshot_thread(jt, tcl);
 373     }
 374   }
 375 }
 376 
 377 void VM_ThreadDump::snapshot_thread(JavaThread* java_thread, ThreadConcurrentLocks* tcl) {
 378   ThreadSnapshot* snapshot = _result->add_thread_snapshot(java_thread);
 379   snapshot->dump_stack_at_safepoint(_max_depth, _with_locked_monitors);
 380   snapshot->set_concurrent_locks(tcl);
 381 }
 382 
 383 volatile bool VM_Exit::_vm_exited = false;
 384 Thread * volatile VM_Exit::_shutdown_thread = NULL;
 385 
 386 int VM_Exit::set_vm_exited() {
 387 
 388   Thread * thr_cur = Thread::current();
 389 
 390   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint already");
 391 
 392   int num_active = 0;
 393 
 394   _shutdown_thread = thr_cur;
 395   _vm_exited = true;                                // global flag
 396   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *thr = jtiwh.next(); ) {
 397     if (thr!=thr_cur && thr->thread_state() == _thread_in_native) {
 398       ++num_active;
 399       thr->set_terminated(JavaThread::_vm_exited);  // per-thread flag
 400     }
 401   }
 402 
 403   return num_active;
 404 }
 405 
 406 int VM_Exit::wait_for_threads_in_native_to_block() {
 407   // VM exits at safepoint. This function must be called at the final safepoint
 408   // to wait for threads in _thread_in_native state to be quiescent.
 409   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint already");
 410 
 411   Thread * thr_cur = Thread::current();
 412   Monitor timer(Mutex::leaf, "VM_Exit timer", true,
 413                 Monitor::_safepoint_check_never);
 414 
 415   // Compiler threads need longer wait because they can access VM data directly
 416   // while in native. If they are active and some structures being used are
 417   // deleted by the shutdown sequence, they will crash. On the other hand, user
 418   // threads must go through native=>Java/VM transitions first to access VM
 419   // data, and they will be stopped during state transition. In theory, we
 420   // don't have to wait for user threads to be quiescent, but it's always
 421   // better to terminate VM when current thread is the only active thread, so
 422   // wait for user threads too. Numbers are in 10 milliseconds.
 423   int max_wait_user_thread = 30;                  // at least 300 milliseconds
 424   int max_wait_compiler_thread = 1000;            // at least 10 seconds
 425 
 426   int max_wait = max_wait_compiler_thread;
 427 
 428   int attempts = 0;
 429   JavaThreadIteratorWithHandle jtiwh;
 430   while (true) {
 431     int num_active = 0;
 432     int num_active_compiler_thread = 0;
 433 
 434     jtiwh.rewind();
 435     for (; JavaThread *thr = jtiwh.next(); ) {
 436       if (thr!=thr_cur && thr->thread_state() == _thread_in_native) {
 437         num_active++;
 438         if (thr->is_Compiler_thread()) {
 439 #if INCLUDE_JVMCI
 440           CompilerThread* ct = (CompilerThread*) thr;
 441           if (ct->compiler() == NULL || !ct->compiler()->is_jvmci()) {
 442             num_active_compiler_thread++;
 443           } else {
 444             // A JVMCI compiler thread never accesses VM data structures
 445             // while in _thread_in_native state so there's no need to wait
 446             // for it and potentially add a 300 millisecond delay to VM
 447             // shutdown.
 448             num_active--;
 449           }
 450 #else
 451           num_active_compiler_thread++;
 452 #endif
 453         }
 454       }
 455     }
 456 
 457     if (num_active == 0) {
 458        return 0;
 459     } else if (attempts > max_wait) {
 460        return num_active;
 461     } else if (num_active_compiler_thread == 0 && attempts > max_wait_user_thread) {
 462        return num_active;
 463     }
 464 
 465     attempts++;
 466 
 467     MonitorLocker ml(&timer, Mutex::_no_safepoint_check_flag);
 468     ml.wait(10);
 469   }
 470 }
 471 
 472 bool VM_Exit::doit_prologue() {
 473   if (AsyncDeflateIdleMonitors && log_is_enabled(Info, monitorinflation)) {
 474     // AsyncDeflateIdleMonitors does a special deflation at the VM_Exit
 475     // safepoint in order to reduce the in-use monitor population that
 476     // is reported by ObjectSynchronizer::log_in_use_monitor_details()
 477     // at VM exit.
 478     ObjectSynchronizer::set_is_special_deflation_requested(true);
 479   }
 480   return true;
 481 }
 482 
 483 void VM_Exit::doit() {
 484 
 485   if (VerifyBeforeExit) {
 486     HandleMark hm(VMThread::vm_thread());
 487     // Among other things, this ensures that Eden top is correct.
 488     Universe::heap()->prepare_for_verify();
 489     // Silent verification so as not to pollute normal output,
 490     // unless we really asked for it.
 491     Universe::verify();
 492   }
 493 
 494   CompileBroker::set_should_block();
 495 
 496   // Wait for a short period for threads in native to block. Any thread
 497   // still executing native code after the wait will be stopped at
 498   // native==>Java/VM barriers.
 499   // Among 16276 JCK tests, 94% of them come here without any threads still
 500   // running in native; the other 6% are quiescent within 250ms (Ultra 80).
 501   wait_for_threads_in_native_to_block();
 502 
 503   set_vm_exited();
 504 
 505   // We'd like to call IdealGraphPrinter::clean_up() to finalize the
 506   // XML logging, but we can't safely do that here. The logic to make
 507   // XML termination logging safe is tied to the termination of the
 508   // VMThread, and it doesn't terminate on this exit path. See 8222534.
 509 
 510   // cleanup globals resources before exiting. exit_globals() currently
 511   // cleans up outputStream resources and PerfMemory resources.
 512   exit_globals();
 513 
 514   LogConfiguration::finalize();
 515 
 516   // Check for exit hook
 517   exit_hook_t exit_hook = Arguments::exit_hook();
 518   if (exit_hook != NULL) {
 519     // exit hook should exit.
 520     exit_hook(_exit_code);
 521     // ... but if it didn't, we must do it here
 522     vm_direct_exit(_exit_code);
 523   } else {
 524     vm_direct_exit(_exit_code);
 525   }
 526 }
 527 
 528 
 529 void VM_Exit::wait_if_vm_exited() {
 530   if (_vm_exited &&
 531       Thread::current_or_null() != _shutdown_thread) {
 532     // _vm_exited is set at safepoint, and the Threads_lock is never released
 533     // we will block here until the process dies
 534     Threads_lock->lock();
 535     ShouldNotReachHere();
 536   }
 537 }
 538 
 539 void VM_PrintCompileQueue::doit() {
 540   CompileBroker::print_compile_queues(_out);
 541 }
 542 
 543 #if INCLUDE_SERVICES
 544 void VM_PrintClassHierarchy::doit() {
 545   KlassHierarchy::print_class_hierarchy(_out, _print_interfaces, _print_subclasses, _classname);
 546 }
 547 #endif