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