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