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