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