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