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/cdsConfig.hpp"
 28 #include "cds/classListWriter.hpp"
 29 #include "cds/classPreloader.hpp"
 30 #include "cds/dynamicArchive.hpp"
 31 #include "cds/methodProfiler.hpp"
 32 #include "cds/metaspaceShared.hpp"
 33 #include "classfile/classLoader.hpp"
 34 #include "classfile/classLoaderDataGraph.hpp"
 35 #include "classfile/javaClasses.hpp"
 36 #include "classfile/stringTable.hpp"
 37 #include "classfile/symbolTable.hpp"
 38 #include "classfile/systemDictionary.hpp"
 39 #include "code/codeCache.hpp"
 40 #include "code/SCCache.hpp"
 41 #include "compiler/compilationMemoryStatistic.hpp"
 42 #include "compiler/compilationPolicy.hpp"
 43 #include "compiler/compileBroker.hpp"
 44 #include "compiler/compilerOracle.hpp"
 45 #include "gc/shared/collectedHeap.hpp"
 46 #include "gc/shared/stringdedup/stringDedup.hpp"
 47 #include "interpreter/bytecodeHistogram.hpp"
 48 #include "interpreter/interpreterRuntime.hpp"
 49 #include "jfr/jfrEvents.hpp"
 50 #include "jfr/support/jfrThreadId.hpp"
 51 #include "jvm.h"
 52 #include "logging/log.hpp"
 53 #include "logging/logStream.hpp"
 54 #include "memory/metaspaceUtils.hpp"
 55 #include "memory/oopFactory.hpp"
 56 #include "memory/resourceArea.hpp"
 57 #include "memory/universe.hpp"
 58 #include "nmt/memTracker.hpp"
 59 #include "oops/constantPool.hpp"
 60 #include "oops/generateOopMap.hpp"
 61 #include "oops/instanceKlass.hpp"
 62 #include "oops/instanceOop.hpp"
 63 #include "oops/klassVtable.hpp"
 64 #include "oops/method.hpp"
 65 #include "oops/objArrayOop.hpp"
 66 #include "oops/oop.inline.hpp"
 67 #include "oops/symbol.hpp"
 68 #include "oops/trainingData.hpp"
 69 #include "prims/jvmtiAgentList.hpp"
 70 #include "prims/jvmtiExport.hpp"
 71 #include "prims/methodHandles.hpp"
 72 #include "runtime/continuation.hpp"
 73 #include "runtime/deoptimization.hpp"
 74 #include "runtime/flags/flagSetting.hpp"
 75 #include "runtime/globals_extension.hpp"
 76 #include "runtime/handles.inline.hpp"
 77 #include "runtime/init.hpp"
 78 #include "runtime/interfaceSupport.inline.hpp"
 79 #include "runtime/java.hpp"
 80 #include "runtime/javaThread.hpp"
 81 #include "runtime/sharedRuntime.hpp"
 82 #include "runtime/statSampler.hpp"
 83 #include "runtime/stubRoutines.hpp"
 84 #include "runtime/task.hpp"
 85 #include "runtime/threads.hpp"
 86 #include "runtime/timer.hpp"
 87 #include "runtime/trimNativeHeap.hpp"
 88 #include "runtime/vmOperations.hpp"
 89 #include "runtime/vmThread.hpp"
 90 #include "runtime/vm_version.hpp"
 91 #include "sanitizers/leak.hpp"
 92 #include "utilities/dtrace.hpp"
 93 #include "utilities/globalDefinitions.hpp"
 94 #include "utilities/macros.hpp"
 95 #include "utilities/vmError.hpp"
 96 #ifdef COMPILER1
 97 #include "c1/c1_Compiler.hpp"
 98 #include "c1/c1_Runtime1.hpp"
 99 #endif
100 #ifdef COMPILER2
101 #include "code/compiledIC.hpp"
102 #include "opto/compile.hpp"
103 #include "opto/indexSet.hpp"
104 #include "opto/runtime.hpp"
105 #endif
106 #if INCLUDE_JFR
107 #include "jfr/jfr.hpp"
108 #endif
109 #if INCLUDE_JVMCI
110 #include "jvmci/jvmci.hpp"
111 #endif
112 
113 GrowableArray<Method*>* collected_profiled_methods;
114 
115 static int compare_methods(Method** a, Method** b) {
116   // compiled_invocation_count() returns int64_t, forcing the entire expression
117   // to be evaluated as int64_t. Overflow is not an issue.
118   int64_t diff = (((*b)->invocation_count() + (*b)->compiled_invocation_count())
119                 - ((*a)->invocation_count() + (*a)->compiled_invocation_count()));
120   return (diff < 0) ? -1 : (diff > 0) ? 1 : 0;
121 }
122 
123 static void collect_profiled_methods(Method* m) {
124   Thread* thread = Thread::current();
125   methodHandle mh(thread, m);
126   if ((m->method_data() != nullptr) &&
127       (PrintMethodData || CompilerOracle::should_print(mh))) {
128     collected_profiled_methods->push(m);
129   }
130 }
131 
132 static void print_method_profiling_data() {
133   if ((ProfileInterpreter COMPILER1_PRESENT(|| C1UpdateMethodData)) &&
134      (PrintMethodData || CompilerOracle::should_print_methods())) {
135     ResourceMark rm;
136     collected_profiled_methods = new GrowableArray<Method*>(1024);
137     SystemDictionary::methods_do(collect_profiled_methods);
138     collected_profiled_methods->sort(&compare_methods);
139 
140     int count = collected_profiled_methods->length();
141     int total_size = 0;
142     if (count > 0) {
143       for (int index = 0; index < count; index++) {
144         Method* m = collected_profiled_methods->at(index);
145 
146         // Instead of taking tty lock, we collect all lines into a string stream
147         // and then print them all at once.
148         ResourceMark rm2;
149         stringStream ss;
150 
151         ss.print_cr("------------------------------------------------------------------------");
152         m->print_invocation_count(&ss);
153         ss.print_cr("  mdo size: %d bytes", m->method_data()->size_in_bytes());
154         ss.cr();
155         // Dump data on parameters if any
156         if (m->method_data() != nullptr && m->method_data()->parameters_type_data() != nullptr) {
157           ss.fill_to(2);
158           m->method_data()->parameters_type_data()->print_data_on(&ss);
159         }
160         m->print_codes_on(&ss);
161         tty->print("%s", ss.as_string()); // print all at once
162         total_size += m->method_data()->size_in_bytes();
163       }
164       tty->print_cr("------------------------------------------------------------------------");
165       tty->print_cr("Total MDO size: %d bytes", total_size);
166     }
167   }
168 }
169 
170 void perf_jvm_print_on(outputStream* st);
171 
172 void log_vm_init_stats() {
173   LogStreamHandle(Info, init) log;
174   if (log.is_enabled()) {
175     SharedRuntime::print_counters_on(&log);
176     ClassLoader::print_counters();
177     ClassPreloader::print_counters();
178     log.cr();
179     // FIXME: intermittent crashes
180 //    if (CountBytecodesPerThread) {
181 //      log.print_cr("Thread info:");
182 //      class PrintThreadInfo : public ThreadClosure {
183 //        outputStream* _st;
184 //      public:
185 //        PrintThreadInfo(outputStream* st) : ThreadClosure(), _st(st) {}
186 //        void do_thread(Thread* thread) {
187 //          JavaThread* jt = JavaThread::cast(thread);
188 //          if (jt->bc_counter_value() > 0) {
189 //            _st->print_cr("  Thread " INTPTR_FORMAT ": %ld bytecodes executed (clinit: %ld)",
190 //                          p2i(jt), /*jt->name(),*/ jt->bc_counter_value(), jt->clinit_bc_counter_value());
191 //          }
192 //        }
193 //      };
194 //      PrintThreadInfo cl(&log);
195 //      Threads::java_threads_do(&cl);
196 //    }
197 //    log.cr();
198     log.print_cr("Deoptimization events: ");
199     Deoptimization::print_statistics_on(&log);
200     log.cr();
201 
202     log.print("Compilation statistics: ");
203     CompileBroker::print_statistics_on(&log);
204     log.cr();
205 
206     {
207       MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
208       log.print("Code cache statistics: ");
209       CodeCache::print_nmethod_statistics_on(&log);
210       log.cr();
211     }
212 
213     if (SCCache::is_on_for_read()) {
214       log.print_cr("Startup Code Cache: ");
215       SCCache::print_statistics_on(&log);
216       log.cr();
217       SCCache::print_timers_on(&log);
218     }
219 
220     VMThread::print_counters_on(&log);
221     log.cr();
222     MutexLockerImpl::print_counters_on(&log);
223     log.cr();
224     log.print("Runtime events for thread \"main\"");
225     if (ProfileRuntimeCalls) {
226       log.print_cr(" (%d nested events):", ProfileVMCallContext::nested_runtime_calls_count());
227 
228       Runtime1::print_counters_on(&log);
229       OptoRuntime::print_counters_on(&log);
230       InterpreterRuntime::print_counters_on(&log);
231       Deoptimization::print_counters_on(&log);
232     } else {
233       log.print_cr(": no info (%s is disabled)", (UsePerfData ? "ProfileRuntimeCalls" : "UsePerfData"));
234     }
235     log.cr();
236     perf_jvm_print_on(&log);
237     log.cr();
238     MethodHandles::print_counters_on(&log);
239   }
240 }
241 
242 void print_bytecode_count() {
243   if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
244     tty->print_cr("[BytecodeCounter::counter_value = %ld]", BytecodeCounter::counter_value());
245   }
246 }
247 
248 #ifndef PRODUCT
249 
250 // Statistics printing (method invocation histogram)
251 
252 GrowableArray<Method*>* collected_invoked_methods;
253 
254 static void collect_invoked_methods(Method* m) {
255   if (m->invocation_count() + m->compiled_invocation_count() >= 1) {
256     collected_invoked_methods->push(m);
257   }
258 }
259 
260 
261 // Invocation count accumulators should be unsigned long to shift the
262 // overflow border. Longer-running workloads tend to create invocation
263 // counts which already overflow 32-bit counters for individual methods.
264 static void print_method_invocation_histogram() {
265   ResourceMark rm;
266   collected_invoked_methods = new GrowableArray<Method*>(1024);
267   SystemDictionary::methods_do(collect_invoked_methods);
268   collected_invoked_methods->sort(&compare_methods);
269   //
270   tty->cr();
271   tty->print_cr("Histogram Over Method Invocation Counters (cutoff = " INTX_FORMAT "):", MethodHistogramCutoff);
272   tty->cr();
273   tty->print_cr("____Count_(I+C)____Method________________________Module_________________");
274   uint64_t total        = 0,
275            int_total    = 0,
276            comp_total   = 0,
277            special_total= 0,
278            static_total = 0,
279            final_total  = 0,
280            synch_total  = 0,
281            native_total = 0,
282            access_total = 0;
283   for (int index = 0; index < collected_invoked_methods->length(); index++) {
284     // Counter values returned from getter methods are signed int.
285     // To shift the overflow border by a factor of two, we interpret
286     // them here as unsigned long. A counter can't be negative anyway.
287     Method* m = collected_invoked_methods->at(index);
288     uint64_t iic = (uint64_t)m->invocation_count();
289     uint64_t cic = (uint64_t)m->compiled_invocation_count();
290     if ((iic + cic) >= (uint64_t)MethodHistogramCutoff) m->print_invocation_count(tty);
291     int_total  += iic;
292     comp_total += cic;
293     if (m->is_final())        final_total  += iic + cic;
294     if (m->is_static())       static_total += iic + cic;
295     if (m->is_synchronized()) synch_total  += iic + cic;
296     if (m->is_native())       native_total += iic + cic;
297     if (m->is_accessor())     access_total += iic + cic;
298   }
299   tty->cr();
300   total = int_total + comp_total;
301   special_total = final_total + static_total +synch_total + native_total + access_total;
302   tty->print_cr("Invocations summary for %d methods:", collected_invoked_methods->length());
303   double total_div = (double)total;
304   tty->print_cr("\t" UINT64_FORMAT_W(12) " (100%%)  total",           total);
305   tty->print_cr("\t" UINT64_FORMAT_W(12) " (%4.1f%%) |- interpreted", int_total,     100.0 * (double)int_total    / total_div);
306   tty->print_cr("\t" UINT64_FORMAT_W(12) " (%4.1f%%) |- compiled",    comp_total,    100.0 * (double)comp_total   / total_div);
307   tty->print_cr("\t" UINT64_FORMAT_W(12) " (%4.1f%%) |- special methods (interpreted and compiled)",
308                                                                          special_total, 100.0 * (double)special_total/ total_div);
309   tty->print_cr("\t" UINT64_FORMAT_W(12) " (%4.1f%%)    |- synchronized",synch_total,   100.0 * (double)synch_total  / total_div);
310   tty->print_cr("\t" UINT64_FORMAT_W(12) " (%4.1f%%)    |- final",       final_total,   100.0 * (double)final_total  / total_div);
311   tty->print_cr("\t" UINT64_FORMAT_W(12) " (%4.1f%%)    |- static",      static_total,  100.0 * (double)static_total / total_div);
312   tty->print_cr("\t" UINT64_FORMAT_W(12) " (%4.1f%%)    |- native",      native_total,  100.0 * (double)native_total / total_div);
313   tty->print_cr("\t" UINT64_FORMAT_W(12) " (%4.1f%%)    |- accessor",    access_total,  100.0 * (double)access_total / total_div);
314   tty->cr();
315   SharedRuntime::print_call_statistics_on(tty);






316 }
317 
318 #else
319 
320 static void print_method_invocation_histogram() {}

321 
322 #endif // PRODUCT
323 
324 
325 // General statistics printing (profiling ...)
326 void print_statistics() {
327   if (ReplayTraining && PrintTrainingInfo) {
328     TrainingData::print_archived_training_data_on(tty);
329   }
330   if (CITime) {
331     CompileBroker::print_times();
332   }
333 
334 #ifdef COMPILER1
335   if ((PrintC1Statistics || LogVMOutput || LogCompilation) && UseCompiler) {
336     FlagSetting fs(DisplayVMOutput, DisplayVMOutput && PrintC1Statistics);
337     Runtime1::print_statistics_on(tty);
338     SharedRuntime::print_statistics();
339   }
340 #endif /* COMPILER1 */
341 
342 #ifdef COMPILER2
343   if ((PrintOptoStatistics || LogVMOutput || LogCompilation) && UseCompiler) {
344     FlagSetting fs(DisplayVMOutput, DisplayVMOutput && PrintOptoStatistics);
345     Compile::print_statistics();
346     Deoptimization::print_statistics();
347 #ifndef COMPILER1
348     SharedRuntime::print_statistics();
349 #endif //COMPILER1
350   }
351 
352   if (PrintLockStatistics || PrintPreciseRTMLockingStatistics) {
353     OptoRuntime::print_named_counters();
354   }
355 #ifdef ASSERT
356   if (CollectIndexSetStatistics) {
357     IndexSet::print_statistics();
358   }
359 #endif // ASSERT
360 #else // COMPILER2
361 #if INCLUDE_JVMCI
362 #ifndef COMPILER1
363   if ((TraceDeoptimization || LogVMOutput || LogCompilation) && UseCompiler) {
364     FlagSetting fs(DisplayVMOutput, DisplayVMOutput && TraceDeoptimization);
365     Deoptimization::print_statistics();
366     SharedRuntime::print_statistics();
367   }
368 #endif // COMPILER1
369 #endif // INCLUDE_JVMCI
370 #endif // COMPILER2
371 
372   if (PrintNMethodStatistics) {
373     nmethod::print_statistics();
374   }
375   if (CountCompiledCalls) {
376     print_method_invocation_histogram();
377   }
378 
379   print_method_profiling_data();
380 
381   if (TimeOopMap) {
382     GenerateOopMap::print_time();
383   }
384   if (PrintSymbolTableSizeHistogram) {
385     SymbolTable::print_histogram();
386   }
387   if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
388     BytecodeCounter::print();
389   }
390   if (PrintBytecodePairHistogram) {
391     BytecodePairHistogram::print();
392   }
393 
394   if (PrintCodeCache) {
395     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
396     CodeCache::print();
397   }
398 
399   // CodeHeap State Analytics.
400   if (PrintCodeHeapAnalytics) {
401     CompileBroker::print_heapinfo(nullptr, "all", 4096); // details
402   }
403 
404   LogStreamHandle(Debug, codecache, nmethod) log;
405   if (log.is_enabled()) {
406     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
407     CodeCache::print_nmethods_on(&log);
408   }
409 
410 #ifndef PRODUCT
411   if (PrintCodeCache2) {
412     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
413     CodeCache::print_internals();
414   }
415 #endif
416 
417   if (VerifyOops && Verbose) {
418     tty->print_cr("+VerifyOops count: %d", StubRoutines::verify_oop_count());
419   }
420 
421   print_bytecode_count();
422 
423   if (PrintSystemDictionaryAtExit) {
424     ResourceMark rm;
425     MutexLocker mcld(ClassLoaderDataGraph_lock);
426     SystemDictionary::print();
427   }
428 
429   if (PrintClassLoaderDataGraphAtExit) {
430     ResourceMark rm;
431     MutexLocker mcld(ClassLoaderDataGraph_lock);
432     ClassLoaderDataGraph::print();
433   }
434 
435   // Native memory tracking data
436   if (PrintNMTStatistics) {
437     MemTracker::final_report(tty);
438   }
439 
440   if (PrintMetaspaceStatisticsAtExit) {
441     MetaspaceUtils::print_basic_report(tty, 0);
442   }
443 
444   if (CompilerOracle::should_print_final_memstat_report()) {
445     CompilationMemoryStatistic::print_all_by_size(tty, false, 0);
446   }
447 
448   ThreadsSMRSupport::log_statistics();
449 
450   log_vm_init_stats();
451 }
452 
453 // Note: before_exit() can be executed only once, if more than one threads
454 //       are trying to shutdown the VM at the same time, only one thread
455 //       can run before_exit() and all other threads must wait.
456 void before_exit(JavaThread* thread, bool halt) {
457   #define BEFORE_EXIT_NOT_RUN 0
458   #define BEFORE_EXIT_RUNNING 1
459   #define BEFORE_EXIT_DONE    2
460   static jint volatile _before_exit_status = BEFORE_EXIT_NOT_RUN;
461 
462   // Note: don't use a Mutex to guard the entire before_exit(), as
463   // JVMTI post_thread_end_event and post_vm_death_event will run native code.
464   // A CAS or OSMutex would work just fine but then we need to manipulate
465   // thread state for Safepoint. Here we use Monitor wait() and notify_all()
466   // for synchronization.
467   { MonitorLocker ml(BeforeExit_lock);
468     switch (_before_exit_status) {
469     case BEFORE_EXIT_NOT_RUN:
470       _before_exit_status = BEFORE_EXIT_RUNNING;
471       break;
472     case BEFORE_EXIT_RUNNING:
473       while (_before_exit_status == BEFORE_EXIT_RUNNING) {
474         ml.wait();
475       }
476       assert(_before_exit_status == BEFORE_EXIT_DONE, "invalid state");
477       return;
478     case BEFORE_EXIT_DONE:
479       // need block to avoid SS compiler bug
480       {
481         return;
482       }
483     }
484   }
485 
486   // At this point only one thread is executing this logic. Any other threads
487   // attempting to invoke before_exit() will wait above and return early once
488   // this thread finishes before_exit().
489 
490   // Do not add any additional shutdown logic between the above mutex logic and
491   // leak sanitizer logic below. Any additional shutdown code which performs some
492   // cleanup should be added after the leak sanitizer logic below.
493 
494 #ifdef LEAK_SANITIZER
495   // If we are built with LSan, we need to perform leak checking. If we are
496   // terminating normally, not halting and no VM error, we perform a normal
497   // leak check which terminates if leaks are found. If we are not terminating
498   // normally, halting or VM error, we perform a recoverable leak check which
499   // prints leaks but will not terminate.
500   if (!halt && !VMError::is_error_reported()) {
501     LSAN_DO_LEAK_CHECK();
502   } else {
503     // Ignore the return value.
504     static_cast<void>(LSAN_DO_RECOVERABLE_LEAK_CHECK());
505   }
506 #endif
507 
508   MethodProfiler::process_method_hotness();
509 
510 #if INCLUDE_CDS
511   ClassListWriter::write_resolved_constants();
512   ClassListWriter::write_reflection_data();
513   ClassListWriter::write_loader_negative_lookup_cache();
514   // Dynamic CDS dumping must happen whilst we can still reliably
515   // run Java code.
516   if (CDSConfig::is_dumping_preimage_static_archive()) {
517     // Creating the hotspot.cds.preimage file
518     MetaspaceShared::preload_and_dump();
519   } else {
520     DynamicArchive::dump_at_exit(thread, ArchiveClassesAtExit);
521   }
522   assert(!thread->has_pending_exception(), "must be");
523 #endif
524 

525   // Actual shutdown logic begins here.
526 
527 #if INCLUDE_JVMCI
528   if (EnableJVMCI) {
529     JVMCI::shutdown(thread);
530   }
531 #endif
532 
533   SCCache::close(); // Write final data and close archive
534 
535   // Hang forever on exit if we're reporting an error.
536   if (ShowMessageBoxOnError && VMError::is_error_reported()) {
537     os::infinite_sleep();
538   }
539 
540   EventThreadEnd event;
541   if (event.should_commit()) {
542     event.set_thread(JFR_JVM_THREAD_ID(thread));
543     event.commit();
544   }
545 
546   JFR_ONLY(Jfr::on_vm_shutdown(false, halt);)
547 
548   // Stop the WatcherThread. We do this before disenrolling various
549   // PeriodicTasks to reduce the likelihood of races.
550   WatcherThread::stop();
551 
552   // shut down the StatSampler task
553   StatSampler::disengage();
554   StatSampler::destroy();
555 
556   NativeHeapTrimmer::cleanup();
557 
558   // Stop concurrent GC threads
559   Universe::heap()->stop();
560 
561   // Print GC/heap related information.
562   Log(gc, heap, exit) log;
563   if (log.is_info()) {
564     ResourceMark rm;
565     LogStream ls_info(log.info());
566     Universe::print_on(&ls_info);
567     if (log.is_trace()) {
568       LogStream ls_trace(log.trace());
569       MutexLocker mcld(ClassLoaderDataGraph_lock);
570       ClassLoaderDataGraph::print_on(&ls_trace);
571     }
572   }
573 
574   if (PrintBytecodeHistogram) {
575     BytecodeHistogram::print(PrintBytecodeHistogramCutoff);
576   }
577 
578 #ifdef LINUX
579   if (DumpPerfMapAtExit) {
580     CodeCache::write_perf_map();
581   }
582 #endif
583 
584   if (JvmtiExport::should_post_thread_life()) {
585     JvmtiExport::post_thread_end(thread);
586   }
587 
588   // Always call even when there are not JVMTI environments yet, since environments
589   // may be attached late and JVMTI must track phases of VM execution
590   JvmtiExport::post_vm_death();
591   JvmtiAgentList::unload_agents();
592 
593   // Terminate the signal thread
594   // Note: we don't wait until it actually dies.
595   os::terminate_signal_thread();
596 
597   if (VerifyTrainingData) {
598     EXCEPTION_MARK;
599     CompilationPolicy::replay_training_at_init(true, THREAD); // implies TrainingData::verify()
600   }
601 
602   print_statistics();
603   Universe::heap()->print_tracing_info();
604 
605   { MutexLocker ml(BeforeExit_lock);
606     _before_exit_status = BEFORE_EXIT_DONE;
607     BeforeExit_lock->notify_all();
608   }
609 
610   if (VerifyStringTableAtExit) {
611     size_t fail_cnt = StringTable::verify_and_compare_entries();
612     if (fail_cnt != 0) {
613       tty->print_cr("ERROR: fail_cnt=" SIZE_FORMAT, fail_cnt);
614       guarantee(fail_cnt == 0, "unexpected StringTable verification failures");
615     }
616   }
617 
618   #undef BEFORE_EXIT_NOT_RUN
619   #undef BEFORE_EXIT_RUNNING
620   #undef BEFORE_EXIT_DONE
621 }
622 
623 void vm_exit(int code) {
624   Thread* thread =
625       ThreadLocalStorage::is_initialized() ? Thread::current_or_null() : nullptr;
626   if (thread == nullptr) {
627     // very early initialization failure -- just exit
628     vm_direct_exit(code);
629   }
630 
631   // We'd like to add an entry to the XML log to show that the VM is
632   // terminating, but we can't safely do that here. The logic to make
633   // XML termination logging safe is tied to the termination of the
634   // VMThread, and it doesn't terminate on this exit path. See 8222534.
635 
636   if (VMThread::vm_thread() != nullptr) {
637     if (thread->is_Java_thread()) {
638       // We must be "in_vm" for the code below to work correctly.
639       // Historically there must have been some exit path for which
640       // that was not the case and so we set it explicitly - even
641       // though we no longer know what that path may be.
642       JavaThread::cast(thread)->set_thread_state(_thread_in_vm);
643     }
644 
645     // Fire off a VM_Exit operation to bring VM to a safepoint and exit
646     VM_Exit op(code);
647 
648     // 4945125 The vm thread comes to a safepoint during exit.
649     // GC vm_operations can get caught at the safepoint, and the
650     // heap is unparseable if they are caught. Grab the Heap_lock
651     // to prevent this. The GC vm_operations will not be able to
652     // queue until after we release it, but we never do that as we
653     // are terminating the VM process.
654     MutexLocker ml(Heap_lock);
655 
656     VMThread::execute(&op);
657     // should never reach here; but in case something wrong with VM Thread.
658     vm_direct_exit(code);
659   } else {
660     // VM thread is gone, just exit
661     vm_direct_exit(code);
662   }
663   ShouldNotReachHere();
664 }
665 
666 void notify_vm_shutdown() {
667   // For now, just a dtrace probe.
668   HOTSPOT_VM_SHUTDOWN();
669 }
670 
671 void vm_direct_exit(int code) {
672   notify_vm_shutdown();
673   os::wait_for_keypress_at_exit();
674   os::exit(code);
675 }
676 
677 void vm_direct_exit(int code, const char* message) {
678   if (message != nullptr) {
679     tty->print_cr("%s", message);
680   }
681   vm_direct_exit(code);
682 }
683 
684 static void vm_perform_shutdown_actions() {
685   if (is_init_completed()) {
686     Thread* thread = Thread::current_or_null();
687     if (thread != nullptr && thread->is_Java_thread()) {
688       // We are leaving the VM, set state to native (in case any OS exit
689       // handlers call back to the VM)
690       JavaThread* jt = JavaThread::cast(thread);
691       // Must always be walkable or have no last_Java_frame when in
692       // thread_in_native
693       jt->frame_anchor()->make_walkable();
694       jt->set_thread_state(_thread_in_native);
695     }
696   }
697   notify_vm_shutdown();
698 }
699 
700 void vm_shutdown()
701 {
702   vm_perform_shutdown_actions();
703   os::wait_for_keypress_at_exit();
704   os::shutdown();
705 }
706 
707 void vm_abort(bool dump_core) {
708   vm_perform_shutdown_actions();
709   os::wait_for_keypress_at_exit();
710 
711   // Flush stdout and stderr before abort.
712   fflush(stdout);
713   fflush(stderr);
714 
715   os::abort(dump_core);
716   ShouldNotReachHere();
717 }
718 
719 static void vm_notify_during_cds_dumping(const char* error, const char* message) {
720   if (error != nullptr) {
721     tty->print_cr("Error occurred during CDS dumping");
722     tty->print("%s", error);
723     if (message != nullptr) {
724       tty->print_cr(": %s", message);
725     }
726     else {
727       tty->cr();
728     }
729   }
730 }
731 
732 void vm_exit_during_cds_dumping(const char* error, const char* message) {
733   vm_notify_during_cds_dumping(error, message);
734 
735   // Failure during CDS dumping, we don't want to dump core
736   vm_abort(false);
737 }
738 
739 static void vm_notify_during_shutdown(const char* error, const char* message) {
740   if (error != nullptr) {
741     tty->print_cr("Error occurred during initialization of VM");
742     tty->print("%s", error);
743     if (message != nullptr) {
744       tty->print_cr(": %s", message);
745     }
746     else {
747       tty->cr();
748     }
749   }
750   if (ShowMessageBoxOnError && WizardMode) {
751     fatal("Error occurred during initialization of VM");
752   }
753 }
754 
755 void vm_exit_during_initialization() {
756   vm_notify_during_shutdown(nullptr, nullptr);
757 
758   // Failure during initialization, we don't want to dump core
759   vm_abort(false);
760 }
761 
762 void vm_exit_during_initialization(Handle exception) {
763   tty->print_cr("Error occurred during initialization of VM");
764   // If there are exceptions on this thread it must be cleared
765   // first and here. Any future calls to EXCEPTION_MARK requires
766   // that no pending exceptions exist.
767   JavaThread* THREAD = JavaThread::current(); // can't be null
768   if (HAS_PENDING_EXCEPTION) {
769     CLEAR_PENDING_EXCEPTION;
770   }
771   java_lang_Throwable::print_stack_trace(exception, tty);
772   tty->cr();
773   vm_notify_during_shutdown(nullptr, nullptr);
774 
775   // Failure during initialization, we don't want to dump core
776   vm_abort(false);
777 }
778 
779 void vm_exit_during_initialization(Symbol* ex, const char* message) {
780   ResourceMark rm;
781   vm_notify_during_shutdown(ex->as_C_string(), message);
782 
783   // Failure during initialization, we don't want to dump core
784   vm_abort(false);
785 }
786 
787 void vm_exit_during_initialization(const char* error, const char* message) {
788   vm_notify_during_shutdown(error, message);
789 
790   // Failure during initialization, we don't want to dump core
791   vm_abort(false);
792 }
793 
794 void vm_shutdown_during_initialization(const char* error, const char* message) {
795   vm_notify_during_shutdown(error, message);
796   vm_shutdown();
797 }
798 
799 JDK_Version JDK_Version::_current;
800 const char* JDK_Version::_java_version;
801 const char* JDK_Version::_runtime_name;
802 const char* JDK_Version::_runtime_version;
803 const char* JDK_Version::_runtime_vendor_version;
804 const char* JDK_Version::_runtime_vendor_vm_bug_url;
805 
806 void JDK_Version::initialize() {
807   assert(!_current.is_valid(), "Don't initialize twice");
808 
809   int major = VM_Version::vm_major_version();
810   int minor = VM_Version::vm_minor_version();
811   int security = VM_Version::vm_security_version();
812   int build = VM_Version::vm_build_number();
813   int patch = VM_Version::vm_patch_version();
814   _current = JDK_Version(major, minor, security, patch, build);
815 }
816 
817 void JDK_Version_init() {
818   JDK_Version::initialize();
819 }
820 
821 static int64_t encode_jdk_version(const JDK_Version& v) {
822   return
823     ((int64_t)v.major_version()          << (BitsPerByte * 4)) |
824     ((int64_t)v.minor_version()          << (BitsPerByte * 3)) |
825     ((int64_t)v.security_version()       << (BitsPerByte * 2)) |
826     ((int64_t)v.patch_version()          << (BitsPerByte * 1)) |
827     ((int64_t)v.build_number()           << (BitsPerByte * 0));
828 }
829 
830 int JDK_Version::compare(const JDK_Version& other) const {
831   assert(is_valid() && other.is_valid(), "Invalid version (uninitialized?)");
832   uint64_t e = encode_jdk_version(*this);
833   uint64_t o = encode_jdk_version(other);
834   return (e > o) ? 1 : ((e == o) ? 0 : -1);
835 }
836 
837 /* See JEP 223 */
838 void JDK_Version::to_string(char* buffer, size_t buflen) const {
839   assert(buffer && buflen > 0, "call with useful buffer");
840   size_t index = 0;
841 
842   if (!is_valid()) {
843     jio_snprintf(buffer, buflen, "%s", "(uninitialized)");
844   } else {
845     int rc = jio_snprintf(
846         &buffer[index], buflen - index, "%d.%d", _major, _minor);
847     if (rc == -1) return;
848     index += rc;
849     if (_patch > 0) {
850       rc = jio_snprintf(&buffer[index], buflen - index, ".%d.%d", _security, _patch);
851       if (rc == -1) return;
852       index += rc;
853     } else if (_security > 0) {
854       rc = jio_snprintf(&buffer[index], buflen - index, ".%d", _security);
855       if (rc == -1) return;
856       index += rc;
857     }
858     if (_build > 0) {
859       rc = jio_snprintf(&buffer[index], buflen - index, "+%d", _build);
860       if (rc == -1) return;
861       index += rc;
862     }
863   }
864 }
--- EOF ---