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