1 /*
  2  * Copyright (c) 1997, 2024, 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 "cds/aotLinkedClassBulkLoader.hpp"
 27 #include "cds/cds_globals.hpp"
 28 #include "cds/cdsConfig.hpp"
 29 #include "cds/classListWriter.hpp"
 30 #include "cds/dynamicArchive.hpp"
 31 #include "cds/methodProfiler.hpp"
 32 #include "cds/metaspaceShared.hpp"
 33 #include "classfile/classLoader.hpp"
 34 #include "classfile/classLoaderDataGraph.hpp"
 35 #include "classfile/javaClasses.hpp"
 36 #include "classfile/stringTable.hpp"
 37 #include "classfile/symbolTable.hpp"
 38 #include "classfile/systemDictionary.hpp"
 39 #include "code/codeCache.hpp"
 40 #include "code/SCCache.hpp"
 41 #include "compiler/compilationMemoryStatistic.hpp"
 42 #include "compiler/compilationPolicy.hpp"
 43 #include "compiler/compileBroker.hpp"
 44 #include "compiler/compilerOracle.hpp"
 45 #include "gc/shared/collectedHeap.hpp"
 46 #include "gc/shared/stringdedup/stringDedup.hpp"
 47 #include "interpreter/bytecodeHistogram.hpp"
 48 #include "interpreter/interpreterRuntime.hpp"
 49 #include "jfr/jfrEvents.hpp"
 50 #include "jfr/support/jfrThreadId.hpp"
 51 #include "jvm.h"
 52 #include "logging/log.hpp"
 53 #include "logging/logStream.hpp"
 54 #include "memory/metaspaceUtils.hpp"
 55 #include "memory/oopFactory.hpp"
 56 #include "memory/resourceArea.hpp"
 57 #include "memory/universe.hpp"
 58 #include "nmt/memMapPrinter.hpp"
 59 #include "nmt/memTracker.hpp"
 60 #include "oops/constantPool.hpp"
 61 #include "oops/generateOopMap.hpp"
 62 #include "oops/instanceKlass.hpp"
 63 #include "oops/instanceOop.hpp"
 64 #include "oops/klassVtable.hpp"
 65 #include "oops/method.hpp"
 66 #include "oops/objArrayOop.hpp"
 67 #include "oops/oop.inline.hpp"
 68 #include "oops/symbol.hpp"
 69 #include "oops/trainingData.hpp"
 70 #include "prims/jvmtiAgentList.hpp"
 71 #include "prims/jvmtiExport.hpp"
 72 #include "prims/methodHandles.hpp"
 73 #include "runtime/continuation.hpp"
 74 #include "runtime/deoptimization.hpp"
 75 #include "runtime/flags/flagSetting.hpp"
 76 #include "runtime/globals_extension.hpp"
 77 #include "runtime/handles.inline.hpp"
 78 #include "runtime/init.hpp"
 79 #include "runtime/interfaceSupport.inline.hpp"
 80 #include "runtime/java.hpp"
 81 #include "runtime/javaThread.hpp"
 82 #include "runtime/sharedRuntime.hpp"
 83 #include "runtime/statSampler.hpp"
 84 #include "runtime/stubRoutines.hpp"
 85 #include "runtime/task.hpp"
 86 #include "runtime/threads.hpp"
 87 #include "runtime/timer.hpp"
 88 #include "runtime/trimNativeHeap.hpp"
 89 #include "runtime/vmOperations.hpp"
 90 #include "runtime/vmThread.hpp"
 91 #include "runtime/vm_version.hpp"
 92 #include "sanitizers/leak.hpp"
 93 #include "utilities/dtrace.hpp"
 94 #include "utilities/events.hpp"
 95 #include "utilities/globalDefinitions.hpp"
 96 #include "utilities/macros.hpp"
 97 #include "utilities/vmError.hpp"
 98 #ifdef COMPILER1
 99 #include "c1/c1_Compiler.hpp"
100 #include "c1/c1_Runtime1.hpp"
101 #endif
102 #ifdef COMPILER2
103 #include "code/compiledIC.hpp"
104 #include "opto/compile.hpp"
105 #include "opto/indexSet.hpp"
106 #include "opto/runtime.hpp"
107 #endif
108 #if INCLUDE_JFR
109 #include "jfr/jfr.hpp"
110 #endif
111 #if INCLUDE_JVMCI
112 #include "jvmci/jvmci.hpp"
113 #endif
114 
115 GrowableArray<Method*>* collected_profiled_methods;
116 
117 static int compare_methods(Method** a, Method** b) {
118   // compiled_invocation_count() returns int64_t, forcing the entire expression
119   // to be evaluated as int64_t. Overflow is not an issue.
120   int64_t diff = (((*b)->invocation_count() + (*b)->compiled_invocation_count())
121                 - ((*a)->invocation_count() + (*a)->compiled_invocation_count()));
122   return (diff < 0) ? -1 : (diff > 0) ? 1 : 0;
123 }
124 
125 static void collect_profiled_methods(Method* m) {
126   Thread* thread = Thread::current();
127   methodHandle mh(thread, m);
128   if ((m->method_data() != nullptr) &&
129       (PrintMethodData || CompilerOracle::should_print(mh))) {
130     collected_profiled_methods->push(m);
131   }
132 }
133 
134 static void print_method_profiling_data() {
135   if ((ProfileInterpreter COMPILER1_PRESENT(|| C1UpdateMethodData)) &&
136      (PrintMethodData || CompilerOracle::should_print_methods())) {
137     ResourceMark rm;
138     collected_profiled_methods = new GrowableArray<Method*>(1024);
139     SystemDictionary::methods_do(collect_profiled_methods);
140     collected_profiled_methods->sort(&compare_methods);
141 
142     int count = collected_profiled_methods->length();
143     int total_size = 0;
144     if (count > 0) {
145       for (int index = 0; index < count; index++) {
146         Method* m = collected_profiled_methods->at(index);
147 
148         // Instead of taking tty lock, we collect all lines into a string stream
149         // and then print them all at once.
150         ResourceMark rm2;
151         stringStream ss;
152 
153         ss.print_cr("------------------------------------------------------------------------");
154         m->print_invocation_count(&ss);
155         ss.print_cr("  mdo size: %d bytes", m->method_data()->size_in_bytes());
156         ss.cr();
157         // Dump data on parameters if any
158         if (m->method_data() != nullptr && m->method_data()->parameters_type_data() != nullptr) {
159           ss.fill_to(2);
160           m->method_data()->parameters_type_data()->print_data_on(&ss);
161         }
162         m->print_codes_on(&ss);
163         tty->print("%s", ss.as_string()); // print all at once
164         total_size += m->method_data()->size_in_bytes();
165       }
166       tty->print_cr("------------------------------------------------------------------------");
167       tty->print_cr("Total MDO size: %d bytes", total_size);
168     }
169   }
170 }
171 
172 void perf_jvm_print_on(outputStream* st);
173 
174 void log_vm_init_stats() {
175   LogStreamHandle(Info, init) log;
176   if (log.is_enabled()) {
177     SharedRuntime::print_counters_on(&log);
178     ClassLoader::print_counters(&log);
179     AOTLinkedClassBulkLoader::print_counters_on(&log);
180     log.cr();
181     // FIXME: intermittent crashes
182 //    if (CountBytecodesPerThread) {
183 //      log.print_cr("Thread info:");
184 //      class PrintThreadInfo : public ThreadClosure {
185 //        outputStream* _st;
186 //      public:
187 //        PrintThreadInfo(outputStream* st) : ThreadClosure(), _st(st) {}
188 //        void do_thread(Thread* thread) {
189 //          JavaThread* jt = JavaThread::cast(thread);
190 //          if (jt->bc_counter_value() > 0) {
191 //            _st->print_cr("  Thread " INTPTR_FORMAT ": %ld bytecodes executed (clinit: %ld)",
192 //                          p2i(jt), /*jt->name(),*/ jt->bc_counter_value(), jt->clinit_bc_counter_value());
193 //          }
194 //        }
195 //      };
196 //      PrintThreadInfo cl(&log);
197 //      Threads::java_threads_do(&cl);
198 //    }
199 //    log.cr();
200     log.print_cr("Deoptimization events: ");
201     Deoptimization::print_statistics_on(&log);
202     log.cr();
203 
204     log.print("Compilation statistics: ");
205     CompileBroker::print_statistics_on(&log);
206     log.cr();
207 
208     {
209       MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
210       log.print("Code cache statistics: ");
211       CodeCache::print_nmethod_statistics_on(&log);
212       log.cr();
213     }
214 
215     if (SCCache::is_on_for_read()) {
216       log.print_cr("Startup Code Cache: ");
217       SCCache::print_statistics_on(&log);
218       log.cr();
219       SCCache::print_timers_on(&log);
220     }
221 
222     VMThread::print_counters_on(&log);
223     log.cr();
224     MutexLockerImpl::print_counters_on(&log);
225     log.cr();
226     log.print("Runtime events for thread \"main\"");
227     if (ProfileRuntimeCalls) {
228       log.print_cr(" (%d nested events):", ProfileVMCallContext::nested_runtime_calls_count());
229 
230       InterpreterRuntime::print_counters_on(&log);
231 #ifdef COMPILER1
232       Runtime1::print_counters_on(&log);
233 #endif
234 #ifdef COMPILER2
235       OptoRuntime::print_counters_on(&log);
236       Deoptimization::print_counters_on(&log);
237 #endif
238     } else {
239       log.print_cr(": no info (%s is disabled)", (UsePerfData ? "ProfileRuntimeCalls" : "UsePerfData"));
240     }
241     log.cr();
242     perf_jvm_print_on(&log);
243     log.cr();
244     MethodHandles::print_counters_on(&log);
245   }
246 }
247 
248 void print_bytecode_count() {
249   if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
250     tty->print_cr("[BytecodeCounter::counter_value = " JLONG_FORMAT "]", BytecodeCounter::counter_value());
251   }
252 }
253 
254 #ifndef PRODUCT
255 
256 // Statistics printing (method invocation histogram)
257 
258 GrowableArray<Method*>* collected_invoked_methods;
259 
260 static void collect_invoked_methods(Method* m) {
261   if (m->invocation_count() + m->compiled_invocation_count() >= 1) {
262     collected_invoked_methods->push(m);
263   }
264 }
265 
266 
267 // Invocation count accumulators should be unsigned long to shift the
268 // overflow border. Longer-running workloads tend to create invocation
269 // counts which already overflow 32-bit counters for individual methods.
270 static void print_method_invocation_histogram() {
271   ResourceMark rm;
272   collected_invoked_methods = new GrowableArray<Method*>(1024);
273   SystemDictionary::methods_do(collect_invoked_methods);
274   collected_invoked_methods->sort(&compare_methods);
275   //
276   tty->cr();
277   tty->print_cr("Histogram Over Method Invocation Counters (cutoff = " INTX_FORMAT "):", MethodHistogramCutoff);
278   tty->cr();
279   tty->print_cr("____Count_(I+C)____Method________________________Module_________________");
280   uint64_t total        = 0,
281            int_total    = 0,
282            comp_total   = 0,
283            special_total= 0,
284            static_total = 0,
285            final_total  = 0,
286            synch_total  = 0,
287            native_total = 0,
288            access_total = 0;
289   for (int index = 0; index < collected_invoked_methods->length(); index++) {
290     // Counter values returned from getter methods are signed int.
291     // To shift the overflow border by a factor of two, we interpret
292     // them here as unsigned long. A counter can't be negative anyway.
293     Method* m = collected_invoked_methods->at(index);
294     uint64_t iic = (uint64_t)m->invocation_count();
295     uint64_t cic = (uint64_t)m->compiled_invocation_count();
296     if ((iic + cic) >= (uint64_t)MethodHistogramCutoff) m->print_invocation_count(tty);
297     int_total  += iic;
298     comp_total += cic;
299     if (m->is_final())        final_total  += iic + cic;
300     if (m->is_static())       static_total += iic + cic;
301     if (m->is_synchronized()) synch_total  += iic + cic;
302     if (m->is_native())       native_total += iic + cic;
303     if (m->is_accessor())     access_total += iic + cic;
304   }
305   tty->cr();
306   total = int_total + comp_total;
307   special_total = final_total + static_total +synch_total + native_total + access_total;
308   tty->print_cr("Invocations summary for %d methods:", collected_invoked_methods->length());
309   double total_div = (double)total;
310   tty->print_cr("\t" UINT64_FORMAT_W(12) " (100%%)  total",           total);
311   tty->print_cr("\t" UINT64_FORMAT_W(12) " (%4.1f%%) |- interpreted", int_total,     100.0 * (double)int_total    / total_div);
312   tty->print_cr("\t" UINT64_FORMAT_W(12) " (%4.1f%%) |- compiled",    comp_total,    100.0 * (double)comp_total   / total_div);
313   tty->print_cr("\t" UINT64_FORMAT_W(12) " (%4.1f%%) |- special methods (interpreted and compiled)",
314                                                                          special_total, 100.0 * (double)special_total/ total_div);
315   tty->print_cr("\t" UINT64_FORMAT_W(12) " (%4.1f%%)    |- synchronized",synch_total,   100.0 * (double)synch_total  / total_div);
316   tty->print_cr("\t" UINT64_FORMAT_W(12) " (%4.1f%%)    |- final",       final_total,   100.0 * (double)final_total  / total_div);
317   tty->print_cr("\t" UINT64_FORMAT_W(12) " (%4.1f%%)    |- static",      static_total,  100.0 * (double)static_total / total_div);
318   tty->print_cr("\t" UINT64_FORMAT_W(12) " (%4.1f%%)    |- native",      native_total,  100.0 * (double)native_total / total_div);
319   tty->print_cr("\t" UINT64_FORMAT_W(12) " (%4.1f%%)    |- accessor",    access_total,  100.0 * (double)access_total / total_div);
320   tty->cr();
321   SharedRuntime::print_call_statistics_on(tty);
322 }
323 
324 #else
325 
326 static void print_method_invocation_histogram() {}
327 
328 #endif // PRODUCT
329 
330 
331 // General statistics printing (profiling ...)
332 void print_statistics() {
333 #if INCLUDE_CDS
334   if (ReplayTraining && PrintTrainingInfo) {
335     TrainingData::print_archived_training_data_on(tty);
336   }
337 #endif
338   if (CITime) {
339     CompileBroker::print_times();
340   }
341 
342 #ifdef COMPILER1
343   if ((PrintC1Statistics || LogVMOutput || LogCompilation) && UseCompiler) {
344     FlagSetting fs(DisplayVMOutput, DisplayVMOutput && PrintC1Statistics);
345     Runtime1::print_statistics_on(tty);
346     SharedRuntime::print_statistics();
347   }
348 #endif /* COMPILER1 */
349 
350 #ifdef COMPILER2
351   if ((PrintOptoStatistics || LogVMOutput || LogCompilation) && UseCompiler) {
352     FlagSetting fs(DisplayVMOutput, DisplayVMOutput && PrintOptoStatistics);
353     Compile::print_statistics();
354     Deoptimization::print_statistics();
355 #ifndef COMPILER1
356     SharedRuntime::print_statistics();
357 #endif //COMPILER1
358   }
359 
360   if (PrintLockStatistics) {
361     OptoRuntime::print_named_counters();
362   }
363 #ifdef ASSERT
364   if (CollectIndexSetStatistics) {
365     IndexSet::print_statistics();
366   }
367 #endif // ASSERT
368 #else // COMPILER2
369 #if INCLUDE_JVMCI
370 #ifndef COMPILER1
371   if ((TraceDeoptimization || LogVMOutput || LogCompilation) && UseCompiler) {
372     FlagSetting fs(DisplayVMOutput, DisplayVMOutput && TraceDeoptimization);
373     Deoptimization::print_statistics();
374     SharedRuntime::print_statistics();
375   }
376 #endif // COMPILER1
377 #endif // INCLUDE_JVMCI
378 #endif // COMPILER2
379 
380   if (PrintNMethodStatistics) {
381     nmethod::print_statistics();
382   }
383   if (CountCompiledCalls) {
384     print_method_invocation_histogram();
385   }
386 
387   print_method_profiling_data();
388 
389   if (TimeOopMap) {
390     GenerateOopMap::print_time();
391   }
392   if (PrintSymbolTableSizeHistogram) {
393     SymbolTable::print_histogram();
394   }
395   if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
396     BytecodeCounter::print();
397   }
398   if (PrintBytecodePairHistogram) {
399     BytecodePairHistogram::print();
400   }
401 
402   if (PrintCodeCache) {
403     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
404     CodeCache::print();
405   }
406 
407   // CodeHeap State Analytics.
408   if (PrintCodeHeapAnalytics) {
409     CompileBroker::print_heapinfo(nullptr, "all", 4096); // details
410   }
411 
412   LogStreamHandle(Debug, codecache, nmethod) log;
413   if (log.is_enabled()) {
414     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
415     CodeCache::print_nmethods_on(&log);
416   }
417 
418 #ifndef PRODUCT
419   if (PrintCodeCache2) {
420     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
421     CodeCache::print_internals();
422   }
423 #endif
424 
425   if (VerifyOops && Verbose) {
426     tty->print_cr("+VerifyOops count: %d", StubRoutines::verify_oop_count());
427   }
428 
429   print_bytecode_count();
430 
431   if (PrintSystemDictionaryAtExit) {
432     ResourceMark rm;
433     MutexLocker mcld(ClassLoaderDataGraph_lock);
434     SystemDictionary::print();
435   }
436 
437   if (PrintClassLoaderDataGraphAtExit) {
438     ResourceMark rm;
439     MutexLocker mcld(ClassLoaderDataGraph_lock);
440     ClassLoaderDataGraph::print();
441   }
442 
443   // Native memory tracking data
444   if (PrintNMTStatistics) {
445     MemTracker::final_report(tty);
446   }
447 
448   if (PrintMetaspaceStatisticsAtExit) {
449     MetaspaceUtils::print_basic_report(tty, 0);
450   }
451 
452   if (CompilerOracle::should_print_final_memstat_report()) {
453     CompilationMemoryStatistic::print_all_by_size(tty, false, 0);
454   }
455 
456   ThreadsSMRSupport::log_statistics();
457 
458   log_vm_init_stats();
459 }
460 
461 // Note: before_exit() can be executed only once, if more than one threads
462 //       are trying to shutdown the VM at the same time, only one thread
463 //       can run before_exit() and all other threads must wait.
464 void before_exit(JavaThread* thread, bool halt) {
465   #define BEFORE_EXIT_NOT_RUN 0
466   #define BEFORE_EXIT_RUNNING 1
467   #define BEFORE_EXIT_DONE    2
468   static jint volatile _before_exit_status = BEFORE_EXIT_NOT_RUN;
469 
470   Events::log(thread, "Before exit entered");
471 
472   // Note: don't use a Mutex to guard the entire before_exit(), as
473   // JVMTI post_thread_end_event and post_vm_death_event will run native code.
474   // A CAS or OSMutex would work just fine but then we need to manipulate
475   // thread state for Safepoint. Here we use Monitor wait() and notify_all()
476   // for synchronization.
477   { MonitorLocker ml(BeforeExit_lock);
478     switch (_before_exit_status) {
479     case BEFORE_EXIT_NOT_RUN:
480       _before_exit_status = BEFORE_EXIT_RUNNING;
481       break;
482     case BEFORE_EXIT_RUNNING:
483       while (_before_exit_status == BEFORE_EXIT_RUNNING) {
484         ml.wait();
485       }
486       assert(_before_exit_status == BEFORE_EXIT_DONE, "invalid state");
487       return;
488     case BEFORE_EXIT_DONE:
489       // need block to avoid SS compiler bug
490       {
491         return;
492       }
493     }
494   }
495 
496   // At this point only one thread is executing this logic. Any other threads
497   // attempting to invoke before_exit() will wait above and return early once
498   // this thread finishes before_exit().
499 
500   // Do not add any additional shutdown logic between the above mutex logic and
501   // leak sanitizer logic below. Any additional shutdown code which performs some
502   // cleanup should be added after the leak sanitizer logic below.
503 
504 #ifdef LEAK_SANITIZER
505   // If we are built with LSan, we need to perform leak checking. If we are
506   // terminating normally, not halting and no VM error, we perform a normal
507   // leak check which terminates if leaks are found. If we are not terminating
508   // normally, halting or VM error, we perform a recoverable leak check which
509   // prints leaks but will not terminate.
510   if (!halt && !VMError::is_error_reported()) {
511     LSAN_DO_LEAK_CHECK();
512   } else {
513     // Ignore the return value.
514     static_cast<void>(LSAN_DO_RECOVERABLE_LEAK_CHECK());
515   }
516 #endif
517 
518 #if INCLUDE_CDS
519   MethodProfiler::process_method_hotness();
520 #endif
521 
522   // Actual shutdown logic begins here.
523 
524 #if INCLUDE_JVMCI
525   if (EnableJVMCI) {
526     JVMCI::shutdown(thread);
527   }
528 #endif
529 
530 #if INCLUDE_CDS
531   ClassListWriter::write_resolved_constants();
532   ClassListWriter::write_reflection_data();
533   ClassListWriter::write_loader_negative_lookup_cache();
534   // Dynamic CDS dumping must happen whilst we can still reliably
535   // run Java code.
536   if (CDSConfig::is_dumping_preimage_static_archive()) {
537     // Creating the hotspot.cds.preimage file
538     MetaspaceShared::preload_and_dump(thread);
539   } else {
540     DynamicArchive::dump_at_exit(thread, ArchiveClassesAtExit);
541   }
542   assert(!thread->has_pending_exception(), "must be");
543 #endif
544 
545   SCCache::close(); // Write final data and close archive
546 
547   // Hang forever on exit if we're reporting an error.
548   if (ShowMessageBoxOnError && VMError::is_error_reported()) {
549     os::infinite_sleep();
550   }
551 
552   EventThreadEnd event;
553   if (event.should_commit()) {
554     event.set_thread(JFR_JVM_THREAD_ID(thread));
555     event.commit();
556   }
557 
558   JFR_ONLY(Jfr::on_vm_shutdown(false, halt);)
559 
560   // Stop the WatcherThread. We do this before disenrolling various
561   // PeriodicTasks to reduce the likelihood of races.
562   WatcherThread::stop();
563 
564   // shut down the StatSampler task
565   StatSampler::disengage();
566   StatSampler::destroy();
567 
568   NativeHeapTrimmer::cleanup();
569 
570   // Stop concurrent GC threads
571   Universe::heap()->stop();
572 
573   // Print GC/heap related information.
574   Log(gc, heap, exit) log;
575   if (log.is_info()) {
576     ResourceMark rm;
577     LogStream ls_info(log.info());
578     Universe::print_on(&ls_info);
579     if (log.is_trace()) {
580       LogStream ls_trace(log.trace());
581       MutexLocker mcld(ClassLoaderDataGraph_lock);
582       ClassLoaderDataGraph::print_on(&ls_trace);
583     }
584   }
585 
586   if (PrintBytecodeHistogram) {
587     BytecodeHistogram::print(PrintBytecodeHistogramCutoff);
588   }
589 
590 #ifdef LINUX
591   if (DumpPerfMapAtExit) {
592     CodeCache::write_perf_map(nullptr, tty);
593   }
594   if (PrintMemoryMapAtExit) {
595     MemMapPrinter::print_all_mappings(tty);
596   }
597 #endif
598 
599   if (JvmtiExport::should_post_thread_life()) {
600     JvmtiExport::post_thread_end(thread);
601   }
602 
603   // Always call even when there are not JVMTI environments yet, since environments
604   // may be attached late and JVMTI must track phases of VM execution
605   JvmtiExport::post_vm_death();
606   JvmtiAgentList::unload_agents();
607 
608   // Terminate the signal thread
609   // Note: we don't wait until it actually dies.
610   os::terminate_signal_thread();
611 
612   if (VerifyTrainingData) {
613     EXCEPTION_MARK;
614     CompilationPolicy::replay_training_at_init(true, THREAD); // implies TrainingData::verify()
615   }
616 
617   print_statistics();
618   Universe::heap()->print_tracing_info();
619 
620   { MutexLocker ml(BeforeExit_lock);
621     _before_exit_status = BEFORE_EXIT_DONE;
622     BeforeExit_lock->notify_all();
623   }
624 
625   if (VerifyStringTableAtExit) {
626     size_t fail_cnt = StringTable::verify_and_compare_entries();
627     if (fail_cnt != 0) {
628       tty->print_cr("ERROR: fail_cnt=" SIZE_FORMAT, fail_cnt);
629       guarantee(fail_cnt == 0, "unexpected StringTable verification failures");
630     }
631   }
632 
633   #undef BEFORE_EXIT_NOT_RUN
634   #undef BEFORE_EXIT_RUNNING
635   #undef BEFORE_EXIT_DONE
636 }
637 
638 void vm_exit(int code) {
639   Thread* thread =
640       ThreadLocalStorage::is_initialized() ? Thread::current_or_null() : nullptr;
641   if (thread == nullptr) {
642     // very early initialization failure -- just exit
643     vm_direct_exit(code);
644   }
645 
646   // We'd like to add an entry to the XML log to show that the VM is
647   // terminating, but we can't safely do that here. The logic to make
648   // XML termination logging safe is tied to the termination of the
649   // VMThread, and it doesn't terminate on this exit path. See 8222534.
650 
651   if (VMThread::vm_thread() != nullptr) {
652     if (thread->is_Java_thread()) {
653       // We must be "in_vm" for the code below to work correctly.
654       // Historically there must have been some exit path for which
655       // that was not the case and so we set it explicitly - even
656       // though we no longer know what that path may be.
657       JavaThread::cast(thread)->set_thread_state(_thread_in_vm);
658     }
659 
660     // Fire off a VM_Exit operation to bring VM to a safepoint and exit
661     VM_Exit op(code);
662 
663     // 4945125 The vm thread comes to a safepoint during exit.
664     // GC vm_operations can get caught at the safepoint, and the
665     // heap is unparseable if they are caught. Grab the Heap_lock
666     // to prevent this. The GC vm_operations will not be able to
667     // queue until after we release it, but we never do that as we
668     // are terminating the VM process.
669     MutexLocker ml(Heap_lock);
670 
671     VMThread::execute(&op);
672     // should never reach here; but in case something wrong with VM Thread.
673     vm_direct_exit(code);
674   } else {
675     // VM thread is gone, just exit
676     vm_direct_exit(code);
677   }
678   ShouldNotReachHere();
679 }
680 
681 void notify_vm_shutdown() {
682   // For now, just a dtrace probe.
683   HOTSPOT_VM_SHUTDOWN();
684 }
685 
686 void vm_direct_exit(int code) {
687   notify_vm_shutdown();
688   os::wait_for_keypress_at_exit();
689   os::exit(code);
690 }
691 
692 void vm_direct_exit(int code, const char* message) {
693   if (message != nullptr) {
694     tty->print_cr("%s", message);
695   }
696   vm_direct_exit(code);
697 }
698 
699 static void vm_perform_shutdown_actions() {
700   if (is_init_completed()) {
701     Thread* thread = Thread::current_or_null();
702     if (thread != nullptr && thread->is_Java_thread()) {
703       // We are leaving the VM, set state to native (in case any OS exit
704       // handlers call back to the VM)
705       JavaThread* jt = JavaThread::cast(thread);
706       // Must always be walkable or have no last_Java_frame when in
707       // thread_in_native
708       jt->frame_anchor()->make_walkable();
709       jt->set_thread_state(_thread_in_native);
710     }
711   }
712   notify_vm_shutdown();
713 }
714 
715 void vm_shutdown()
716 {
717   vm_perform_shutdown_actions();
718   os::wait_for_keypress_at_exit();
719   os::shutdown();
720 }
721 
722 void vm_abort(bool dump_core) {
723   vm_perform_shutdown_actions();
724   os::wait_for_keypress_at_exit();
725 
726   // Flush stdout and stderr before abort.
727   fflush(stdout);
728   fflush(stderr);
729 
730   os::abort(dump_core);
731   ShouldNotReachHere();
732 }
733 
734 static void vm_notify_during_cds_dumping(const char* error, const char* message) {
735   if (error != nullptr) {
736     tty->print_cr("Error occurred during CDS dumping");
737     tty->print("%s", error);
738     if (message != nullptr) {
739       tty->print_cr(": %s", message);
740     }
741     else {
742       tty->cr();
743     }
744   }
745 }
746 
747 void vm_exit_during_cds_dumping(const char* error, const char* message) {
748   vm_notify_during_cds_dumping(error, message);
749 
750   // Failure during CDS dumping, we don't want to dump core
751   vm_abort(false);
752 }
753 
754 static void vm_notify_during_shutdown(const char* error, const char* message) {
755   if (error != nullptr) {
756     tty->print_cr("Error occurred during initialization of VM");
757     tty->print("%s", error);
758     if (message != nullptr) {
759       tty->print_cr(": %s", message);
760     }
761     else {
762       tty->cr();
763     }
764   }
765   if (ShowMessageBoxOnError && WizardMode) {
766     fatal("Error occurred during initialization of VM");
767   }
768 }
769 
770 void vm_exit_during_initialization() {
771   vm_notify_during_shutdown(nullptr, nullptr);
772 
773   // Failure during initialization, we don't want to dump core
774   vm_abort(false);
775 }
776 
777 void vm_exit_during_initialization(Handle exception) {
778   tty->print_cr("Error occurred during initialization of VM");
779   // If there are exceptions on this thread it must be cleared
780   // first and here. Any future calls to EXCEPTION_MARK requires
781   // that no pending exceptions exist.
782   JavaThread* THREAD = JavaThread::current(); // can't be null
783   if (HAS_PENDING_EXCEPTION) {
784     CLEAR_PENDING_EXCEPTION;
785   }
786   java_lang_Throwable::print_stack_trace(exception, tty);
787   tty->cr();
788   vm_notify_during_shutdown(nullptr, nullptr);
789 
790   // Failure during initialization, we don't want to dump core
791   vm_abort(false);
792 }
793 
794 void vm_exit_during_initialization(Symbol* ex, const char* message) {
795   ResourceMark rm;
796   vm_notify_during_shutdown(ex->as_C_string(), message);
797 
798   // Failure during initialization, we don't want to dump core
799   vm_abort(false);
800 }
801 
802 void vm_exit_during_initialization(const char* error, const char* message) {
803   vm_notify_during_shutdown(error, message);
804 
805   // Failure during initialization, we don't want to dump core
806   vm_abort(false);
807 }
808 
809 void vm_shutdown_during_initialization(const char* error, const char* message) {
810   vm_notify_during_shutdown(error, message);
811   vm_shutdown();
812 }
813 
814 JDK_Version JDK_Version::_current;
815 const char* JDK_Version::_java_version;
816 const char* JDK_Version::_runtime_name;
817 const char* JDK_Version::_runtime_version;
818 const char* JDK_Version::_runtime_vendor_version;
819 const char* JDK_Version::_runtime_vendor_vm_bug_url;
820 
821 void JDK_Version::initialize() {
822   assert(!_current.is_valid(), "Don't initialize twice");
823 
824   int major = VM_Version::vm_major_version();
825   int minor = VM_Version::vm_minor_version();
826   int security = VM_Version::vm_security_version();
827   int build = VM_Version::vm_build_number();
828   int patch = VM_Version::vm_patch_version();
829   _current = JDK_Version(major, minor, security, patch, build);
830 }
831 
832 void JDK_Version_init() {
833   JDK_Version::initialize();
834 }
835 
836 static int64_t encode_jdk_version(const JDK_Version& v) {
837   return
838     ((int64_t)v.major_version()          << (BitsPerByte * 4)) |
839     ((int64_t)v.minor_version()          << (BitsPerByte * 3)) |
840     ((int64_t)v.security_version()       << (BitsPerByte * 2)) |
841     ((int64_t)v.patch_version()          << (BitsPerByte * 1)) |
842     ((int64_t)v.build_number()           << (BitsPerByte * 0));
843 }
844 
845 int JDK_Version::compare(const JDK_Version& other) const {
846   assert(is_valid() && other.is_valid(), "Invalid version (uninitialized?)");
847   uint64_t e = encode_jdk_version(*this);
848   uint64_t o = encode_jdk_version(other);
849   return (e > o) ? 1 : ((e == o) ? 0 : -1);
850 }
851 
852 /* See JEP 223 */
853 void JDK_Version::to_string(char* buffer, size_t buflen) const {
854   assert(buffer && buflen > 0, "call with useful buffer");
855   size_t index = 0;
856 
857   if (!is_valid()) {
858     jio_snprintf(buffer, buflen, "%s", "(uninitialized)");
859   } else {
860     int rc = jio_snprintf(
861         &buffer[index], buflen - index, "%d.%d", _major, _minor);
862     if (rc == -1) return;
863     index += rc;
864     if (_patch > 0) {
865       rc = jio_snprintf(&buffer[index], buflen - index, ".%d.%d", _security, _patch);
866       if (rc == -1) return;
867       index += rc;
868     } else if (_security > 0) {
869       rc = jio_snprintf(&buffer[index], buflen - index, ".%d", _security);
870       if (rc == -1) return;
871       index += rc;
872     }
873     if (_build > 0) {
874       rc = jio_snprintf(&buffer[index], buflen - index, "+%d", _build);
875       if (rc == -1) return;
876       index += rc;
877     }
878   }
879 }