1 /*
2 * Copyright (c) 1997, 2026, 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 "cds/aotMetaspace.hpp"
26 #include "cds/cdsConfig.hpp"
27 #include "cds/dynamicArchive.hpp"
28 #include "cds/heapShared.inline.hpp"
29 #include "classfile/classLoader.hpp"
30 #include "classfile/classLoaderDataGraph.hpp"
31 #include "classfile/classLoaderDataShared.hpp"
32 #include "classfile/javaClasses.hpp"
33 #include "classfile/stringTable.hpp"
34 #include "classfile/symbolTable.hpp"
35 #include "classfile/systemDictionary.hpp"
36 #include "classfile/vmClasses.hpp"
37 #include "classfile/vmSymbols.hpp"
38 #include "code/codeBehaviours.hpp"
39 #include "code/codeCache.hpp"
40 #include "compiler/oopMap.hpp"
41 #include "gc/shared/collectedHeap.inline.hpp"
42 #include "gc/shared/gcArguments.hpp"
43 #include "gc/shared/gcConfig.hpp"
44 #include "gc/shared/gcLogPrecious.hpp"
45 #include "gc/shared/gcTraceTime.inline.hpp"
46 #include "gc/shared/oopStorageSet.hpp"
47 #include "gc/shared/plab.hpp"
48 #include "gc/shared/stringdedup/stringDedup.hpp"
49 #include "gc/shared/tlab_globals.hpp"
50 #include "logging/log.hpp"
51 #include "logging/logStream.hpp"
52 #include "memory/memoryReserver.hpp"
53 #include "memory/metadataFactory.hpp"
54 #include "memory/metaspaceClosure.hpp"
55 #include "memory/metaspaceCounters.hpp"
56 #include "memory/metaspaceUtils.hpp"
57 #include "memory/oopFactory.hpp"
58 #include "memory/resourceArea.hpp"
59 #include "memory/universe.hpp"
60 #include "oops/compressedOops.hpp"
61 #include "oops/instanceKlass.hpp"
62 #include "oops/instanceMirrorKlass.hpp"
63 #include "oops/jmethodIDTable.hpp"
64 #include "oops/klass.inline.hpp"
65 #include "oops/objArrayOop.inline.hpp"
66 #include "oops/objLayout.hpp"
67 #include "oops/oop.inline.hpp"
68 #include "oops/oopCast.inline.hpp"
69 #include "oops/oopHandle.inline.hpp"
70 #include "oops/refArrayKlass.hpp"
71 #include "oops/typeArrayKlass.hpp"
72 #include "prims/resolvedMethodTable.hpp"
73 #include "runtime/arguments.hpp"
74 #include "runtime/atomicAccess.hpp"
75 #include "runtime/cpuTimeCounters.hpp"
76 #include "runtime/flags/jvmFlagLimit.hpp"
77 #include "runtime/handles.inline.hpp"
78 #include "runtime/init.hpp"
79 #include "runtime/java.hpp"
80 #include "runtime/javaThread.hpp"
81 #include "runtime/jniHandles.hpp"
82 #include "runtime/threads.hpp"
83 #include "runtime/timerTrace.hpp"
84 #include "sanitizers/leak.hpp"
85 #include "services/cpuTimeUsage.hpp"
86 #include "services/memoryService.hpp"
87 #include "utilities/align.hpp"
88 #include "utilities/autoRestore.hpp"
89 #include "utilities/debug.hpp"
90 #include "utilities/formatBuffer.hpp"
91 #include "utilities/globalDefinitions.hpp"
92 #include "utilities/macros.hpp"
93 #include "utilities/ostream.hpp"
94 #include "utilities/preserveException.hpp"
95
96 // A helper class for caching a Method* when the user of the cache
97 // only cares about the latest version of the Method*. This cache safely
98 // interacts with the RedefineClasses API.
99 class LatestMethodCache {
100 // We save the InstanceKlass* and the idnum of Method* in order to get
101 // the current Method*.
102 InstanceKlass* _klass;
103 int _method_idnum;
104
105 public:
106 LatestMethodCache() { _klass = nullptr; _method_idnum = -1; }
107
108 void init(JavaThread* current, InstanceKlass* ik, const char* method,
109 Symbol* signature, bool is_static);
110 Method* get_method();
111 };
112
113 static LatestMethodCache _finalizer_register_cache; // Finalizer.register()
114 static LatestMethodCache _loader_addClass_cache; // ClassLoader.addClass()
115 static LatestMethodCache _throw_illegal_access_error_cache; // Unsafe.throwIllegalAccessError()
116 static LatestMethodCache _throw_no_such_method_error_cache; // Unsafe.throwNoSuchMethodError()
117 static LatestMethodCache _do_stack_walk_cache; // AbstractStackWalker.doStackWalk()
118 static LatestMethodCache _is_substitutable_cache; // ValueObjectMethods.isSubstitutable()
119 static LatestMethodCache _value_object_hash_code_cache; // ValueObjectMethods.valueObjectHashCode()
120
121 // Known objects
122 TypeArrayKlass* Universe::_typeArrayKlasses[T_LONG+1] = { nullptr /*, nullptr...*/ };
123 ObjArrayKlass* Universe::_objectArrayKlass = nullptr;
124 Klass* Universe::_fillerArrayKlass = nullptr;
125 OopHandle Universe::_basic_type_mirrors[T_VOID+1];
126 #if INCLUDE_CDS_JAVA_HEAP
127 int Universe::_archived_basic_type_mirror_indices[T_VOID+1];
128 #endif
129
130 OopHandle Universe::_main_thread_group;
131 OopHandle Universe::_system_thread_group;
132 OopHandle Universe::_the_empty_class_array;
133 OopHandle Universe::_the_null_string;
134 OopHandle Universe::_the_min_jint_string;
135
136 OopHandle Universe::_the_null_sentinel;
137
138 // _out_of_memory_errors is an objArray
139 enum OutOfMemoryInstance { _oom_java_heap,
140 _oom_c_heap,
141 _oom_metaspace,
142 _oom_class_metaspace,
143 _oom_array_size,
144 _oom_gc_overhead_limit,
145 _oom_realloc_objects,
146 _oom_count };
147
148 OopHandle Universe::_out_of_memory_errors;
149 OopHandle Universe:: _class_init_stack_overflow_error;
150 OopHandle Universe::_delayed_stack_overflow_error_message;
151 OopHandle Universe::_preallocated_out_of_memory_error_array;
152 volatile jint Universe::_preallocated_out_of_memory_error_avail_count = 0;
153
154 // Message details for OOME objects, preallocate these objects since they could be
155 // used when throwing OOME, we should try to avoid further allocation in such case
156 OopHandle Universe::_msg_metaspace;
157 OopHandle Universe::_msg_class_metaspace;
158
159 OopHandle Universe::_reference_pending_list;
160
161 Array<Klass*>* Universe::_the_array_interfaces_array = nullptr;
162
163 long Universe::verify_flags = Universe::Verify_All;
164
165 Array<int>* Universe::_the_empty_int_array = nullptr;
166 Array<u2>* Universe::_the_empty_short_array = nullptr;
167 Array<Klass*>* Universe::_the_empty_klass_array = nullptr;
168 Array<InstanceKlass*>* Universe::_the_empty_instance_klass_array = nullptr;
169 Array<Method*>* Universe::_the_empty_method_array = nullptr;
170
171 uintx Universe::_the_array_interfaces_bitmap = 0;
172 uintx Universe::_the_empty_klass_bitmap = 0;
173
174 // These variables are guarded by FullGCALot_lock.
175 DEBUG_ONLY(OopHandle Universe::_fullgc_alot_dummy_array;)
176 DEBUG_ONLY(int Universe::_fullgc_alot_dummy_next = 0;)
177
178 // Heap
179 int Universe::_verify_count = 0;
180
181 // Oop verification (see MacroAssembler::verify_oop)
182 uintptr_t Universe::_verify_oop_mask = 0;
183 uintptr_t Universe::_verify_oop_bits = (uintptr_t) -1;
184
185 int Universe::_base_vtable_size = 0;
186 bool Universe::_bootstrapping = false;
187 bool Universe::_module_initialized = false;
188 bool Universe::_fully_initialized = false;
189
190 OopStorage* Universe::_vm_weak = nullptr;
191 OopStorage* Universe::_vm_global = nullptr;
192
193 CollectedHeap* Universe::_collectedHeap = nullptr;
194
195 // These are the exceptions that are always created and are guatanteed to exist.
196 // If possible, they can be stored as CDS archived objects to speed up AOT code.
197 class BuiltinException {
198 OopHandle _instance;
199 CDS_JAVA_HEAP_ONLY(int _archived_root_index;)
200
201 public:
202 BuiltinException() : _instance() {
203 CDS_JAVA_HEAP_ONLY(_archived_root_index = 0);
204 }
205
206 void init_if_empty(Symbol* symbol, TRAPS) {
207 if (_instance.is_empty()) {
208 Klass* k = SystemDictionary::resolve_or_fail(symbol, true, CHECK);
209 oop obj = InstanceKlass::cast(k)->allocate_instance(CHECK);
210 _instance = OopHandle(Universe::vm_global(), obj);
211 }
212 }
213
214 oop instance() {
215 return _instance.resolve();
216 }
217
218 #if INCLUDE_CDS_JAVA_HEAP
219 void store_in_cds() {
220 _archived_root_index = HeapShared::archive_exception_instance(instance());
221 }
222
223 void load_from_cds() {
224 if (_archived_root_index >= 0) {
225 oop obj = HeapShared::get_root(_archived_root_index);
226 assert(obj != nullptr, "must be");
227 _instance = OopHandle(Universe::vm_global(), obj);
228 }
229 }
230
231 void serialize(SerializeClosure *f) {
232 f->do_int(&_archived_root_index);
233 }
234 #endif
235 };
236
237 static BuiltinException _null_ptr_exception;
238 static BuiltinException _arithmetic_exception;
239 static BuiltinException _internal_error;
240 static BuiltinException _array_index_out_of_bounds_exception;
241 static BuiltinException _array_store_exception;
242 static BuiltinException _class_cast_exception;
243 static BuiltinException _preempted_exception;
244
245 objArrayOop Universe::the_empty_class_array () {
246 return (objArrayOop)_the_empty_class_array.resolve();
247 }
248
249 oop Universe::main_thread_group() { return _main_thread_group.resolve(); }
250 void Universe::set_main_thread_group(oop group) { _main_thread_group = OopHandle(vm_global(), group); }
251
252 oop Universe::system_thread_group() { return _system_thread_group.resolve(); }
253 void Universe::set_system_thread_group(oop group) { _system_thread_group = OopHandle(vm_global(), group); }
254
255 oop Universe::the_null_string() { return _the_null_string.resolve(); }
256 oop Universe::the_min_jint_string() { return _the_min_jint_string.resolve(); }
257
258 oop Universe::null_ptr_exception_instance() { return _null_ptr_exception.instance(); }
259 oop Universe::arithmetic_exception_instance() { return _arithmetic_exception.instance(); }
260 oop Universe::internal_error_instance() { return _internal_error.instance(); }
261 oop Universe::array_index_out_of_bounds_exception_instance() { return _array_index_out_of_bounds_exception.instance(); }
262 oop Universe::array_store_exception_instance() { return _array_store_exception.instance(); }
263 oop Universe::class_cast_exception_instance() { return _class_cast_exception.instance(); }
264 oop Universe::preempted_exception_instance() { return _preempted_exception.instance(); }
265
266 oop Universe::the_null_sentinel() { return _the_null_sentinel.resolve(); }
267
268 oop Universe::int_mirror() { return check_mirror(_basic_type_mirrors[T_INT].resolve()); }
269 oop Universe::float_mirror() { return check_mirror(_basic_type_mirrors[T_FLOAT].resolve()); }
270 oop Universe::double_mirror() { return check_mirror(_basic_type_mirrors[T_DOUBLE].resolve()); }
271 oop Universe::byte_mirror() { return check_mirror(_basic_type_mirrors[T_BYTE].resolve()); }
272 oop Universe::bool_mirror() { return check_mirror(_basic_type_mirrors[T_BOOLEAN].resolve()); }
273 oop Universe::char_mirror() { return check_mirror(_basic_type_mirrors[T_CHAR].resolve()); }
274 oop Universe::long_mirror() { return check_mirror(_basic_type_mirrors[T_LONG].resolve()); }
275 oop Universe::short_mirror() { return check_mirror(_basic_type_mirrors[T_SHORT].resolve()); }
276 oop Universe::void_mirror() { return check_mirror(_basic_type_mirrors[T_VOID].resolve()); }
277
278 oop Universe::java_mirror(BasicType t) {
279 assert((uint)t < T_VOID+1, "range check");
280 assert(!is_reference_type(t), "sanity");
281 return check_mirror(_basic_type_mirrors[t].resolve());
282 }
283
284 void Universe::basic_type_classes_do(KlassClosure *closure) {
285 for (int i = T_BOOLEAN; i < T_LONG+1; i++) {
286 closure->do_klass(_typeArrayKlasses[i]);
287 }
288 // We don't do the following because it will confuse JVMTI.
289 // _fillerArrayKlass is used only by GC, which doesn't need to see
290 // this klass from basic_type_classes_do().
291 //
292 // closure->do_klass(_fillerArrayKlass);
293 }
294
295 void Universe::metaspace_pointers_do(MetaspaceClosure* it) {
296 it->push(&_fillerArrayKlass);
297 for (int i = 0; i < T_LONG+1; i++) {
298 it->push(&_typeArrayKlasses[i]);
299 }
300 it->push(&_objectArrayKlass);
301
302 it->push(&_the_empty_int_array);
303 it->push(&_the_empty_short_array);
304 it->push(&_the_empty_klass_array);
305 it->push(&_the_empty_instance_klass_array);
306 it->push(&_the_empty_method_array);
307 it->push(&_the_array_interfaces_array);
308 }
309
310 #if INCLUDE_CDS_JAVA_HEAP
311 void Universe::set_archived_basic_type_mirror_index(BasicType t, int index) {
312 assert(CDSConfig::is_dumping_heap(), "sanity");
313 assert(!is_reference_type(t), "sanity");
314 _archived_basic_type_mirror_indices[t] = index;
315 }
316
317 void Universe::archive_exception_instances() {
318 _null_ptr_exception.store_in_cds();
319 _arithmetic_exception.store_in_cds();
320 _internal_error.store_in_cds();
321 _array_index_out_of_bounds_exception.store_in_cds();
322 _array_store_exception.store_in_cds();
323 _class_cast_exception.store_in_cds();
324 _preempted_exception.store_in_cds();
325 }
326
327 void Universe::load_archived_object_instances() {
328 if (HeapShared::is_archived_heap_in_use()) {
329 for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
330 int index = _archived_basic_type_mirror_indices[i];
331 if (!is_reference_type((BasicType)i) && index >= 0) {
332 oop mirror_oop = HeapShared::get_root(index);
333 assert(mirror_oop != nullptr, "must be");
334 _basic_type_mirrors[i] = OopHandle(vm_global(), mirror_oop);
335 }
336 }
337
338 _null_ptr_exception.load_from_cds();
339 _arithmetic_exception.load_from_cds();
340 _internal_error.load_from_cds();
341 _array_index_out_of_bounds_exception.load_from_cds();
342 _array_store_exception.load_from_cds();
343 _class_cast_exception.load_from_cds();
344 _preempted_exception.load_from_cds();
345 }
346 }
347 #endif
348
349 void Universe::serialize(SerializeClosure* f) {
350
351 #if INCLUDE_CDS_JAVA_HEAP
352 for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
353 f->do_int(&_archived_basic_type_mirror_indices[i]);
354 // if f->reading(): We can't call HeapShared::get_root() yet, as the heap
355 // contents may need to be relocated. _basic_type_mirrors[i] will be
356 // updated later in Universe::load_archived_object_instances().
357 }
358 _null_ptr_exception.serialize(f);
359 _arithmetic_exception.serialize(f);
360 _internal_error.serialize(f);
361 _array_index_out_of_bounds_exception.serialize(f);
362 _array_store_exception.serialize(f);
363 _class_cast_exception.serialize(f);
364 _preempted_exception.serialize(f);
365 #endif
366
367 f->do_ptr(&_fillerArrayKlass);
368 for (int i = 0; i < T_LONG+1; i++) {
369 f->do_ptr(&_typeArrayKlasses[i]);
370 }
371
372 f->do_ptr(&_objectArrayKlass);
373 f->do_ptr(&_the_array_interfaces_array);
374 f->do_ptr(&_the_empty_int_array);
375 f->do_ptr(&_the_empty_short_array);
376 f->do_ptr(&_the_empty_method_array);
377 f->do_ptr(&_the_empty_klass_array);
378 f->do_ptr(&_the_empty_instance_klass_array);
379 }
380
381
382 void Universe::check_alignment(uintx size, uintx alignment, const char* name) {
383 if (size < alignment || size % alignment != 0) {
384 vm_exit_during_initialization(
385 err_msg("Size of %s (%zu bytes) must be aligned to %zu bytes", name, size, alignment));
386 }
387 }
388
389 static void initialize_basic_type_klass(Klass* k, TRAPS) {
390 Klass* ok = vmClasses::Object_klass();
391 #if INCLUDE_CDS
392 if (CDSConfig::is_using_archive()) {
393 ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
394 assert(k->super() == ok, "u3");
395 if (k->is_instance_klass()) {
396 InstanceKlass::cast(k)->restore_unshareable_info(loader_data, Handle(), nullptr, CHECK);
397 } else {
398 ArrayKlass::cast(k)->restore_unshareable_info(loader_data, Handle(), CHECK);
399 }
400 } else
401 #endif
402 {
403 k->initialize_supers(ok, nullptr, CHECK);
404 }
405 k->append_to_sibling_list();
406 }
407
408 void Universe::genesis(TRAPS) {
409 ResourceMark rm(THREAD);
410 HandleMark hm(THREAD);
411
412 // Explicit null checks are needed if these offsets are not smaller than the page size
413 if (UseCompactObjectHeaders) {
414 assert(oopDesc::mark_offset_in_bytes() < static_cast<intptr_t>(os::vm_page_size()),
415 "Mark offset is expected to be less than the page size");
416 } else {
417 assert(oopDesc::klass_offset_in_bytes() < static_cast<intptr_t>(os::vm_page_size()),
418 "Klass offset is expected to be less than the page size");
419 }
420 assert(arrayOopDesc::length_offset_in_bytes() < static_cast<intptr_t>(os::vm_page_size()),
421 "Array length offset is expected to be less than the page size");
422
423 { AutoModifyRestore<bool> temporarily(_bootstrapping, true);
424
425 java_lang_Class::allocate_fixup_lists();
426
427 // determine base vtable size; without that we cannot create the array klasses
428 compute_base_vtable_size();
429
430 if (!CDSConfig::is_using_archive()) {
431 // Initialization of the fillerArrayKlass must come before regular
432 // int-TypeArrayKlass so that the int-Array mirror points to the
433 // int-TypeArrayKlass.
434 _fillerArrayKlass = TypeArrayKlass::create_klass(T_INT, "[Ljdk/internal/vm/FillerElement;", CHECK);
435 for (int i = T_BOOLEAN; i < T_LONG+1; i++) {
436 _typeArrayKlasses[i] = TypeArrayKlass::create_klass((BasicType)i, CHECK);
437 }
438
439 ClassLoaderData* null_cld = ClassLoaderData::the_null_class_loader_data();
440
441 _the_array_interfaces_array = MetadataFactory::new_array<Klass*>(null_cld, 2, nullptr, CHECK);
442 _the_empty_int_array = MetadataFactory::new_array<int>(null_cld, 0, CHECK);
443 _the_empty_short_array = MetadataFactory::new_array<u2>(null_cld, 0, CHECK);
444 _the_empty_method_array = MetadataFactory::new_array<Method*>(null_cld, 0, CHECK);
445 _the_empty_klass_array = MetadataFactory::new_array<Klass*>(null_cld, 0, CHECK);
446 _the_empty_instance_klass_array = MetadataFactory::new_array<InstanceKlass*>(null_cld, 0, CHECK);
447 }
448
449 vmSymbols::initialize();
450
451 // Initialize table for matching jmethodID, before SystemDictionary.
452 JmethodIDTable::initialize();
453
454 SystemDictionary::initialize(CHECK);
455
456 // Create string constants
457 oop s = StringTable::intern("null", CHECK);
458 _the_null_string = OopHandle(vm_global(), s);
459 s = StringTable::intern("-2147483648", CHECK);
460 _the_min_jint_string = OopHandle(vm_global(), s);
461
462 #if INCLUDE_CDS
463 if (CDSConfig::is_using_archive()) {
464 // Verify shared interfaces array.
465 assert(_the_array_interfaces_array->at(0) ==
466 vmClasses::Cloneable_klass(), "u3");
467 assert(_the_array_interfaces_array->at(1) ==
468 vmClasses::Serializable_klass(), "u3");
469 } else
470 #endif
471 {
472 // Set up shared interfaces array. (Do this before supers are set up.)
473 _the_array_interfaces_array->at_put(0, vmClasses::Cloneable_klass());
474 _the_array_interfaces_array->at_put(1, vmClasses::Serializable_klass());
475 }
476
477 _the_array_interfaces_bitmap = Klass::compute_secondary_supers_bitmap(_the_array_interfaces_array);
478 _the_empty_klass_bitmap = Klass::compute_secondary_supers_bitmap(_the_empty_klass_array);
479
480 initialize_basic_type_klass(_fillerArrayKlass, CHECK);
481
482 initialize_basic_type_klass(boolArrayKlass(), CHECK);
483 initialize_basic_type_klass(charArrayKlass(), CHECK);
484 initialize_basic_type_klass(floatArrayKlass(), CHECK);
485 initialize_basic_type_klass(doubleArrayKlass(), CHECK);
486 initialize_basic_type_klass(byteArrayKlass(), CHECK);
487 initialize_basic_type_klass(shortArrayKlass(), CHECK);
488 initialize_basic_type_klass(intArrayKlass(), CHECK);
489 initialize_basic_type_klass(longArrayKlass(), CHECK);
490
491 assert(_fillerArrayKlass != intArrayKlass(),
492 "Internal filler array klass should be different to int array Klass");
493 } // end of core bootstrapping
494
495 {
496 Handle tns = java_lang_String::create_from_str("<null_sentinel>", CHECK);
497 _the_null_sentinel = OopHandle(vm_global(), tns());
498 }
499
500 // Create a handle for reference_pending_list
501 _reference_pending_list = OopHandle(vm_global(), nullptr);
502
503 // Maybe this could be lifted up now that object array can be initialized
504 // during the bootstrapping.
505
506 // OLD
507 // Initialize _objectArrayKlass after core bootstraping to make
508 // sure the super class is set up properly for _objectArrayKlass.
509 // ---
510 // NEW
511 // Since some of the old system object arrays have been converted to
512 // ordinary object arrays, _objectArrayKlass will be loaded when
513 // SystemDictionary::initialize(CHECK); is run. See the extra check
514 // for Object_klass_is_loaded in ObjArrayKlass::allocate_objArray_klass.
515 {
516 ArrayKlass* oak = vmClasses::Object_klass()->array_klass(CHECK);
517 oak->append_to_sibling_list();
518
519 // Create a RefArrayKlass (which is the default) and initialize.
520 ObjArrayKlass* rak = ObjArrayKlass::cast(oak)->klass_with_properties(ArrayProperties::Default(), THREAD);
521 _objectArrayKlass = rak;
522 }
523
524 #ifdef ASSERT
525 if (FullGCALot) {
526 // Allocate an array of dummy objects.
527 // We'd like these to be at the bottom of the old generation,
528 // so that when we free one and then collect,
529 // (almost) the whole heap moves
530 // and we find out if we actually update all the oops correctly.
531 // But we can't allocate directly in the old generation,
532 // so we allocate wherever, and hope that the first collection
533 // moves these objects to the bottom of the old generation.
534 int size = FullGCALotDummies * 2;
535
536 objArrayOop naked_array = oopFactory::new_objArray(vmClasses::Object_klass(), size, CHECK);
537 objArrayHandle dummy_array(THREAD, naked_array);
538 int i = 0;
539 while (i < size) {
540 // Allocate dummy in old generation
541 oop dummy = vmClasses::Object_klass()->allocate_instance(CHECK);
542 dummy_array->obj_at_put(i++, dummy);
543 }
544 {
545 // Only modify the global variable inside the mutex.
546 // If we had a race to here, the other dummy_array instances
547 // and their elements just get dropped on the floor, which is fine.
548 MutexLocker ml(THREAD, FullGCALot_lock, Mutex::_no_safepoint_check_flag);
549 if (_fullgc_alot_dummy_array.is_empty()) {
550 _fullgc_alot_dummy_array = OopHandle(vm_global(), dummy_array());
551 }
552 }
553 assert(i == ((objArrayOop)_fullgc_alot_dummy_array.resolve())->length(), "just checking");
554 }
555 #endif
556 }
557
558 void Universe::initialize_basic_type_mirrors(TRAPS) {
559 #if INCLUDE_CDS_JAVA_HEAP
560 if (CDSConfig::is_using_archive() &&
561 HeapShared::is_archived_heap_in_use() &&
562 _basic_type_mirrors[T_INT].resolve() != nullptr) {
563 // check that all basic type mirrors are mapped also
564 for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
565 if (!is_reference_type((BasicType)i)) {
566 oop m = _basic_type_mirrors[i].resolve();
567 assert(m != nullptr, "archived mirrors should not be null");
568 }
569 }
570 } else
571 // _basic_type_mirrors[T_INT], etc, are null if not using an archived heap
572 #endif
573 {
574 for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
575 BasicType bt = (BasicType)i;
576 if (!is_reference_type(bt)) {
577 oop m = java_lang_Class::create_basic_type_mirror(type2name(bt), bt, CHECK);
578 _basic_type_mirrors[i] = OopHandle(vm_global(), m);
579 }
580 CDS_JAVA_HEAP_ONLY(_archived_basic_type_mirror_indices[i] = -1);
581 }
582 }
583 if (CDSConfig::is_dumping_heap()) {
584 HeapShared::init_scratch_objects_for_basic_type_mirrors(CHECK);
585 }
586 }
587
588 void Universe::fixup_mirrors(TRAPS) {
589 if (CDSConfig::is_using_aot_linked_classes()) {
590 // All mirrors of preloaded classes are already restored. No need to fix up.
591 return;
592 }
593
594 // Bootstrap problem: all classes gets a mirror (java.lang.Class instance) assigned eagerly,
595 // but we cannot do that for classes created before java.lang.Class is loaded. Here we simply
596 // walk over permanent objects created so far (mostly classes) and fixup their mirrors. Note
597 // that the number of objects allocated at this point is very small.
598 assert(vmClasses::Class_klass_is_loaded(), "java.lang.Class should be loaded");
599 HandleMark hm(THREAD);
600
601 if (!CDSConfig::is_using_archive()) {
602 // Cache the start of the static fields
603 InstanceMirrorKlass::init_offset_of_static_fields();
604 }
605
606 GrowableArray <Klass*>* list = java_lang_Class::fixup_mirror_list();
607 int list_length = list->length();
608 for (int i = 0; i < list_length; i++) {
609 Klass* k = list->at(i);
610 assert(k->is_klass(), "List should only hold classes");
611 java_lang_Class::fixup_mirror(k, CATCH);
612 }
613 delete java_lang_Class::fixup_mirror_list();
614 java_lang_Class::set_fixup_mirror_list(nullptr);
615 }
616
617 #define assert_pll_locked(test) \
618 assert(Heap_lock->test(), "Reference pending list access requires lock")
619
620 #define assert_pll_ownership() assert_pll_locked(owned_by_self)
621
622 oop Universe::reference_pending_list() {
623 if (Thread::current()->is_VM_thread()) {
624 assert_pll_locked(is_locked);
625 } else {
626 assert_pll_ownership();
627 }
628 return _reference_pending_list.resolve();
629 }
630
631 void Universe::clear_reference_pending_list() {
632 assert_pll_ownership();
633 _reference_pending_list.replace(nullptr);
634 }
635
636 bool Universe::has_reference_pending_list() {
637 assert_pll_ownership();
638 return _reference_pending_list.peek() != nullptr;
639 }
640
641 oop Universe::swap_reference_pending_list(oop list) {
642 assert_pll_locked(is_locked);
643 return _reference_pending_list.xchg(list);
644 }
645
646 #undef assert_pll_locked
647 #undef assert_pll_ownership
648
649 static void reinitialize_vtables() {
650 // The vtables are initialized by starting at java.lang.Object and
651 // initializing through the subclass links, so that the super
652 // classes are always initialized first.
653 for (ClassHierarchyIterator iter(vmClasses::Object_klass()); !iter.done(); iter.next()) {
654 Klass* sub = iter.klass();
655 sub->vtable().initialize_vtable();
656 }
657
658 // This isn't added to the subclass list, so need to reinitialize vtables directly.
659 Universe::objectArrayKlass()->vtable().initialize_vtable();
660 }
661
662 static void reinitialize_itables() {
663
664 class ReinitTableClosure : public KlassClosure {
665 public:
666 void do_klass(Klass* k) {
667 if (k->is_instance_klass()) {
668 InstanceKlass::cast(k)->itable().initialize_itable();
669 }
670 }
671 };
672
673 MutexLocker mcld(ClassLoaderDataGraph_lock);
674 ReinitTableClosure cl;
675 ClassLoaderDataGraph::classes_do(&cl);
676 }
677
678 bool Universe::on_page_boundary(void* addr) {
679 return is_aligned(addr, os::vm_page_size());
680 }
681
682 // the array of preallocated errors with backtraces
683 refArrayOop Universe::preallocated_out_of_memory_errors() {
684 return oop_cast<refArrayOop>(_preallocated_out_of_memory_error_array.resolve());
685 }
686
687 refArrayOop Universe::out_of_memory_errors() { return oop_cast<refArrayOop>(_out_of_memory_errors.resolve()); }
688
689 oop Universe::out_of_memory_error_java_heap() {
690 return gen_out_of_memory_error(out_of_memory_errors()->obj_at(_oom_java_heap));
691 }
692
693 oop Universe::out_of_memory_error_java_heap_without_backtrace() {
694 return out_of_memory_errors()->obj_at(_oom_java_heap);
695 }
696
697 oop Universe::out_of_memory_error_c_heap() {
698 return gen_out_of_memory_error(out_of_memory_errors()->obj_at(_oom_c_heap));
699 }
700
701 oop Universe::out_of_memory_error_metaspace() {
702 return gen_out_of_memory_error(out_of_memory_errors()->obj_at(_oom_metaspace));
703 }
704
705 oop Universe::out_of_memory_error_class_metaspace() {
706 return gen_out_of_memory_error(out_of_memory_errors()->obj_at(_oom_class_metaspace));
707 }
708
709 oop Universe::out_of_memory_error_array_size() {
710 return gen_out_of_memory_error(out_of_memory_errors()->obj_at(_oom_array_size));
711 }
712
713 oop Universe::out_of_memory_error_gc_overhead_limit() {
714 return gen_out_of_memory_error(out_of_memory_errors()->obj_at(_oom_gc_overhead_limit));
715 }
716
717 oop Universe::out_of_memory_error_realloc_objects() {
718 return gen_out_of_memory_error(out_of_memory_errors()->obj_at(_oom_realloc_objects));
719 }
720
721 oop Universe::class_init_out_of_memory_error() { return out_of_memory_errors()->obj_at(_oom_java_heap); }
722 oop Universe::class_init_stack_overflow_error() { return _class_init_stack_overflow_error.resolve(); }
723 oop Universe::delayed_stack_overflow_error_message() { return _delayed_stack_overflow_error_message.resolve(); }
724
725
726 bool Universe::should_fill_in_stack_trace(Handle throwable) {
727 // never attempt to fill in the stack trace of preallocated errors that do not have
728 // backtrace. These errors are kept alive forever and may be "re-used" when all
729 // preallocated errors with backtrace have been consumed. Also need to avoid
730 // a potential loop which could happen if an out of memory occurs when attempting
731 // to allocate the backtrace.
732 refArrayOop preallocated_oom = out_of_memory_errors();
733 for (int i = 0; i < _oom_count; i++) {
734 if (throwable() == preallocated_oom->obj_at(i)) {
735 return false;
736 }
737 }
738 return true;
739 }
740
741
742 oop Universe::gen_out_of_memory_error(oop default_err) {
743 // generate an out of memory error:
744 // - if there is a preallocated error and stack traces are available
745 // (j.l.Throwable is initialized), then return the preallocated
746 // error with a filled in stack trace, and with the message
747 // provided by the default error.
748 // - otherwise, return the default error, without a stack trace.
749 int next;
750 if ((_preallocated_out_of_memory_error_avail_count > 0) &&
751 vmClasses::Throwable_klass()->is_initialized()) {
752 next = (int)AtomicAccess::add(&_preallocated_out_of_memory_error_avail_count, -1);
753 assert(next < (int)PreallocatedOutOfMemoryErrorCount, "avail count is corrupt");
754 } else {
755 next = -1;
756 }
757 if (next < 0) {
758 // all preallocated errors have been used.
759 // return default
760 return default_err;
761 } else {
762 JavaThread* current = JavaThread::current();
763 Handle default_err_h(current, default_err);
764 // get the error object at the slot and set set it to null so that the
765 // array isn't keeping it alive anymore.
766 Handle exc(current, preallocated_out_of_memory_errors()->obj_at(next));
767 assert(exc() != nullptr, "slot has been used already");
768 preallocated_out_of_memory_errors()->obj_at_put(next, nullptr);
769
770 // use the message from the default error
771 oop msg = java_lang_Throwable::message(default_err_h());
772 assert(msg != nullptr, "no message");
773 java_lang_Throwable::set_message(exc(), msg);
774
775 // populate the stack trace and return it.
776 java_lang_Throwable::fill_in_stack_trace_of_preallocated_backtrace(exc);
777 return exc();
778 }
779 }
780
781 bool Universe::is_out_of_memory_error_metaspace(oop ex_obj) {
782 return java_lang_Throwable::message(ex_obj) == _msg_metaspace.resolve();
783 }
784
785 bool Universe::is_out_of_memory_error_class_metaspace(oop ex_obj) {
786 return java_lang_Throwable::message(ex_obj) == _msg_class_metaspace.resolve();
787 }
788
789 // Setup preallocated OutOfMemoryError errors
790 void Universe::create_preallocated_out_of_memory_errors(TRAPS) {
791 InstanceKlass* ik = vmClasses::OutOfMemoryError_klass();
792 refArrayOop ra = oopFactory::new_refArray(ik, _oom_count, CHECK);
793 refArrayHandle oom_array(THREAD, ra);
794
795 for (int i = 0; i < _oom_count; i++) {
796 oop oom_obj = ik->allocate_instance(CHECK);
797 oom_array->obj_at_put(i, oom_obj);
798 }
799 _out_of_memory_errors = OopHandle(vm_global(), oom_array());
800
801 Handle msg = java_lang_String::create_from_str("Java heap space", CHECK);
802 java_lang_Throwable::set_message(oom_array->obj_at(_oom_java_heap), msg());
803
804 msg = java_lang_String::create_from_str("C heap space", CHECK);
805 java_lang_Throwable::set_message(oom_array->obj_at(_oom_c_heap), msg());
806
807 msg = java_lang_String::create_from_str("Metaspace", CHECK);
808 _msg_metaspace = OopHandle(vm_global(), msg());
809 java_lang_Throwable::set_message(oom_array->obj_at(_oom_metaspace), msg());
810
811 msg = java_lang_String::create_from_str("Compressed class space", CHECK);
812 _msg_class_metaspace = OopHandle(vm_global(), msg());
813 java_lang_Throwable::set_message(oom_array->obj_at(_oom_class_metaspace), msg());
814
815 msg = java_lang_String::create_from_str("Requested array size exceeds VM limit", CHECK);
816 java_lang_Throwable::set_message(oom_array->obj_at(_oom_array_size), msg());
817
818 msg = java_lang_String::create_from_str("GC overhead limit exceeded", CHECK);
819 java_lang_Throwable::set_message(oom_array->obj_at(_oom_gc_overhead_limit), msg());
820
821 msg = java_lang_String::create_from_str("Java heap space: failed reallocation of scalar replaced objects", CHECK);
822 java_lang_Throwable::set_message(oom_array->obj_at(_oom_realloc_objects), msg());
823
824 // Setup the array of errors that have preallocated backtrace
825 int len = (StackTraceInThrowable) ? (int)PreallocatedOutOfMemoryErrorCount : 0;
826 refArrayOop instance = oopFactory::new_refArray(ik, len, CHECK);
827 _preallocated_out_of_memory_error_array = OopHandle(vm_global(), instance);
828 refArrayHandle preallocated_oom_array(THREAD, instance);
829
830 for (int i=0; i<len; i++) {
831 oop err = ik->allocate_instance(CHECK);
832 Handle err_h(THREAD, err);
833 java_lang_Throwable::allocate_backtrace(err_h, CHECK);
834 preallocated_oom_array->obj_at_put(i, err_h());
835 }
836 _preallocated_out_of_memory_error_avail_count = (jint)len;
837 }
838
839 intptr_t Universe::_non_oop_bits = 0;
840
841 void* Universe::non_oop_word() {
842 // Neither the high bits nor the low bits of this value is allowed
843 // to look like (respectively) the high or low bits of a real oop.
844 //
845 // High and low are CPU-specific notions, but low always includes
846 // the low-order bit. Since oops are always aligned at least mod 4,
847 // setting the low-order bit will ensure that the low half of the
848 // word will never look like that of a real oop.
849 //
850 // Using the OS-supplied non-memory-address word (usually 0 or -1)
851 // will take care of the high bits, however many there are.
852
853 if (_non_oop_bits == 0) {
854 _non_oop_bits = (intptr_t)os::non_memory_address_word() | 1;
855 }
856
857 return (void*)_non_oop_bits;
858 }
859
860 bool Universe::contains_non_oop_word(void* p) {
861 return *(void**)p == non_oop_word();
862 }
863
864 static void initialize_global_behaviours() {
865 DefaultICProtectionBehaviour* protection_behavior = new DefaultICProtectionBehaviour();
866 // Ignore leak of DefaultICProtectionBehaviour. It is overriden by some GC implementations and the
867 // pointer is leaked once.
868 LSAN_IGNORE_OBJECT(protection_behavior);
869 CompiledICProtectionBehaviour::set_current(protection_behavior);
870 }
871
872 jint universe_init() {
873 assert(!Universe::_fully_initialized, "called after initialize_vtables");
874 guarantee(1 << LogHeapWordSize == sizeof(HeapWord),
875 "LogHeapWordSize is incorrect.");
876 guarantee(sizeof(oop) >= sizeof(HeapWord), "HeapWord larger than oop?");
877 guarantee(sizeof(oop) % sizeof(HeapWord) == 0,
878 "oop size is not not a multiple of HeapWord size");
879
880 TraceTime timer("Genesis", TRACETIME_LOG(Info, startuptime));
881
882 initialize_global_behaviours();
883
884 GCLogPrecious::initialize();
885
886 // Initialize CPUTimeCounters object, which must be done before creation of the heap.
887 CPUTimeCounters::initialize();
888
889 ObjLayout::initialize();
890
891 #ifdef _LP64
892 AOTMetaspace::adjust_heap_sizes_for_dumping();
893 #endif // _LP64
894
895 GCConfig::arguments()->initialize_heap_sizes();
896
897 jint status = Universe::initialize_heap();
898 if (status != JNI_OK) {
899 return status;
900 }
901
902 Universe::initialize_tlab();
903
904 Metaspace::global_initialize();
905
906 // Initialize performance counters for metaspaces
907 MetaspaceCounters::initialize_performance_counters();
908
909 // Checks 'AfterMemoryInit' constraints.
910 if (!JVMFlagLimit::check_all_constraints(JVMFlagConstraintPhase::AfterMemoryInit)) {
911 return JNI_EINVAL;
912 }
913
914 // Add main_thread to threads list to finish barrier setup with
915 // on_thread_attach. Should be before starting to build Java objects in
916 // the AOT heap loader, which invokes barriers.
917 {
918 JavaThread* main_thread = JavaThread::current();
919 MutexLocker mu(Threads_lock);
920 Threads::add(main_thread);
921 }
922
923 HeapShared::initialize_writing_mode();
924
925 // Create the string table before the AOT object archive is loaded,
926 // as it might need to access the string table.
927 StringTable::create_table();
928
929 #if INCLUDE_CDS
930 if (CDSConfig::is_using_archive()) {
931 // Read the data structures supporting the shared spaces (shared
932 // system dictionary, symbol table, etc.)
933 AOTMetaspace::initialize_shared_spaces();
934 }
935 #endif
936
937 ClassLoaderData::init_null_class_loader_data();
938
939 #if INCLUDE_CDS
940 #if INCLUDE_CDS_JAVA_HEAP
941 if (CDSConfig::is_using_full_module_graph()) {
942 ClassLoaderDataShared::restore_archived_entries_for_null_class_loader_data();
943 }
944 #endif // INCLUDE_CDS_JAVA_HEAP
945 if (CDSConfig::is_dumping_archive()) {
946 CDSConfig::prepare_for_dumping();
947 }
948 #endif
949
950 SymbolTable::create_table();
951
952 if (strlen(VerifySubSet) > 0) {
953 Universe::initialize_verify_flags();
954 }
955
956 ResolvedMethodTable::create_table();
957
958 return JNI_OK;
959 }
960
961 jint Universe::initialize_heap() {
962 assert(_collectedHeap == nullptr, "Heap already created");
963 _collectedHeap = GCConfig::arguments()->create_heap();
964
965 log_info(gc)("Using %s", _collectedHeap->name());
966 return _collectedHeap->initialize();
967 }
968
969 void Universe::initialize_tlab() {
970 ThreadLocalAllocBuffer::set_max_size(Universe::heap()->max_tlab_size());
971 PLAB::startup_initialization();
972 if (UseTLAB) {
973 ThreadLocalAllocBuffer::startup_initialization();
974 }
975 }
976
977 ReservedHeapSpace Universe::reserve_heap(size_t heap_size, size_t alignment, size_t desired_page_size) {
978
979 assert(alignment <= Arguments::conservative_max_heap_alignment(),
980 "actual alignment %zu must be within maximum heap alignment %zu",
981 alignment, Arguments::conservative_max_heap_alignment());
982 assert(is_aligned(heap_size, alignment), "precondition");
983
984 size_t total_reserved = heap_size;
985 assert(!UseCompressedOops || (total_reserved <= (OopEncodingHeapMax - os::vm_page_size())),
986 "heap size is too big for compressed oops");
987
988 size_t page_size;
989 if (desired_page_size == 0) {
990 if (UseLargePages) {
991 page_size = os::large_page_size();
992 } else {
993 page_size = os::vm_page_size();
994 }
995 } else {
996 // Parallel is the only collector that might opt out of using large pages
997 // for the heap.
998 assert(UseParallelGC , "only Parallel");
999 // Use caller provided value.
1000 page_size = desired_page_size;
1001 }
1002 assert(is_aligned(heap_size, page_size), "inv");
1003 // Now create the space.
1004 ReservedHeapSpace rhs = HeapReserver::reserve(total_reserved, alignment, page_size, AllocateHeapAt);
1005
1006 if (!rhs.is_reserved()) {
1007 vm_exit_during_initialization(
1008 err_msg("Could not reserve enough space for %zu KB object heap",
1009 total_reserved/K));
1010 }
1011
1012 assert(total_reserved == rhs.size(), "must be exactly of required size");
1013 assert(is_aligned(rhs.base(),alignment),"must be exactly of required alignment");
1014
1015 assert(markWord::encode_pointer_as_mark(rhs.base()).decode_pointer() == rhs.base(),
1016 "area must be distinguishable from marks for mark-sweep");
1017 assert(markWord::encode_pointer_as_mark(&rhs.base()[rhs.size()]).decode_pointer() ==
1018 &rhs.base()[rhs.size()],
1019 "area must be distinguishable from marks for mark-sweep");
1020
1021 // We are good.
1022
1023 if (AllocateHeapAt != nullptr) {
1024 log_info(gc,heap)("Successfully allocated Java heap at location %s", AllocateHeapAt);
1025 }
1026
1027 if (UseCompressedOops) {
1028 CompressedOops::initialize(rhs);
1029 }
1030
1031 Universe::calculate_verify_data((HeapWord*)rhs.base(), (HeapWord*)rhs.end());
1032
1033 return rhs;
1034 }
1035
1036 OopStorage* Universe::vm_weak() {
1037 return Universe::_vm_weak;
1038 }
1039
1040 OopStorage* Universe::vm_global() {
1041 return Universe::_vm_global;
1042 }
1043
1044 void Universe::oopstorage_init() {
1045 Universe::_vm_global = OopStorageSet::create_strong("VM Global", mtInternal);
1046 Universe::_vm_weak = OopStorageSet::create_weak("VM Weak", mtInternal);
1047 }
1048
1049 void universe_oopstorage_init() {
1050 Universe::oopstorage_init();
1051 }
1052
1053 void LatestMethodCache::init(JavaThread* current, InstanceKlass* ik,
1054 const char* method, Symbol* signature, bool is_static)
1055 {
1056 TempNewSymbol name = SymbolTable::new_symbol(method);
1057 Method* m = nullptr;
1058 // The klass must be linked before looking up the method.
1059 if (!ik->link_class_or_fail(current) ||
1060 ((m = ik->find_method(name, signature)) == nullptr) ||
1061 is_static != m->is_static()) {
1062 ResourceMark rm(current);
1063 // NoSuchMethodException doesn't actually work because it tries to run the
1064 // <init> function before java_lang_Class is linked. Print error and exit.
1065 vm_exit_during_initialization(err_msg("Unable to link/verify %s.%s method",
1066 ik->name()->as_C_string(), method));
1067 }
1068
1069 _klass = ik;
1070 _method_idnum = m->method_idnum();
1071 assert(_method_idnum >= 0, "sanity check");
1072 }
1073
1074 Method* LatestMethodCache::get_method() {
1075 if (_klass == nullptr) {
1076 return nullptr;
1077 } else {
1078 Method* m = _klass->method_with_idnum(_method_idnum);
1079 assert(m != nullptr, "sanity check");
1080 return m;
1081 }
1082 }
1083
1084 Method* Universe::finalizer_register_method() { return _finalizer_register_cache.get_method(); }
1085 Method* Universe::loader_addClass_method() { return _loader_addClass_cache.get_method(); }
1086 Method* Universe::throw_illegal_access_error() { return _throw_illegal_access_error_cache.get_method(); }
1087 Method* Universe::throw_no_such_method_error() { return _throw_no_such_method_error_cache.get_method(); }
1088 Method* Universe::do_stack_walk_method() { return _do_stack_walk_cache.get_method(); }
1089 Method* Universe::is_substitutable_method() { return _is_substitutable_cache.get_method(); }
1090 Method* Universe::value_object_hash_code_method() { return _value_object_hash_code_cache.get_method(); }
1091
1092 void Universe::initialize_known_methods(JavaThread* current) {
1093 // Set up static method for registering finalizers
1094 _finalizer_register_cache.init(current,
1095 vmClasses::Finalizer_klass(),
1096 "register",
1097 vmSymbols::object_void_signature(), true);
1098
1099 _throw_illegal_access_error_cache.init(current,
1100 vmClasses::internal_Unsafe_klass(),
1101 "throwIllegalAccessError",
1102 vmSymbols::void_method_signature(), true);
1103
1104 _throw_no_such_method_error_cache.init(current,
1105 vmClasses::internal_Unsafe_klass(),
1106 "throwNoSuchMethodError",
1107 vmSymbols::void_method_signature(), true);
1108
1109 // Set up method for registering loaded classes in class loader vector
1110 _loader_addClass_cache.init(current,
1111 vmClasses::ClassLoader_klass(),
1112 "addClass",
1113 vmSymbols::class_void_signature(), false);
1114
1115 // Set up method for stack walking
1116 _do_stack_walk_cache.init(current,
1117 vmClasses::AbstractStackWalker_klass(),
1118 "doStackWalk",
1119 vmSymbols::doStackWalk_signature(), false);
1120
1121 // Set up substitutability testing
1122 ResourceMark rm(current);
1123 _is_substitutable_cache.init(current,
1124 vmClasses::ValueObjectMethods_klass(),
1125 vmSymbols::isSubstitutable_name()->as_C_string(),
1126 vmSymbols::object_object_boolean_signature(), true);
1127 _value_object_hash_code_cache.init(current,
1128 vmClasses::ValueObjectMethods_klass(),
1129 vmSymbols::valueObjectHashCode_name()->as_C_string(),
1130 vmSymbols::object_int_signature(), true);
1131 }
1132
1133 void universe2_init() {
1134 EXCEPTION_MARK;
1135 Universe::genesis(CATCH);
1136 }
1137
1138 // Set after initialization of the module runtime, call_initModuleRuntime
1139 void universe_post_module_init() {
1140 Universe::_module_initialized = true;
1141 }
1142
1143 bool universe_post_init() {
1144 assert(!is_init_completed(), "Error: initialization not yet completed!");
1145 Universe::_fully_initialized = true;
1146 EXCEPTION_MARK;
1147 if (!CDSConfig::is_using_archive()) {
1148 reinitialize_vtables();
1149 reinitialize_itables();
1150 }
1151
1152 HandleMark hm(THREAD);
1153 // Setup preallocated empty java.lang.Class array for Method reflection.
1154
1155 objArrayOop the_empty_class_array = oopFactory::new_objArray(vmClasses::Class_klass(), 0, CHECK_false);
1156 Universe::_the_empty_class_array = OopHandle(Universe::vm_global(), the_empty_class_array);
1157
1158 // Setup preallocated OutOfMemoryError errors
1159 Universe::create_preallocated_out_of_memory_errors(CHECK_false);
1160
1161 oop instance;
1162 // Setup preallocated cause message for delayed StackOverflowError
1163 if (StackReservedPages > 0) {
1164 instance = java_lang_String::create_oop_from_str("Delayed StackOverflowError due to ReservedStackAccess annotated method", CHECK_false);
1165 Universe::_delayed_stack_overflow_error_message = OopHandle(Universe::vm_global(), instance);
1166 }
1167
1168 // Setup preallocated exceptions used for a cheap & dirty solution in compiler exception handling
1169 _null_ptr_exception.init_if_empty(vmSymbols::java_lang_NullPointerException(), CHECK_false);
1170 _arithmetic_exception.init_if_empty(vmSymbols::java_lang_ArithmeticException(), CHECK_false);
1171 _array_index_out_of_bounds_exception.init_if_empty(vmSymbols::java_lang_ArrayIndexOutOfBoundsException(), CHECK_false);
1172 _array_store_exception.init_if_empty(vmSymbols::java_lang_ArrayStoreException(), CHECK_false);
1173 _class_cast_exception.init_if_empty(vmSymbols::java_lang_ClassCastException(), CHECK_false);
1174 _preempted_exception.init_if_empty(vmSymbols::jdk_internal_vm_PreemptedException(), CHECK_false);
1175
1176 // Virtual Machine Error for when we get into a situation we can't resolve
1177 Klass* k = vmClasses::InternalError_klass();
1178 bool linked = InstanceKlass::cast(k)->link_class_or_fail(CHECK_false);
1179 if (!linked) {
1180 tty->print_cr("Unable to link/verify InternalError class");
1181 return false; // initialization failed
1182 }
1183 _internal_error.init_if_empty(vmSymbols::java_lang_InternalError(), CHECK_false);
1184
1185 Handle msg = java_lang_String::create_from_str("/ by zero", CHECK_false);
1186 java_lang_Throwable::set_message(Universe::arithmetic_exception_instance(), msg());
1187
1188 // Setup preallocated StackOverflowError for use with class initialization failure
1189 k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_StackOverflowError(), true, CHECK_false);
1190 instance = InstanceKlass::cast(k)->allocate_instance(CHECK_false);
1191 Universe::_class_init_stack_overflow_error = OopHandle(Universe::vm_global(), instance);
1192
1193 Universe::initialize_known_methods(THREAD);
1194
1195 // This needs to be done before the first scavenge/gc, since
1196 // it's an input to soft ref clearing policy.
1197 {
1198 MutexLocker x(THREAD, Heap_lock);
1199 Universe::heap()->update_capacity_and_used_at_gc();
1200 }
1201
1202 // ("weak") refs processing infrastructure initialization
1203 Universe::heap()->post_initialize();
1204
1205 MemoryService::add_metaspace_memory_pools();
1206
1207 MemoryService::set_universe_heap(Universe::heap());
1208
1209 #if INCLUDE_CDS
1210 AOTMetaspace::post_initialize(CHECK_false);
1211 #endif
1212 return true;
1213 }
1214
1215
1216 void Universe::compute_base_vtable_size() {
1217 _base_vtable_size = ClassLoader::compute_Object_vtable();
1218 }
1219
1220 void Universe::print_on(outputStream* st) {
1221 GCMutexLocker hl(Heap_lock); // Heap_lock might be locked by caller thread.
1222 st->print_cr("Heap");
1223
1224 StreamIndentor si(st, 1);
1225 heap()->print_heap_on(st);
1226 MetaspaceUtils::print_on(st);
1227 }
1228
1229 void Universe::print_heap_at_SIGBREAK() {
1230 if (PrintHeapAtSIGBREAK) {
1231 print_on(tty);
1232 tty->cr();
1233 tty->flush();
1234 }
1235 }
1236
1237 void Universe::initialize_verify_flags() {
1238 verify_flags = 0;
1239 const char delimiter[] = " ,";
1240
1241 size_t length = strlen(VerifySubSet);
1242 char* subset_list = NEW_C_HEAP_ARRAY(char, length + 1, mtInternal);
1243 strncpy(subset_list, VerifySubSet, length + 1);
1244 char* save_ptr;
1245
1246 char* token = strtok_r(subset_list, delimiter, &save_ptr);
1247 while (token != nullptr) {
1248 if (strcmp(token, "threads") == 0) {
1249 verify_flags |= Verify_Threads;
1250 } else if (strcmp(token, "heap") == 0) {
1251 verify_flags |= Verify_Heap;
1252 } else if (strcmp(token, "symbol_table") == 0) {
1253 verify_flags |= Verify_SymbolTable;
1254 } else if (strcmp(token, "string_table") == 0) {
1255 verify_flags |= Verify_StringTable;
1256 } else if (strcmp(token, "codecache") == 0) {
1257 verify_flags |= Verify_CodeCache;
1258 } else if (strcmp(token, "dictionary") == 0) {
1259 verify_flags |= Verify_SystemDictionary;
1260 } else if (strcmp(token, "classloader_data_graph") == 0) {
1261 verify_flags |= Verify_ClassLoaderDataGraph;
1262 } else if (strcmp(token, "metaspace") == 0) {
1263 verify_flags |= Verify_MetaspaceUtils;
1264 } else if (strcmp(token, "jni_handles") == 0) {
1265 verify_flags |= Verify_JNIHandles;
1266 } else if (strcmp(token, "codecache_oops") == 0) {
1267 verify_flags |= Verify_CodeCacheOops;
1268 } else if (strcmp(token, "resolved_method_table") == 0) {
1269 verify_flags |= Verify_ResolvedMethodTable;
1270 } else if (strcmp(token, "stringdedup") == 0) {
1271 verify_flags |= Verify_StringDedup;
1272 } else {
1273 vm_exit_during_initialization(err_msg("VerifySubSet: \'%s\' memory sub-system is unknown, please correct it", token));
1274 }
1275 token = strtok_r(nullptr, delimiter, &save_ptr);
1276 }
1277 FREE_C_HEAP_ARRAY(char, subset_list);
1278 }
1279
1280 bool Universe::should_verify_subset(uint subset) {
1281 if (verify_flags & subset) {
1282 return true;
1283 }
1284 return false;
1285 }
1286
1287 void Universe::verify(VerifyOption option, const char* prefix) {
1288 COMPILER2_PRESENT(
1289 assert(!DerivedPointerTable::is_active(),
1290 "DPT should not be active during verification "
1291 "(of thread stacks below)");
1292 )
1293
1294 Thread* thread = Thread::current();
1295 ResourceMark rm(thread);
1296 HandleMark hm(thread); // Handles created during verification can be zapped
1297 _verify_count++;
1298
1299 FormatBuffer<> title("Verifying %s", prefix);
1300 GCTraceTime(Info, gc, verify) tm(title.buffer());
1301 if (should_verify_subset(Verify_Threads)) {
1302 log_debug(gc, verify)("Threads");
1303 Threads::verify();
1304 }
1305 if (should_verify_subset(Verify_Heap)) {
1306 log_debug(gc, verify)("Heap");
1307 heap()->verify(option);
1308 }
1309 if (should_verify_subset(Verify_SymbolTable)) {
1310 log_debug(gc, verify)("SymbolTable");
1311 SymbolTable::verify();
1312 }
1313 if (should_verify_subset(Verify_StringTable)) {
1314 log_debug(gc, verify)("StringTable");
1315 StringTable::verify();
1316 }
1317 if (should_verify_subset(Verify_CodeCache)) {
1318 log_debug(gc, verify)("CodeCache");
1319 CodeCache::verify();
1320 }
1321 if (should_verify_subset(Verify_SystemDictionary)) {
1322 log_debug(gc, verify)("SystemDictionary");
1323 SystemDictionary::verify();
1324 }
1325 if (should_verify_subset(Verify_ClassLoaderDataGraph)) {
1326 log_debug(gc, verify)("ClassLoaderDataGraph");
1327 ClassLoaderDataGraph::verify();
1328 }
1329 if (should_verify_subset(Verify_MetaspaceUtils)) {
1330 log_debug(gc, verify)("MetaspaceUtils");
1331 DEBUG_ONLY(MetaspaceUtils::verify();)
1332 }
1333 if (should_verify_subset(Verify_JNIHandles)) {
1334 log_debug(gc, verify)("JNIHandles");
1335 JNIHandles::verify();
1336 }
1337 if (should_verify_subset(Verify_CodeCacheOops)) {
1338 log_debug(gc, verify)("CodeCache Oops");
1339 CodeCache::verify_oops();
1340 }
1341 if (should_verify_subset(Verify_ResolvedMethodTable)) {
1342 log_debug(gc, verify)("ResolvedMethodTable Oops");
1343 ResolvedMethodTable::verify();
1344 }
1345 if (should_verify_subset(Verify_StringDedup)) {
1346 log_debug(gc, verify)("String Deduplication");
1347 StringDedup::verify();
1348 }
1349 }
1350
1351 static void log_cpu_time() {
1352 LogTarget(Info, cpu) cpuLog;
1353 if (!cpuLog.is_enabled()) {
1354 return;
1355 }
1356
1357 const double process_cpu_time = os::elapsed_process_cpu_time();
1358 if (process_cpu_time == 0 || process_cpu_time == -1) {
1359 // 0 can happen e.g. for short running processes with
1360 // low CPU utilization
1361 return;
1362 }
1363
1364 const double gc_threads_cpu_time = (double) CPUTimeUsage::GC::gc_threads() / NANOSECS_PER_SEC;
1365 const double gc_vm_thread_cpu_time = (double) CPUTimeUsage::GC::vm_thread() / NANOSECS_PER_SEC;
1366 const double gc_string_dedup_cpu_time = (double) CPUTimeUsage::GC::stringdedup() / NANOSECS_PER_SEC;
1367 const double gc_cpu_time = (double) gc_threads_cpu_time + gc_vm_thread_cpu_time + gc_string_dedup_cpu_time;
1368
1369 const double elasped_time = os::elapsedTime();
1370 const bool has_error = CPUTimeUsage::Error::has_error();
1371
1372 if (gc_cpu_time < process_cpu_time) {
1373 cpuLog.print("=== CPU time Statistics =============================================================");
1374 if (has_error) {
1375 cpuLog.print("WARNING: CPU time sampling reported errors, numbers may be unreliable");
1376 }
1377 cpuLog.print(" CPUs");
1378 cpuLog.print(" s %% utilized");
1379 cpuLog.print(" Process");
1380 cpuLog.print(" Total %30.4f %6.2f %8.1f", process_cpu_time, 100.0, process_cpu_time / elasped_time);
1381 cpuLog.print(" Garbage Collection %30.4f %6.2f %8.1f", gc_cpu_time, percent_of(gc_cpu_time, process_cpu_time), gc_cpu_time / elasped_time);
1382 cpuLog.print(" GC Threads %30.4f %6.2f %8.1f", gc_threads_cpu_time, percent_of(gc_threads_cpu_time, process_cpu_time), gc_threads_cpu_time / elasped_time);
1383 cpuLog.print(" VM Thread %30.4f %6.2f %8.1f", gc_vm_thread_cpu_time, percent_of(gc_vm_thread_cpu_time, process_cpu_time), gc_vm_thread_cpu_time / elasped_time);
1384
1385 if (UseStringDeduplication) {
1386 cpuLog.print(" String Deduplication %30.4f %6.2f %8.1f", gc_string_dedup_cpu_time, percent_of(gc_string_dedup_cpu_time, process_cpu_time), gc_string_dedup_cpu_time / elasped_time);
1387 }
1388 cpuLog.print("=====================================================================================");
1389 }
1390 }
1391
1392 void Universe::before_exit() {
1393 // Tell the GC that it is time to shutdown and to block requests for new GC pauses.
1394 heap()->initiate_shutdown();
1395
1396 // Log CPU time statistics before stopping the GC threads.
1397 log_cpu_time();
1398
1399 // Stop the GC threads.
1400 heap()->stop();
1401
1402 // Print GC/heap related information.
1403 Log(gc, exit) log;
1404 if (log.is_info()) {
1405 LogStream ls_info(log.info());
1406 Universe::print_on(&ls_info);
1407 if (log.is_trace()) {
1408 LogStream ls_trace(log.trace());
1409 MutexLocker mcld(ClassLoaderDataGraph_lock);
1410 ClassLoaderDataGraph::print_on(&ls_trace);
1411 }
1412 }
1413 }
1414
1415 #ifndef PRODUCT
1416 void Universe::calculate_verify_data(HeapWord* low_boundary, HeapWord* high_boundary) {
1417 assert(low_boundary < high_boundary, "bad interval");
1418
1419 // decide which low-order bits we require to be clear:
1420 size_t alignSize = MinObjAlignmentInBytes;
1421 size_t min_object_size = CollectedHeap::min_fill_size();
1422
1423 // make an inclusive limit:
1424 uintptr_t max = (uintptr_t)high_boundary - min_object_size*wordSize;
1425 uintptr_t min = (uintptr_t)low_boundary;
1426 assert(min < max, "bad interval");
1427 uintptr_t diff = max ^ min;
1428
1429 // throw away enough low-order bits to make the diff vanish
1430 uintptr_t mask = (uintptr_t)(-1);
1431 while ((mask & diff) != 0)
1432 mask <<= 1;
1433 uintptr_t bits = (min & mask);
1434 assert(bits == (max & mask), "correct mask");
1435 // check an intermediate value between min and max, just to make sure:
1436 assert(bits == ((min + (max-min)/2) & mask), "correct mask");
1437
1438 // require address alignment, too:
1439 mask |= (alignSize - 1);
1440
1441 if (!(_verify_oop_mask == 0 && _verify_oop_bits == (uintptr_t)-1)) {
1442 assert(_verify_oop_mask == mask && _verify_oop_bits == bits, "mask stability");
1443 }
1444 _verify_oop_mask = mask;
1445 _verify_oop_bits = bits;
1446 }
1447
1448 void Universe::set_verify_data(uintptr_t mask, uintptr_t bits) {
1449 _verify_oop_mask = mask;
1450 _verify_oop_bits = bits;
1451 }
1452
1453 // Oop verification (see MacroAssembler::verify_oop)
1454
1455 uintptr_t Universe::verify_oop_mask() {
1456 return _verify_oop_mask;
1457 }
1458
1459 uintptr_t Universe::verify_oop_bits() {
1460 return _verify_oop_bits;
1461 }
1462
1463 uintptr_t Universe::verify_mark_mask() {
1464 return markWord::lock_mask_in_place;
1465 }
1466
1467 uintptr_t Universe::verify_mark_bits() {
1468 intptr_t mask = verify_mark_mask();
1469 intptr_t bits = (intptr_t)markWord::prototype().value();
1470 assert((bits & ~mask) == 0, "no stray header bits");
1471 return bits;
1472 }
1473 #endif // PRODUCT
1474
1475 #ifdef ASSERT
1476 // Release dummy object(s) at bottom of heap
1477 bool Universe::release_fullgc_alot_dummy() {
1478 MutexLocker ml(FullGCALot_lock, Mutex::_no_safepoint_check_flag);
1479 objArrayOop fullgc_alot_dummy_array = (objArrayOop)_fullgc_alot_dummy_array.resolve();
1480 if (fullgc_alot_dummy_array != nullptr) {
1481 if (_fullgc_alot_dummy_next >= fullgc_alot_dummy_array->length()) {
1482 // No more dummies to release, release entire array instead
1483 _fullgc_alot_dummy_array.release(Universe::vm_global());
1484 _fullgc_alot_dummy_array = OopHandle(); // null out OopStorage pointer.
1485 return false;
1486 }
1487
1488 // Release dummy at bottom of old generation
1489 fullgc_alot_dummy_array->obj_at_put(_fullgc_alot_dummy_next++, nullptr);
1490 }
1491 return true;
1492 }
1493
1494 bool Universe::is_stw_gc_active() {
1495 return heap()->is_stw_gc_active();
1496 }
1497
1498 bool Universe::is_in_heap(const void* p) {
1499 return heap()->is_in(p);
1500 }
1501
1502 #endif // ASSERT