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