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