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 #ifndef PRODUCT
320   if (PrintCodeCache2) {
321     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
322     CodeCache::print_internals();
323   }
324 #endif
325 
326   if (VerifyOops && Verbose) {
327     tty->print_cr("+VerifyOops count: %d", StubRoutines::verify_oop_count());
328   }
329 
330   print_bytecode_count();
331 
332   if (PrintSystemDictionaryAtExit) {
333     ResourceMark rm;
334     MutexLocker mcld(ClassLoaderDataGraph_lock);
335     SystemDictionary::print();
336   }
337 
338   if (PrintClassLoaderDataGraphAtExit) {
339     ResourceMark rm;
340     MutexLocker mcld(ClassLoaderDataGraph_lock);
341     ClassLoaderDataGraph::print();
342   }
343 
344   // Native memory tracking data
345   if (PrintNMTStatistics) {
346     MemTracker::final_report(tty);
347   }
348 
349   if (PrintMetaspaceStatisticsAtExit) {
350     MetaspaceUtils::print_basic_report(tty, 0);
351   }
352 
353   if (CompilerOracle::should_print_final_memstat_report()) {
354     CompilationMemoryStatistic::print_all_by_size(tty, false, 0);
355   }
356 
357   ThreadsSMRSupport::log_statistics();


358 }
359 
360 // Note: before_exit() can be executed only once, if more than one threads
361 //       are trying to shutdown the VM at the same time, only one thread
362 //       can run before_exit() and all other threads must wait.
363 void before_exit(JavaThread* thread, bool halt) {
364   #define BEFORE_EXIT_NOT_RUN 0
365   #define BEFORE_EXIT_RUNNING 1
366   #define BEFORE_EXIT_DONE    2
367   static jint volatile _before_exit_status = BEFORE_EXIT_NOT_RUN;
368 
369   // Note: don't use a Mutex to guard the entire before_exit(), as
370   // JVMTI post_thread_end_event and post_vm_death_event will run native code.
371   // A CAS or OSMutex would work just fine but then we need to manipulate
372   // thread state for Safepoint. Here we use Monitor wait() and notify_all()
373   // for synchronization.
374   { MonitorLocker ml(BeforeExit_lock);
375     switch (_before_exit_status) {
376     case BEFORE_EXIT_NOT_RUN:
377       _before_exit_status = BEFORE_EXIT_RUNNING;
378       break;
379     case BEFORE_EXIT_RUNNING:
380       while (_before_exit_status == BEFORE_EXIT_RUNNING) {
381         ml.wait();
382       }
383       assert(_before_exit_status == BEFORE_EXIT_DONE, "invalid state");
384       return;
385     case BEFORE_EXIT_DONE:
386       // need block to avoid SS compiler bug
387       {
388         return;
389       }
390     }
391   }
392 
393   // At this point only one thread is executing this logic. Any other threads
394   // attempting to invoke before_exit() will wait above and return early once
395   // this thread finishes before_exit().
396 
397   // Do not add any additional shutdown logic between the above mutex logic and
398   // leak sanitizer logic below. Any additional shutdown code which performs some
399   // cleanup should be added after the leak sanitizer logic below.
400 
401 #ifdef LEAK_SANITIZER
402   // If we are built with LSan, we need to perform leak checking. If we are
403   // terminating normally, not halting and no VM error, we perform a normal
404   // leak check which terminates if leaks are found. If we are not terminating
405   // normally, halting or VM error, we perform a recoverable leak check which
406   // prints leaks but will not terminate.
407   if (!halt && !VMError::is_error_reported()) {
408     LSAN_DO_LEAK_CHECK();
409   } else {
410     // Ignore the return value.
411     static_cast<void>(LSAN_DO_RECOVERABLE_LEAK_CHECK());
412   }
413 #endif
414 


415 #if INCLUDE_CDS



416   // Dynamic CDS dumping must happen whilst we can still reliably
417   // run Java code.
418   DynamicArchive::dump_at_exit(thread, ArchiveClassesAtExit);





419   assert(!thread->has_pending_exception(), "must be");
420 #endif
421 
422 
423   // Actual shutdown logic begins here.
424 
425 #if INCLUDE_JVMCI
426   if (EnableJVMCI) {
427     JVMCI::shutdown(thread);
428   }
429 #endif
430 


431   // Hang forever on exit if we're reporting an error.
432   if (ShowMessageBoxOnError && VMError::is_error_reported()) {
433     os::infinite_sleep();
434   }
435 
436   EventThreadEnd event;
437   if (event.should_commit()) {
438     event.set_thread(JFR_JVM_THREAD_ID(thread));
439     event.commit();
440   }
441 
442   JFR_ONLY(Jfr::on_vm_shutdown(false, halt);)
443 
444   // Stop the WatcherThread. We do this before disenrolling various
445   // PeriodicTasks to reduce the likelihood of races.
446   WatcherThread::stop();
447 
448   // shut down the StatSampler task
449   StatSampler::disengage();
450   StatSampler::destroy();
451 
452   NativeHeapTrimmer::cleanup();
453 
454   // Stop concurrent GC threads
455   Universe::heap()->stop();
456 
457   // Print GC/heap related information.
458   Log(gc, heap, exit) log;
459   if (log.is_info()) {
460     ResourceMark rm;
461     LogStream ls_info(log.info());
462     Universe::print_on(&ls_info);
463     if (log.is_trace()) {
464       LogStream ls_trace(log.trace());
465       MutexLocker mcld(ClassLoaderDataGraph_lock);
466       ClassLoaderDataGraph::print_on(&ls_trace);
467     }
468   }
469 
470   if (PrintBytecodeHistogram) {
471     BytecodeHistogram::print();
472   }
473 
474 #ifdef LINUX
475   if (DumpPerfMapAtExit) {
476     CodeCache::write_perf_map();
477   }
478 #endif
479 
480   if (JvmtiExport::should_post_thread_life()) {
481     JvmtiExport::post_thread_end(thread);
482   }
483 
484   // Always call even when there are not JVMTI environments yet, since environments
485   // may be attached late and JVMTI must track phases of VM execution
486   JvmtiExport::post_vm_death();
487   JvmtiAgentList::unload_agents();
488 
489   // Terminate the signal thread
490   // Note: we don't wait until it actually dies.
491   os::terminate_signal_thread();
492 





493   print_statistics();
494   Universe::heap()->print_tracing_info();
495 
496   { MutexLocker ml(BeforeExit_lock);
497     _before_exit_status = BEFORE_EXIT_DONE;
498     BeforeExit_lock->notify_all();
499   }
500 
501   if (VerifyStringTableAtExit) {
502     size_t fail_cnt = StringTable::verify_and_compare_entries();
503     if (fail_cnt != 0) {
504       tty->print_cr("ERROR: fail_cnt=" SIZE_FORMAT, fail_cnt);
505       guarantee(fail_cnt == 0, "unexpected StringTable verification failures");
506     }
507   }
508 
509   #undef BEFORE_EXIT_NOT_RUN
510   #undef BEFORE_EXIT_RUNNING
511   #undef BEFORE_EXIT_DONE
512 }
513 
514 void vm_exit(int code) {
515   Thread* thread =
516       ThreadLocalStorage::is_initialized() ? Thread::current_or_null() : nullptr;
517   if (thread == nullptr) {
518     // very early initialization failure -- just exit
519     vm_direct_exit(code);
520   }
521 
522   // We'd like to add an entry to the XML log to show that the VM is
523   // terminating, but we can't safely do that here. The logic to make
524   // XML termination logging safe is tied to the termination of the
525   // VMThread, and it doesn't terminate on this exit path. See 8222534.
526 
527   if (VMThread::vm_thread() != nullptr) {
528     if (thread->is_Java_thread()) {
529       // We must be "in_vm" for the code below to work correctly.
530       // Historically there must have been some exit path for which
531       // that was not the case and so we set it explicitly - even
532       // though we no longer know what that path may be.
533       JavaThread::cast(thread)->set_thread_state(_thread_in_vm);
534     }
535 
536     // Fire off a VM_Exit operation to bring VM to a safepoint and exit
537     VM_Exit op(code);
538 
539     // 4945125 The vm thread comes to a safepoint during exit.
540     // GC vm_operations can get caught at the safepoint, and the
541     // heap is unparseable if they are caught. Grab the Heap_lock
542     // to prevent this. The GC vm_operations will not be able to
543     // queue until after we release it, but we never do that as we
544     // are terminating the VM process.
545     MutexLocker ml(Heap_lock);
546 
547     VMThread::execute(&op);
548     // should never reach here; but in case something wrong with VM Thread.
549     vm_direct_exit(code);
550   } else {
551     // VM thread is gone, just exit
552     vm_direct_exit(code);
553   }
554   ShouldNotReachHere();
555 }
556 
557 void notify_vm_shutdown() {
558   // For now, just a dtrace probe.
559   HOTSPOT_VM_SHUTDOWN();
560 }
561 
562 void vm_direct_exit(int code) {
563   notify_vm_shutdown();
564   os::wait_for_keypress_at_exit();
565   os::exit(code);
566 }
567 
568 void vm_direct_exit(int code, const char* message) {
569   if (message != nullptr) {
570     tty->print_cr("%s", message);
571   }
572   vm_direct_exit(code);
573 }
574 
575 static void vm_perform_shutdown_actions() {
576   if (is_init_completed()) {
577     Thread* thread = Thread::current_or_null();
578     if (thread != nullptr && thread->is_Java_thread()) {
579       // We are leaving the VM, set state to native (in case any OS exit
580       // handlers call back to the VM)
581       JavaThread* jt = JavaThread::cast(thread);
582       // Must always be walkable or have no last_Java_frame when in
583       // thread_in_native
584       jt->frame_anchor()->make_walkable();
585       jt->set_thread_state(_thread_in_native);
586     }
587   }
588   notify_vm_shutdown();
589 }
590 
591 void vm_shutdown()
592 {
593   vm_perform_shutdown_actions();
594   os::wait_for_keypress_at_exit();
595   os::shutdown();
596 }
597 
598 void vm_abort(bool dump_core) {
599   vm_perform_shutdown_actions();
600   os::wait_for_keypress_at_exit();
601 
602   // Flush stdout and stderr before abort.
603   fflush(stdout);
604   fflush(stderr);
605 
606   os::abort(dump_core);
607   ShouldNotReachHere();
608 }
609 
610 static void vm_notify_during_cds_dumping(const char* error, const char* message) {
611   if (error != nullptr) {
612     tty->print_cr("Error occurred during CDS dumping");
613     tty->print("%s", error);
614     if (message != nullptr) {
615       tty->print_cr(": %s", message);
616     }
617     else {
618       tty->cr();
619     }
620   }
621 }
622 
623 void vm_exit_during_cds_dumping(const char* error, const char* message) {
624   vm_notify_during_cds_dumping(error, message);
625 
626   // Failure during CDS dumping, we don't want to dump core
627   vm_abort(false);
628 }
629 
630 static void vm_notify_during_shutdown(const char* error, const char* message) {
631   if (error != nullptr) {
632     tty->print_cr("Error occurred during initialization of VM");
633     tty->print("%s", error);
634     if (message != nullptr) {
635       tty->print_cr(": %s", message);
636     }
637     else {
638       tty->cr();
639     }
640   }
641   if (ShowMessageBoxOnError && WizardMode) {
642     fatal("Error occurred during initialization of VM");
643   }
644 }
645 
646 void vm_exit_during_initialization() {
647   vm_notify_during_shutdown(nullptr, nullptr);
648 
649   // Failure during initialization, we don't want to dump core
650   vm_abort(false);
651 }
652 
653 void vm_exit_during_initialization(Handle exception) {
654   tty->print_cr("Error occurred during initialization of VM");
655   // If there are exceptions on this thread it must be cleared
656   // first and here. Any future calls to EXCEPTION_MARK requires
657   // that no pending exceptions exist.
658   JavaThread* THREAD = JavaThread::current(); // can't be null
659   if (HAS_PENDING_EXCEPTION) {
660     CLEAR_PENDING_EXCEPTION;
661   }
662   java_lang_Throwable::print_stack_trace(exception, tty);
663   tty->cr();
664   vm_notify_during_shutdown(nullptr, nullptr);
665 
666   // Failure during initialization, we don't want to dump core
667   vm_abort(false);
668 }
669 
670 void vm_exit_during_initialization(Symbol* ex, const char* message) {
671   ResourceMark rm;
672   vm_notify_during_shutdown(ex->as_C_string(), message);
673 
674   // Failure during initialization, we don't want to dump core
675   vm_abort(false);
676 }
677 
678 void vm_exit_during_initialization(const char* error, const char* message) {
679   vm_notify_during_shutdown(error, message);
680 
681   // Failure during initialization, we don't want to dump core
682   vm_abort(false);
683 }
684 
685 void vm_shutdown_during_initialization(const char* error, const char* message) {
686   vm_notify_during_shutdown(error, message);
687   vm_shutdown();
688 }
689 
690 JDK_Version JDK_Version::_current;
691 const char* JDK_Version::_java_version;
692 const char* JDK_Version::_runtime_name;
693 const char* JDK_Version::_runtime_version;
694 const char* JDK_Version::_runtime_vendor_version;
695 const char* JDK_Version::_runtime_vendor_vm_bug_url;
696 
697 void JDK_Version::initialize() {
698   assert(!_current.is_valid(), "Don't initialize twice");
699 
700   int major = VM_Version::vm_major_version();
701   int minor = VM_Version::vm_minor_version();
702   int security = VM_Version::vm_security_version();
703   int build = VM_Version::vm_build_number();
704   int patch = VM_Version::vm_patch_version();
705   _current = JDK_Version(major, minor, security, patch, build);
706 }
707 
708 void JDK_Version_init() {
709   JDK_Version::initialize();
710 }
711 
712 static int64_t encode_jdk_version(const JDK_Version& v) {
713   return
714     ((int64_t)v.major_version()          << (BitsPerByte * 4)) |
715     ((int64_t)v.minor_version()          << (BitsPerByte * 3)) |
716     ((int64_t)v.security_version()       << (BitsPerByte * 2)) |
717     ((int64_t)v.patch_version()          << (BitsPerByte * 1)) |
718     ((int64_t)v.build_number()           << (BitsPerByte * 0));
719 }
720 
721 int JDK_Version::compare(const JDK_Version& other) const {
722   assert(is_valid() && other.is_valid(), "Invalid version (uninitialized?)");
723   uint64_t e = encode_jdk_version(*this);
724   uint64_t o = encode_jdk_version(other);
725   return (e > o) ? 1 : ((e == o) ? 0 : -1);
726 }
727 
728 /* See JEP 223 */
729 void JDK_Version::to_string(char* buffer, size_t buflen) const {
730   assert(buffer && buflen > 0, "call with useful buffer");
731   size_t index = 0;
732 
733   if (!is_valid()) {
734     jio_snprintf(buffer, buflen, "%s", "(uninitialized)");
735   } else {
736     int rc = jio_snprintf(
737         &buffer[index], buflen - index, "%d.%d", _major, _minor);
738     if (rc == -1) return;
739     index += rc;
740     if (_patch > 0) {
741       rc = jio_snprintf(&buffer[index], buflen - index, ".%d.%d", _security, _patch);
742       if (rc == -1) return;
743       index += rc;
744     } else if (_security > 0) {
745       rc = jio_snprintf(&buffer[index], buflen - index, ".%d", _security);
746       if (rc == -1) return;
747       index += rc;
748     }
749     if (_build > 0) {
750       rc = jio_snprintf(&buffer[index], buflen - index, "+%d", _build);
751       if (rc == -1) return;
752       index += rc;
753     }
754   }
755 }
--- EOF ---