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