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