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