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