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