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