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