1 /*
  2  * Copyright (c) 1997, 2025, 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/cds_globals.hpp"
 26 #include "cds/cdsConfig.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.inline.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 = %zd):", 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 
445   if (CDSConfig::is_dumping_preimage_static_archive()) {
446     MetaspaceShared::preload_and_dump(thread);
447   }
448 #endif
449 
450   // Hang forever on exit if we're reporting an error.
451   if (ShowMessageBoxOnError && VMError::is_error_reported()) {
452     os::infinite_sleep();
453   }
454 
455   EventThreadEnd event;
456   if (event.should_commit()) {
457     event.set_thread(JFR_JVM_THREAD_ID(thread));
458     event.commit();
459   }
460 
461   JFR_ONLY(Jfr::on_vm_shutdown(false, halt);)
462 
463   // Stop the WatcherThread. We do this before disenrolling various
464   // PeriodicTasks to reduce the likelihood of races.
465   WatcherThread::stop();
466 
467   // shut down the StatSampler task
468   StatSampler::disengage();
469   StatSampler::destroy();
470 
471   NativeHeapTrimmer::cleanup();
472 
473   // Stop concurrent GC threads
474   Universe::heap()->stop();
475 
476   // Print GC/heap related information.
477   Log(gc, heap, exit) log;
478   if (log.is_info()) {
479     ResourceMark rm;
480     LogStream ls_info(log.info());
481     Universe::print_on(&ls_info);
482     if (log.is_trace()) {
483       LogStream ls_trace(log.trace());
484       MutexLocker mcld(ClassLoaderDataGraph_lock);
485       ClassLoaderDataGraph::print_on(&ls_trace);
486     }
487   }
488 
489   if (PrintBytecodeHistogram) {
490     BytecodeHistogram::print();
491   }
492 
493 #ifdef LINUX
494   if (DumpPerfMapAtExit) {
495     CodeCache::write_perf_map(nullptr, tty);
496   }
497   if (PrintMemoryMapAtExit) {
498     MemMapPrinter::print_all_mappings(tty);
499   }
500 #endif
501 
502   if (JvmtiExport::should_post_thread_life()) {
503     JvmtiExport::post_thread_end(thread);
504   }
505 
506   // Always call even when there are not JVMTI environments yet, since environments
507   // may be attached late and JVMTI must track phases of VM execution
508   JvmtiExport::post_vm_death();
509   JvmtiAgentList::unload_agents();
510 
511   // Terminate the signal thread
512   // Note: we don't wait until it actually dies.
513   os::terminate_signal_thread();
514 
515   print_statistics();
516   Universe::heap()->print_tracing_info();
517 
518   { MutexLocker ml(BeforeExit_lock);
519     _before_exit_status = BEFORE_EXIT_DONE;
520     BeforeExit_lock->notify_all();
521   }
522 
523   if (VerifyStringTableAtExit) {
524     size_t fail_cnt = StringTable::verify_and_compare_entries();
525     if (fail_cnt != 0) {
526       tty->print_cr("ERROR: fail_cnt=%zu", fail_cnt);
527       guarantee(fail_cnt == 0, "unexpected StringTable verification failures");
528     }
529   }
530 
531   #undef BEFORE_EXIT_NOT_RUN
532   #undef BEFORE_EXIT_RUNNING
533   #undef BEFORE_EXIT_DONE
534 }
535 
536 void vm_exit(int code) {
537   Thread* thread =
538       ThreadLocalStorage::is_initialized() ? Thread::current_or_null() : nullptr;
539   if (thread == nullptr) {
540     // very early initialization failure -- just exit
541     vm_direct_exit(code);
542   }
543 
544   // We'd like to add an entry to the XML log to show that the VM is
545   // terminating, but we can't safely do that here. The logic to make
546   // XML termination logging safe is tied to the termination of the
547   // VMThread, and it doesn't terminate on this exit path. See 8222534.
548 
549   if (VMThread::vm_thread() != nullptr) {
550     if (thread->is_Java_thread()) {
551       // We must be "in_vm" for the code below to work correctly.
552       // Historically there must have been some exit path for which
553       // that was not the case and so we set it explicitly - even
554       // though we no longer know what that path may be.
555       JavaThread::cast(thread)->set_thread_state(_thread_in_vm);
556     }
557 
558     // Fire off a VM_Exit operation to bring VM to a safepoint and exit
559     VM_Exit op(code);
560 
561     // 4945125 The vm thread comes to a safepoint during exit.
562     // GC vm_operations can get caught at the safepoint, and the
563     // heap is unparseable if they are caught. Grab the Heap_lock
564     // to prevent this. The GC vm_operations will not be able to
565     // queue until after we release it, but we never do that as we
566     // are terminating the VM process.
567     MutexLocker ml(Heap_lock);
568 
569     VMThread::execute(&op);
570     // should never reach here; but in case something wrong with VM Thread.
571     vm_direct_exit(code);
572   } else {
573     // VM thread is gone, just exit
574     vm_direct_exit(code);
575   }
576   ShouldNotReachHere();
577 }
578 
579 void notify_vm_shutdown() {
580   // For now, just a dtrace probe.
581   HOTSPOT_VM_SHUTDOWN();
582 }
583 
584 void vm_direct_exit(int code) {
585   notify_vm_shutdown();
586   os::wait_for_keypress_at_exit();
587   os::exit(code);
588 }
589 
590 void vm_direct_exit(int code, const char* message) {
591   if (message != nullptr) {
592     tty->print_cr("%s", message);
593   }
594   vm_direct_exit(code);
595 }
596 
597 static void vm_perform_shutdown_actions() {
598   if (is_init_completed()) {
599     Thread* thread = Thread::current_or_null();
600     if (thread != nullptr && thread->is_Java_thread()) {
601       // We are leaving the VM, set state to native (in case any OS exit
602       // handlers call back to the VM)
603       JavaThread* jt = JavaThread::cast(thread);
604       // Must always be walkable or have no last_Java_frame when in
605       // thread_in_native
606       jt->frame_anchor()->make_walkable();
607       jt->set_thread_state(_thread_in_native);
608     }
609   }
610   notify_vm_shutdown();
611 }
612 
613 void vm_shutdown()
614 {
615   vm_perform_shutdown_actions();
616   os::wait_for_keypress_at_exit();
617   os::shutdown();
618 }
619 
620 void vm_abort(bool dump_core) {
621   vm_perform_shutdown_actions();
622   os::wait_for_keypress_at_exit();
623 
624   // Flush stdout and stderr before abort.
625   fflush(stdout);
626   fflush(stderr);
627 
628   os::abort(dump_core);
629   ShouldNotReachHere();
630 }
631 
632 static void vm_notify_during_cds_dumping(const char* error, const char* message) {
633   if (error != nullptr) {
634     tty->print_cr("Error occurred during CDS dumping");
635     tty->print("%s", error);
636     if (message != nullptr) {
637       tty->print_cr(": %s", message);
638     }
639     else {
640       tty->cr();
641     }
642   }
643 }
644 
645 void vm_exit_during_cds_dumping(const char* error, const char* message) {
646   vm_notify_during_cds_dumping(error, message);
647 
648   // Failure during CDS dumping, we don't want to dump core
649   vm_abort(false);
650 }
651 
652 static void vm_notify_during_shutdown(const char* error, const char* message) {
653   if (error != nullptr) {
654     tty->print_cr("Error occurred during initialization of VM");
655     tty->print("%s", error);
656     if (message != nullptr) {
657       tty->print_cr(": %s", message);
658     }
659     else {
660       tty->cr();
661     }
662   }
663   if (ShowMessageBoxOnError && WizardMode) {
664     fatal("Error occurred during initialization of VM");
665   }
666 }
667 
668 void vm_exit_during_initialization() {
669   vm_notify_during_shutdown(nullptr, nullptr);
670 
671   // Failure during initialization, we don't want to dump core
672   vm_abort(false);
673 }
674 
675 void vm_exit_during_initialization(Handle exception) {
676   tty->print_cr("Error occurred during initialization of VM");
677   // If there are exceptions on this thread it must be cleared
678   // first and here. Any future calls to EXCEPTION_MARK requires
679   // that no pending exceptions exist.
680   JavaThread* THREAD = JavaThread::current(); // can't be null
681   if (HAS_PENDING_EXCEPTION) {
682     CLEAR_PENDING_EXCEPTION;
683   }
684   java_lang_Throwable::print_stack_trace(exception, tty);
685   tty->cr();
686   vm_notify_during_shutdown(nullptr, nullptr);
687 
688   // Failure during initialization, we don't want to dump core
689   vm_abort(false);
690 }
691 
692 void vm_exit_during_initialization(Symbol* ex, const char* message) {
693   ResourceMark rm;
694   vm_notify_during_shutdown(ex->as_C_string(), message);
695 
696   // Failure during initialization, we don't want to dump core
697   vm_abort(false);
698 }
699 
700 void vm_exit_during_initialization(const char* error, const char* message) {
701   vm_notify_during_shutdown(error, message);
702 
703   // Failure during initialization, we don't want to dump core
704   vm_abort(false);
705 }
706 
707 void vm_shutdown_during_initialization(const char* error, const char* message) {
708   vm_notify_during_shutdown(error, message);
709   vm_shutdown();
710 }
711 
712 JDK_Version JDK_Version::_current;
713 const char* JDK_Version::_java_version;
714 const char* JDK_Version::_runtime_name;
715 const char* JDK_Version::_runtime_version;
716 const char* JDK_Version::_runtime_vendor_version;
717 const char* JDK_Version::_runtime_vendor_vm_bug_url;
718 
719 void JDK_Version::initialize() {
720   assert(!_current.is_valid(), "Don't initialize twice");
721 
722   int major = VM_Version::vm_major_version();
723   int minor = VM_Version::vm_minor_version();
724   int security = VM_Version::vm_security_version();
725   int build = VM_Version::vm_build_number();
726   int patch = VM_Version::vm_patch_version();
727   _current = JDK_Version(major, minor, security, patch, build);
728 }
729 
730 void JDK_Version_init() {
731   JDK_Version::initialize();
732 }
733 
734 static int64_t encode_jdk_version(const JDK_Version& v) {
735   return
736     ((int64_t)v.major_version()          << (BitsPerByte * 4)) |
737     ((int64_t)v.minor_version()          << (BitsPerByte * 3)) |
738     ((int64_t)v.security_version()       << (BitsPerByte * 2)) |
739     ((int64_t)v.patch_version()          << (BitsPerByte * 1)) |
740     ((int64_t)v.build_number()           << (BitsPerByte * 0));
741 }
742 
743 int JDK_Version::compare(const JDK_Version& other) const {
744   assert(is_valid() && other.is_valid(), "Invalid version (uninitialized?)");
745   uint64_t e = encode_jdk_version(*this);
746   uint64_t o = encode_jdk_version(other);
747   return (e > o) ? 1 : ((e == o) ? 0 : -1);
748 }
749 
750 /* See JEP 223 */
751 void JDK_Version::to_string(char* buffer, size_t buflen) const {
752   assert(buffer && buflen > 0, "call with useful buffer");
753   size_t index = 0;
754 
755   if (!is_valid()) {
756     jio_snprintf(buffer, buflen, "%s", "(uninitialized)");
757   } else {
758     int rc = jio_snprintf(
759         &buffer[index], buflen - index, "%d.%d", _major, _minor);
760     if (rc == -1) return;
761     index += rc;
762     if (_patch > 0) {
763       rc = jio_snprintf(&buffer[index], buflen - index, ".%d.%d", _security, _patch);
764       if (rc == -1) return;
765       index += rc;
766     } else if (_security > 0) {
767       rc = jio_snprintf(&buffer[index], buflen - index, ".%d", _security);
768       if (rc == -1) return;
769       index += rc;
770     }
771     if (_build > 0) {
772       rc = jio_snprintf(&buffer[index], buflen - index, "+%d", _build);
773       if (rc == -1) return;
774       index += rc;
775     }
776   }
777 }