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/aotConstantPoolResolver.hpp"
26 #include "cds/archiveBuilder.hpp"
27 #include "cds/cdsConfig.hpp"
28 #include "cds/heapShared.inline.hpp"
29 #include "classfile/classLoader.hpp"
30 #include "classfile/classLoaderData.hpp"
31 #include "classfile/javaClasses.inline.hpp"
32 #include "classfile/metadataOnStackMark.hpp"
33 #include "classfile/stringTable.hpp"
34 #include "classfile/systemDictionary.hpp"
35 #include "classfile/systemDictionaryShared.hpp"
36 #include "classfile/vmClasses.hpp"
37 #include "classfile/vmSymbols.hpp"
38 #include "code/codeCache.hpp"
39 #include "interpreter/bootstrapInfo.hpp"
40 #include "interpreter/linkResolver.hpp"
41 #include "jvm.h"
42 #include "logging/log.hpp"
43 #include "logging/logStream.hpp"
44 #include "memory/allocation.inline.hpp"
45 #include "memory/metadataFactory.hpp"
46 #include "memory/metaspaceClosure.hpp"
47 #include "memory/oopFactory.hpp"
48 #include "memory/resourceArea.hpp"
49 #include "memory/universe.hpp"
50 #include "oops/array.hpp"
51 #include "oops/constantPool.inline.hpp"
52 #include "oops/cpCache.inline.hpp"
53 #include "oops/fieldStreams.inline.hpp"
54 #include "oops/instanceKlass.hpp"
55 #include "oops/klass.inline.hpp"
56 #include "oops/objArrayKlass.hpp"
57 #include "oops/objArrayOop.inline.hpp"
58 #include "oops/oop.inline.hpp"
59 #include "oops/typeArrayOop.inline.hpp"
60 #include "prims/jvmtiExport.hpp"
61 #include "runtime/atomicAccess.hpp"
62 #include "runtime/fieldDescriptor.inline.hpp"
63 #include "runtime/handles.inline.hpp"
64 #include "runtime/init.hpp"
65 #include "runtime/javaCalls.hpp"
66 #include "runtime/javaThread.inline.hpp"
67 #include "runtime/perfData.hpp"
68 #include "runtime/signature.hpp"
69 #include "runtime/vframe.inline.hpp"
70 #include "utilities/checkedCast.hpp"
71 #include "utilities/copy.hpp"
72
73 ConstantPool* ConstantPool::allocate(ClassLoaderData* loader_data, int length, TRAPS) {
74 Array<u1>* tags = MetadataFactory::new_array<u1>(loader_data, length, 0, CHECK_NULL);
75 int size = ConstantPool::size(length);
76 return new (loader_data, size, MetaspaceObj::ConstantPoolType, THREAD) ConstantPool(tags);
77 }
78
79 void ConstantPool::copy_fields(const ConstantPool* orig) {
80 // Preserve dynamic constant information from the original pool
81 if (orig->has_dynamic_constant()) {
82 set_has_dynamic_constant();
83 }
84
85 set_major_version(orig->major_version());
86 set_minor_version(orig->minor_version());
87
88 set_source_file_name_index(orig->source_file_name_index());
89 set_generic_signature_index(orig->generic_signature_index());
90 }
91
92 #ifdef ASSERT
93
94 // MetaspaceObj allocation invariant is calloc equivalent memory
95 // simple verification of this here (JVM_CONSTANT_Invalid == 0 )
96 static bool tag_array_is_zero_initialized(Array<u1>* tags) {
97 assert(tags != nullptr, "invariant");
98 const int length = tags->length();
99 for (int index = 0; index < length; ++index) {
100 if (JVM_CONSTANT_Invalid != tags->at(index)) {
101 return false;
102 }
103 }
104 return true;
105 }
106
107 #endif
108
109 ConstantPool::ConstantPool() {
110 assert(CDSConfig::is_dumping_static_archive() || CDSConfig::is_using_archive(), "only for CDS");
111 }
112
113 ConstantPool::ConstantPool(Array<u1>* tags) :
114 _tags(tags),
115 _length(tags->length()) {
116
117 assert(_tags != nullptr, "invariant");
118 assert(tags->length() == _length, "invariant");
119 assert(tag_array_is_zero_initialized(tags), "invariant");
120 assert(0 == flags(), "invariant");
121 assert(0 == version(), "invariant");
122 assert(nullptr == _pool_holder, "invariant");
123 }
124
125 void ConstantPool::deallocate_contents(ClassLoaderData* loader_data) {
126 if (cache() != nullptr) {
127 MetadataFactory::free_metadata(loader_data, cache());
128 set_cache(nullptr);
129 }
130
131 MetadataFactory::free_array<Klass*>(loader_data, resolved_klasses());
132 set_resolved_klasses(nullptr);
133
134 bsm_entries().deallocate_contents(loader_data);
135
136 release_C_heap_structures();
137
138 // free tag array
139 MetadataFactory::free_array<u1>(loader_data, tags());
140 set_tags(nullptr);
141 }
142
143 void ConstantPool::release_C_heap_structures() {
144 // walk constant pool and decrement symbol reference counts
145 unreference_symbols();
146 }
147
148 void ConstantPool::metaspace_pointers_do(MetaspaceClosure* it) {
149 log_trace(aot)("Iter(ConstantPool): %p", this);
150
151 it->push(&_tags, MetaspaceClosure::_writable);
152 it->push(&_cache);
153 it->push(&_pool_holder);
154 it->push(&bsm_entries().offsets());
155 it->push(&bsm_entries().bootstrap_methods());
156 it->push(&_resolved_klasses, MetaspaceClosure::_writable);
157
158 for (int i = 0; i < length(); i++) {
159 // The only MSO's embedded in the CP entries are Symbols:
160 // JVM_CONSTANT_String
161 // JVM_CONSTANT_Utf8
162 constantTag ctag = tag_at(i);
163 if (ctag.is_string() || ctag.is_utf8()) {
164 it->push(symbol_at_addr(i));
165 }
166 }
167 }
168
169 objArrayOop ConstantPool::resolved_references() const {
170 return _cache->resolved_references();
171 }
172
173 // Called from outside constant pool resolution where a resolved_reference array
174 // may not be present.
175 objArrayOop ConstantPool::resolved_references_or_null() const {
176 if (_cache == nullptr) {
177 return nullptr;
178 } else {
179 return _cache->resolved_references();
180 }
181 }
182
183 oop ConstantPool::resolved_reference_at(int index) const {
184 oop result = resolved_references()->obj_at(index);
185 assert(oopDesc::is_oop_or_null(result), "Must be oop");
186 return result;
187 }
188
189 // Use a CAS for multithreaded access
190 oop ConstantPool::set_resolved_reference_at(int index, oop new_result) {
191 assert(oopDesc::is_oop_or_null(new_result), "Must be oop");
192 return resolved_references()->replace_if_null(index, new_result);
193 }
194
195 // Create resolved_references array and mapping array for original cp indexes
196 // The ldc bytecode was rewritten to have the resolved reference array index so need a way
197 // to map it back for resolving and some unlikely miscellaneous uses.
198 // The objects created by invokedynamic are appended to this list.
199 void ConstantPool::initialize_resolved_references(ClassLoaderData* loader_data,
200 const intStack& reference_map,
201 int constant_pool_map_length,
202 TRAPS) {
203 // Initialized the resolved object cache.
204 int map_length = reference_map.length();
205 if (map_length > 0) {
206 // Only need mapping back to constant pool entries. The map isn't used for
207 // invokedynamic resolved_reference entries. For invokedynamic entries,
208 // the constant pool cache index has the mapping back to both the constant
209 // pool and to the resolved reference index.
210 if (constant_pool_map_length > 0) {
211 Array<u2>* om = MetadataFactory::new_array<u2>(loader_data, constant_pool_map_length, CHECK);
212
213 for (int i = 0; i < constant_pool_map_length; i++) {
214 int x = reference_map.at(i);
215 assert(x == (int)(jushort) x, "klass index is too big");
216 om->at_put(i, (jushort)x);
217 }
218 set_reference_map(om);
219 }
220
221 // Create Java array for holding resolved strings, methodHandles,
222 // methodTypes, invokedynamic and invokehandle appendix objects, etc.
223 objArrayOop stom = oopFactory::new_objArray(vmClasses::Object_klass(), map_length, CHECK);
224 HandleMark hm(THREAD);
225 Handle refs_handle (THREAD, stom); // must handleize.
226 set_resolved_references(loader_data->add_handle(refs_handle));
227
228 // Create a "scratch" copy of the resolved references array to archive
229 if (CDSConfig::is_dumping_heap()) {
230 objArrayOop scratch_references = oopFactory::new_objArray(vmClasses::Object_klass(), map_length, CHECK);
231 HeapShared::add_scratch_resolved_references(this, scratch_references);
232 }
233 }
234 }
235
236 void ConstantPool::allocate_resolved_klasses(ClassLoaderData* loader_data, int num_klasses, TRAPS) {
237 // A ConstantPool can't possibly have 0xffff valid class entries,
238 // because entry #0 must be CONSTANT_Invalid, and each class entry must refer to a UTF8
239 // entry for the class's name. So at most we will have 0xfffe class entries.
240 // This allows us to use 0xffff (ConstantPool::_temp_resolved_klass_index) to indicate
241 // UnresolvedKlass entries that are temporarily created during class redefinition.
242 assert(num_klasses < CPKlassSlot::_temp_resolved_klass_index, "sanity");
243 assert(resolved_klasses() == nullptr, "sanity");
244 Array<Klass*>* rk = MetadataFactory::new_array<Klass*>(loader_data, num_klasses, CHECK);
245 set_resolved_klasses(rk);
246 }
247
248 void ConstantPool::initialize_unresolved_klasses(ClassLoaderData* loader_data, TRAPS) {
249 int len = length();
250 int num_klasses = 0;
251 for (int i = 1; i <len; i++) {
252 switch (tag_at(i).value()) {
253 case JVM_CONSTANT_ClassIndex:
254 {
255 const int class_index = klass_index_at(i);
256 unresolved_klass_at_put(i, class_index, num_klasses++);
257 }
258 break;
259 #ifndef PRODUCT
260 case JVM_CONSTANT_Class:
261 case JVM_CONSTANT_UnresolvedClass:
262 case JVM_CONSTANT_UnresolvedClassInError:
263 // All of these should have been reverted back to ClassIndex before calling
264 // this function.
265 ShouldNotReachHere();
266 #endif
267 }
268 }
269 allocate_resolved_klasses(loader_data, num_klasses, THREAD);
270 }
271
272 // Hidden class support:
273 void ConstantPool::klass_at_put(int class_index, Klass* k) {
274 assert(k != nullptr, "must be valid klass");
275 CPKlassSlot kslot = klass_slot_at(class_index);
276 int resolved_klass_index = kslot.resolved_klass_index();
277 Klass** adr = resolved_klasses()->adr_at(resolved_klass_index);
278 AtomicAccess::release_store(adr, k);
279
280 // The interpreter assumes when the tag is stored, the klass is resolved
281 // and the Klass* non-null, so we need hardware store ordering here.
282 release_tag_at_put(class_index, JVM_CONSTANT_Class);
283 }
284
285 #if INCLUDE_CDS_JAVA_HEAP
286 template <typename Function>
287 void ConstantPool::iterate_archivable_resolved_references(Function function) {
288 objArrayOop rr = resolved_references();
289 if (rr != nullptr && cache() != nullptr && CDSConfig::is_dumping_method_handles()) {
290 Array<ResolvedIndyEntry>* indy_entries = cache()->resolved_indy_entries();
291 if (indy_entries != nullptr) {
292 for (int i = 0; i < indy_entries->length(); i++) {
293 ResolvedIndyEntry *rie = indy_entries->adr_at(i);
294 if (rie->is_resolved() && AOTConstantPoolResolver::is_resolution_deterministic(this, rie->constant_pool_index())) {
295 int rr_index = rie->resolved_references_index();
296 assert(resolved_reference_at(rr_index) != nullptr, "must exist");
297 function(rr_index);
298
299 // Save the BSM as well (sometimes the JIT looks up the BSM it for replay)
300 int indy_cp_index = rie->constant_pool_index();
301 int bsm_mh_cp_index = bootstrap_method_ref_index_at(indy_cp_index);
302 int bsm_rr_index = cp_to_object_index(bsm_mh_cp_index);
303 assert(resolved_reference_at(bsm_rr_index) != nullptr, "must exist");
304 function(bsm_rr_index);
305 }
306 }
307 }
308
309 Array<ResolvedMethodEntry>* method_entries = cache()->resolved_method_entries();
310 if (method_entries != nullptr) {
311 for (int i = 0; i < method_entries->length(); i++) {
312 ResolvedMethodEntry* rme = method_entries->adr_at(i);
313 const char* rejection_reason = nullptr;
314 if (rme->is_resolved(Bytecodes::_invokehandle) && rme->has_appendix() &&
315 cache()->can_archive_resolved_method(this, rme, rejection_reason)) {
316 int rr_index = rme->resolved_references_index();
317 assert(resolved_reference_at(rr_index) != nullptr, "must exist");
318 function(rr_index);
319 }
320 }
321 }
322 }
323 }
324
325 // Returns the _resolved_reference array after removing unarchivable items from it.
326 // Returns null if this class is not supported, or _resolved_reference doesn't exist.
327 objArrayOop ConstantPool::prepare_resolved_references_for_archiving() {
328 if (_cache == nullptr) {
329 return nullptr; // nothing to do
330 }
331
332 InstanceKlass *ik = pool_holder();
333 if (!SystemDictionaryShared::is_builtin_loader(ik->class_loader_data())) {
334 // Archiving resolved references for classes from non-builtin loaders
335 // is not yet supported.
336 return nullptr;
337 }
338
339 objArrayOop rr = resolved_references();
340 if (rr != nullptr) {
341 ResourceMark rm;
342 int rr_len = rr->length();
343 GrowableArray<bool> keep_resolved_refs(rr_len, rr_len, false);
344
345 iterate_archivable_resolved_references([&](int rr_index) {
346 keep_resolved_refs.at_put(rr_index, true);
347 });
348
349 objArrayOop scratch_rr = HeapShared::scratch_resolved_references(this);
350 Array<u2>* ref_map = reference_map();
351 int ref_map_len = ref_map == nullptr ? 0 : ref_map->length();
352 for (int i = 0; i < rr_len; i++) {
353 oop obj = rr->obj_at(i);
354 scratch_rr->obj_at_put(i, nullptr);
355 if (obj != nullptr) {
356 if (i < ref_map_len) {
357 int index = object_to_cp_index(i);
358 if (tag_at(index).is_string()) {
359 assert(java_lang_String::is_instance(obj), "must be");
360 if (!HeapShared::is_string_too_large_to_archive(obj)) {
361 scratch_rr->obj_at_put(i, obj);
362 }
363 continue;
364 }
365 }
366
367 if (keep_resolved_refs.at(i)) {
368 scratch_rr->obj_at_put(i, obj);
369 }
370 }
371 }
372 return scratch_rr;
373 }
374 return rr;
375 }
376 #endif
377
378 #if INCLUDE_CDS
379 // CDS support. Create a new resolved_references array.
380 void ConstantPool::restore_unshareable_info(TRAPS) {
381 if (!_pool_holder->is_linked() && !_pool_holder->is_rewritten()) {
382 return;
383 }
384 assert(is_constantPool(), "ensure C++ vtable is restored");
385 assert(on_stack(), "should always be set for constant pools in AOT cache");
386 assert(in_aot_cache(), "should always be set for constant pools in AOT cache");
387 if (is_for_method_handle_intrinsic()) {
388 // See the same check in remove_unshareable_info() below.
389 assert(cache() == nullptr, "must not have cpCache");
390 return;
391 }
392 assert(_cache != nullptr, "constant pool _cache should not be null");
393
394 // Only create the new resolved references array if it hasn't been attempted before
395 if (resolved_references() != nullptr) return;
396
397 if (vmClasses::Object_klass_is_loaded()) {
398 ClassLoaderData* loader_data = pool_holder()->class_loader_data();
399 #if INCLUDE_CDS_JAVA_HEAP
400 if (HeapShared::is_archived_heap_in_use() &&
401 _cache->archived_references() != nullptr) {
402 oop archived = _cache->archived_references();
403 // Create handle for the archived resolved reference array object
404 HandleMark hm(THREAD);
405 Handle refs_handle(THREAD, archived);
406 set_resolved_references(loader_data->add_handle(refs_handle));
407 _cache->clear_archived_references();
408 } else
409 #endif
410 {
411 // No mapped archived resolved reference array
412 // Recreate the object array and add to ClassLoaderData.
413 int map_length = resolved_reference_length();
414 if (map_length > 0) {
415 objArrayOop stom = oopFactory::new_objArray(vmClasses::Object_klass(), map_length, CHECK);
416 HandleMark hm(THREAD);
417 Handle refs_handle(THREAD, stom); // must handleize.
418 set_resolved_references(loader_data->add_handle(refs_handle));
419 }
420 }
421 }
422
423 if (CDSConfig::is_dumping_final_static_archive() && CDSConfig::is_dumping_heap() && resolved_references() != nullptr) {
424 objArrayOop scratch_references = oopFactory::new_objArray(vmClasses::Object_klass(), resolved_references()->length(), CHECK);
425 HeapShared::add_scratch_resolved_references(this, scratch_references);
426 }
427 }
428
429 void ConstantPool::remove_unshareable_info() {
430 // ConstantPools in AOT cache are in the RO region, so the _flags cannot be modified.
431 // The _on_stack flag is used to prevent ConstantPools from deallocation during
432 // class redefinition. Since such ConstantPools cannot be deallocated anyway,
433 // we always set _on_stack to true to avoid having to change _flags during runtime.
434 _flags |= (_on_stack | _in_aot_cache);
435
436 if (is_for_method_handle_intrinsic()) {
437 // This CP was created by Method::make_method_handle_intrinsic() and has nothing
438 // that need to be removed/restored. It has no cpCache since the intrinsic methods
439 // don't have any bytecodes.
440 assert(cache() == nullptr, "must not have cpCache");
441 return;
442 }
443
444 bool update_resolved_reference = true;
445 if (CDSConfig::is_dumping_final_static_archive()) {
446 ConstantPool* src_cp = ArchiveBuilder::current()->get_source_addr(this);
447 InstanceKlass* src_holder = src_cp->pool_holder();
448 if (src_holder->defined_by_other_loaders()) {
449 // Unregistered classes are not loaded in the AOT assembly phase. The resolved reference length
450 // is already saved during the training run.
451 precond(!src_holder->is_loaded());
452 precond(resolved_reference_length() >= 0);
453 precond(resolved_references() == nullptr);
454 update_resolved_reference = false;
455 }
456 }
457
458 // resolved_references(): remember its length. If it cannot be restored
459 // from the archived heap objects at run time, we need to dynamically allocate it.
460 if (update_resolved_reference && cache() != nullptr) {
461 set_resolved_reference_length(
462 resolved_references() != nullptr ? resolved_references()->length() : 0);
463 set_resolved_references(OopHandle());
464 }
465 remove_unshareable_entries();
466 }
467
468 static const char* get_type(Klass* k) {
469 const char* type;
470 Klass* src_k;
471 if (ArchiveBuilder::is_active() && ArchiveBuilder::current()->is_in_buffer_space(k)) {
472 src_k = ArchiveBuilder::current()->get_source_addr(k);
473 } else {
474 src_k = k;
475 }
476
477 if (src_k->is_objArray_klass()) {
478 src_k = ObjArrayKlass::cast(src_k)->bottom_klass();
479 assert(!src_k->is_objArray_klass(), "sanity");
480 }
481
482 if (src_k->is_typeArray_klass()) {
483 type = "prim";
484 } else {
485 InstanceKlass* src_ik = InstanceKlass::cast(src_k);
486 if (CDSConfig::is_dumping_final_static_archive() && src_ik->class_loader_data() == nullptr) {
487 return "unreg";
488 }
489 if (src_ik->defined_by_boot_loader()) {
490 return "boot";
491 } else if (src_ik->defined_by_platform_loader()) {
492 return "plat";
493 } else if (src_ik->defined_by_app_loader()) {
494 return "app";
495 } else {
496 return "unreg";
497 }
498 }
499
500 return type;
501 }
502
503 void ConstantPool::remove_unshareable_entries() {
504 ResourceMark rm;
505 log_info(aot, resolve)("Archiving CP entries for %s", pool_holder()->name()->as_C_string());
506 for (int cp_index = 1; cp_index < length(); cp_index++) { // cp_index 0 is unused
507 int cp_tag = tag_at(cp_index).value();
508 switch (cp_tag) {
509 case JVM_CONSTANT_UnresolvedClass:
510 ArchiveBuilder::alloc_stats()->record_klass_cp_entry(false, false);
511 break;
512 case JVM_CONSTANT_UnresolvedClassInError:
513 tag_at_put(cp_index, JVM_CONSTANT_UnresolvedClass);
514 ArchiveBuilder::alloc_stats()->record_klass_cp_entry(false, true);
515 break;
516 case JVM_CONSTANT_MethodHandleInError:
517 tag_at_put(cp_index, JVM_CONSTANT_MethodHandle);
518 break;
519 case JVM_CONSTANT_MethodTypeInError:
520 tag_at_put(cp_index, JVM_CONSTANT_MethodType);
521 break;
522 case JVM_CONSTANT_DynamicInError:
523 tag_at_put(cp_index, JVM_CONSTANT_Dynamic);
524 break;
525 case JVM_CONSTANT_Class:
526 remove_resolved_klass_if_non_deterministic(cp_index);
527 break;
528 default:
529 break;
530 }
531 }
532
533 if (cache() != nullptr) {
534 // cache() is null if this class is not yet linked.
535 cache()->remove_unshareable_info();
536 }
537 }
538
539 void ConstantPool::remove_resolved_klass_if_non_deterministic(int cp_index) {
540 assert(ArchiveBuilder::current()->is_in_buffer_space(this), "must be");
541 assert(tag_at(cp_index).is_klass(), "must be resolved");
542
543 bool can_archive;
544 Klass* k = nullptr;
545
546 if (CDSConfig::is_dumping_preimage_static_archive()) {
547 can_archive = false;
548 } else {
549 k = resolved_klass_at(cp_index);
550 if (k == nullptr) {
551 // We'd come here if the referenced class has been excluded via
552 // SystemDictionaryShared::is_excluded_class(). As a result, ArchiveBuilder
553 // has cleared the resolved_klasses()->at(...) pointer to null. Thus, we
554 // need to revert the tag to JVM_CONSTANT_UnresolvedClass.
555 can_archive = false;
556 } else {
557 ConstantPool* src_cp = ArchiveBuilder::current()->get_source_addr(this);
558 can_archive = AOTConstantPoolResolver::is_resolution_deterministic(src_cp, cp_index);
559 }
560 }
561
562 if (!can_archive) {
563 int resolved_klass_index = klass_slot_at(cp_index).resolved_klass_index();
564 // This might be at a safepoint but do this in the right order.
565 tag_at_put(cp_index, JVM_CONSTANT_UnresolvedClass);
566 resolved_klasses()->at_put(resolved_klass_index, nullptr);
567 }
568
569 LogStreamHandle(Trace, aot, resolve) log;
570 if (log.is_enabled()) {
571 ResourceMark rm;
572 log.print("%s klass CP entry [%3d]: %s %s",
573 (can_archive ? "archived" : "reverted"),
574 cp_index, pool_holder()->name()->as_C_string(), get_type(pool_holder()));
575 if (can_archive) {
576 log.print(" => %s %s%s", k->name()->as_C_string(), get_type(k),
577 (!k->is_instance_klass() || pool_holder()->is_subtype_of(k)) ? "" : " (not supertype)");
578 } else {
579 Symbol* name = klass_name_at(cp_index);
580 log.print(" => %s", name->as_C_string());
581 }
582 }
583
584 ArchiveBuilder::alloc_stats()->record_klass_cp_entry(can_archive, /*reverted=*/!can_archive);
585 }
586 #endif // INCLUDE_CDS
587
588 int ConstantPool::cp_to_object_index(int cp_index) {
589 // this is harder don't do this so much.
590 int i = reference_map()->find(checked_cast<u2>(cp_index));
591 // We might not find the index for jsr292 call.
592 return (i < 0) ? _no_index_sentinel : i;
593 }
594
595 void ConstantPool::string_at_put(int obj_index, oop str) {
596 oop result = set_resolved_reference_at(obj_index, str);
597 assert(result == nullptr || result == str, "Only set once or to the same string.");
598 }
599
600 void ConstantPool::trace_class_resolution(const constantPoolHandle& this_cp, Klass* k) {
601 ResourceMark rm;
602 int line_number = -1;
603 const char * source_file = nullptr;
604 if (JavaThread::current()->has_last_Java_frame()) {
605 // try to identify the method which called this function.
606 vframeStream vfst(JavaThread::current());
607 if (!vfst.at_end()) {
608 line_number = vfst.method()->line_number_from_bci(vfst.bci());
609 Symbol* s = vfst.method()->method_holder()->source_file_name();
610 if (s != nullptr) {
611 source_file = s->as_C_string();
612 }
613 }
614 }
615 if (k != this_cp->pool_holder()) {
616 // only print something if the classes are different
617 if (source_file != nullptr) {
618 log_debug(class, resolve)("%s %s %s:%d",
619 this_cp->pool_holder()->external_name(),
620 k->external_name(), source_file, line_number);
621 } else {
622 log_debug(class, resolve)("%s %s",
623 this_cp->pool_holder()->external_name(),
624 k->external_name());
625 }
626 }
627 }
628
629 Klass* ConstantPool::klass_at_impl(const constantPoolHandle& this_cp, int cp_index,
630 TRAPS) {
631 JavaThread* javaThread = THREAD;
632
633 // A resolved constantPool entry will contain a Klass*, otherwise a Symbol*.
634 // It is not safe to rely on the tag bit's here, since we don't have a lock, and
635 // the entry and tag is not updated atomically.
636 CPKlassSlot kslot = this_cp->klass_slot_at(cp_index);
637 int resolved_klass_index = kslot.resolved_klass_index();
638 int name_index = kslot.name_index();
639 assert(this_cp->tag_at(name_index).is_symbol(), "sanity");
640
641 // The tag must be JVM_CONSTANT_Class in order to read the correct value from
642 // the unresolved_klasses() array.
643 if (this_cp->tag_at(cp_index).is_klass()) {
644 Klass* klass = this_cp->resolved_klasses()->at(resolved_klass_index);
645 assert(klass != nullptr, "must be resolved");
646 return klass;
647 }
648
649 // This tag doesn't change back to unresolved class unless at a safepoint.
650 if (this_cp->tag_at(cp_index).is_unresolved_klass_in_error()) {
651 // The original attempt to resolve this constant pool entry failed so find the
652 // class of the original error and throw another error of the same class
653 // (JVMS 5.4.3).
654 // If there is a detail message, pass that detail message to the error.
655 // The JVMS does not strictly require us to duplicate the same detail message,
656 // or any internal exception fields such as cause or stacktrace. But since the
657 // detail message is often a class name or other literal string, we will repeat it
658 // if we can find it in the symbol table.
659 throw_resolution_error(this_cp, cp_index, CHECK_NULL);
660 ShouldNotReachHere();
661 }
662
663 HandleMark hm(THREAD);
664 Handle mirror_handle;
665 Symbol* name = this_cp->symbol_at(name_index);
666 Handle loader (THREAD, this_cp->pool_holder()->class_loader());
667
668 Klass* k;
669 {
670 // Turn off the single stepping while doing class resolution
671 JvmtiHideSingleStepping jhss(javaThread);
672 k = SystemDictionary::resolve_or_fail(name, loader, true, THREAD);
673 } // JvmtiHideSingleStepping jhss(javaThread);
674
675 if (!HAS_PENDING_EXCEPTION) {
676 // preserve the resolved klass from unloading
677 mirror_handle = Handle(THREAD, k->java_mirror());
678 // Do access check for klasses
679 verify_constant_pool_resolve(this_cp, k, THREAD);
680 }
681
682 // Failed to resolve class. We must record the errors so that subsequent attempts
683 // to resolve this constant pool entry fail with the same error (JVMS 5.4.3).
684 if (HAS_PENDING_EXCEPTION) {
685 save_and_throw_exception(this_cp, cp_index, constantTag(JVM_CONSTANT_UnresolvedClass), CHECK_NULL);
686 // If CHECK_NULL above doesn't return the exception, that means that
687 // some other thread has beaten us and has resolved the class.
688 // To preserve old behavior, we return the resolved class.
689 Klass* klass = this_cp->resolved_klasses()->at(resolved_klass_index);
690 assert(klass != nullptr, "must be resolved if exception was cleared");
691 return klass;
692 }
693
694 // logging for class+resolve.
695 if (log_is_enabled(Debug, class, resolve)){
696 trace_class_resolution(this_cp, k);
697 }
698
699 // The interpreter assumes when the tag is stored, the klass is resolved
700 // and the Klass* stored in _resolved_klasses is non-null, so we need
701 // hardware store ordering here.
702 // We also need to CAS to not overwrite an error from a racing thread.
703 Klass** adr = this_cp->resolved_klasses()->adr_at(resolved_klass_index);
704 AtomicAccess::release_store(adr, k);
705
706 jbyte old_tag = AtomicAccess::cmpxchg((jbyte*)this_cp->tag_addr_at(cp_index),
707 (jbyte)JVM_CONSTANT_UnresolvedClass,
708 (jbyte)JVM_CONSTANT_Class);
709
710 // We need to recheck exceptions from racing thread and return the same.
711 if (old_tag == JVM_CONSTANT_UnresolvedClassInError) {
712 // Remove klass.
713 AtomicAccess::store(adr, (Klass*)nullptr);
714 throw_resolution_error(this_cp, cp_index, CHECK_NULL);
715 }
716
717 return k;
718 }
719
720
721 // Does not update ConstantPool* - to avoid any exception throwing. Used
722 // by compiler and exception handling. Also used to avoid classloads for
723 // instanceof operations. Returns null if the class has not been loaded or
724 // if the verification of constant pool failed
725 Klass* ConstantPool::klass_at_if_loaded(const constantPoolHandle& this_cp, int which) {
726 CPKlassSlot kslot = this_cp->klass_slot_at(which);
727 int resolved_klass_index = kslot.resolved_klass_index();
728 int name_index = kslot.name_index();
729 assert(this_cp->tag_at(name_index).is_symbol(), "sanity");
730
731 if (this_cp->tag_at(which).is_klass()) {
732 Klass* k = this_cp->resolved_klasses()->at(resolved_klass_index);
733 assert(k != nullptr, "must be resolved");
734 return k;
735 } else if (this_cp->tag_at(which).is_unresolved_klass_in_error()) {
736 return nullptr;
737 } else {
738 Thread* current = Thread::current();
739 HandleMark hm(current);
740 Symbol* name = this_cp->symbol_at(name_index);
741 oop loader = this_cp->pool_holder()->class_loader();
742 Handle h_loader (current, loader);
743 Klass* k = SystemDictionary::find_instance_klass(current, name, h_loader);
744
745 // Avoid constant pool verification at a safepoint, as it takes the Module_lock.
746 if (k != nullptr && current->is_Java_thread()) {
747 // Make sure that resolving is legal
748 JavaThread* THREAD = JavaThread::cast(current); // For exception macros.
749 ExceptionMark em(THREAD);
750 // return null if verification fails
751 verify_constant_pool_resolve(this_cp, k, THREAD);
752 if (HAS_PENDING_EXCEPTION) {
753 CLEAR_PENDING_EXCEPTION;
754 return nullptr;
755 }
756 return k;
757 } else {
758 return k;
759 }
760 }
761 }
762
763 Method* ConstantPool::method_at_if_loaded(const constantPoolHandle& cpool,
764 int which) {
765 if (cpool->cache() == nullptr) return nullptr; // nothing to load yet
766 if (!(which >= 0 && which < cpool->resolved_method_entries_length())) {
767 // FIXME: should be an assert
768 log_debug(class, resolve)("bad BSM %d in:", which); cpool->print();
769 return nullptr;
770 }
771 return cpool->cache()->method_if_resolved(which);
772 }
773
774
775 bool ConstantPool::has_appendix_at_if_loaded(const constantPoolHandle& cpool, int which, Bytecodes::Code code) {
776 if (cpool->cache() == nullptr) return false; // nothing to load yet
777 if (code == Bytecodes::_invokedynamic) {
778 return cpool->resolved_indy_entry_at(which)->has_appendix();
779 } else {
780 return cpool->resolved_method_entry_at(which)->has_appendix();
781 }
782 }
783
784 oop ConstantPool::appendix_at_if_loaded(const constantPoolHandle& cpool, int which, Bytecodes::Code code) {
785 if (cpool->cache() == nullptr) return nullptr; // nothing to load yet
786 if (code == Bytecodes::_invokedynamic) {
787 return cpool->resolved_reference_from_indy(which);
788 } else {
789 return cpool->cache()->appendix_if_resolved(which);
790 }
791 }
792
793
794 bool ConstantPool::has_local_signature_at_if_loaded(const constantPoolHandle& cpool, int which, Bytecodes::Code code) {
795 if (cpool->cache() == nullptr) return false; // nothing to load yet
796 if (code == Bytecodes::_invokedynamic) {
797 return cpool->resolved_indy_entry_at(which)->has_local_signature();
798 } else {
799 return cpool->resolved_method_entry_at(which)->has_local_signature();
800 }
801 }
802
803 // Translate index, which could be CPCache index or Indy index, to a constant pool index
804 int ConstantPool::to_cp_index(int index, Bytecodes::Code code) {
805 assert(cache() != nullptr, "'index' is a rewritten index so this class must have been rewritten");
806 switch(code) {
807 case Bytecodes::_invokedynamic:
808 return invokedynamic_bootstrap_ref_index_at(index);
809 case Bytecodes::_getfield:
810 case Bytecodes::_getstatic:
811 case Bytecodes::_putfield:
812 case Bytecodes::_putstatic:
813 return resolved_field_entry_at(index)->constant_pool_index();
814 case Bytecodes::_invokeinterface:
815 case Bytecodes::_invokehandle:
816 case Bytecodes::_invokespecial:
817 case Bytecodes::_invokestatic:
818 case Bytecodes::_invokevirtual:
819 case Bytecodes::_fast_invokevfinal: // Bytecode interpreter uses this
820 return resolved_method_entry_at(index)->constant_pool_index();
821 default:
822 fatal("Unexpected bytecode: %s", Bytecodes::name(code));
823 }
824 }
825
826 bool ConstantPool::is_resolved(int index, Bytecodes::Code code) {
827 assert(cache() != nullptr, "'index' is a rewritten index so this class must have been rewritten");
828 switch(code) {
829 case Bytecodes::_invokedynamic:
830 return resolved_indy_entry_at(index)->is_resolved();
831
832 case Bytecodes::_getfield:
833 case Bytecodes::_getstatic:
834 case Bytecodes::_putfield:
835 case Bytecodes::_putstatic:
836 return resolved_field_entry_at(index)->is_resolved(code);
837
838 case Bytecodes::_invokeinterface:
839 case Bytecodes::_invokehandle:
840 case Bytecodes::_invokespecial:
841 case Bytecodes::_invokestatic:
842 case Bytecodes::_invokevirtual:
843 case Bytecodes::_fast_invokevfinal: // Bytecode interpreter uses this
844 return resolved_method_entry_at(index)->is_resolved(code);
845
846 default:
847 fatal("Unexpected bytecode: %s", Bytecodes::name(code));
848 }
849 }
850
851 u2 ConstantPool::uncached_name_and_type_ref_index_at(int cp_index) {
852 if (tag_at(cp_index).has_bootstrap()) {
853 u2 pool_index = bootstrap_name_and_type_ref_index_at(cp_index);
854 assert(tag_at(pool_index).is_name_and_type(), "");
855 return pool_index;
856 }
857 assert(tag_at(cp_index).is_field_or_method(), "Corrupted constant pool");
858 assert(!tag_at(cp_index).has_bootstrap(), "Must be handled above");
859 jint ref_index = *int_at_addr(cp_index);
860 return extract_high_short_from_int(ref_index);
861 }
862
863 u2 ConstantPool::name_and_type_ref_index_at(int index, Bytecodes::Code code) {
864 return uncached_name_and_type_ref_index_at(to_cp_index(index, code));
865 }
866
867 constantTag ConstantPool::tag_ref_at(int which, Bytecodes::Code code) {
868 // which may be either a Constant Pool index or a rewritten index
869 int pool_index = which;
870 assert(cache() != nullptr, "'index' is a rewritten index so this class must have been rewritten");
871 pool_index = to_cp_index(which, code);
872 return tag_at(pool_index);
873 }
874
875 u2 ConstantPool::uncached_klass_ref_index_at(int cp_index) {
876 assert(tag_at(cp_index).is_field_or_method(), "Corrupted constant pool");
877 jint ref_index = *int_at_addr(cp_index);
878 return extract_low_short_from_int(ref_index);
879 }
880
881 u2 ConstantPool::klass_ref_index_at(int index, Bytecodes::Code code) {
882 assert(code != Bytecodes::_invokedynamic,
883 "an invokedynamic instruction does not have a klass");
884 return uncached_klass_ref_index_at(to_cp_index(index, code));
885 }
886
887 void ConstantPool::verify_constant_pool_resolve(const constantPoolHandle& this_cp, Klass* k, TRAPS) {
888 if (!(k->is_instance_klass() || k->is_objArray_klass())) {
889 return; // short cut, typeArray klass is always accessible
890 }
891 Klass* holder = this_cp->pool_holder();
892 LinkResolver::check_klass_accessibility(holder, k, CHECK);
893 }
894
895
896 u2 ConstantPool::name_ref_index_at(int cp_index) {
897 jint ref_index = name_and_type_at(cp_index);
898 return extract_low_short_from_int(ref_index);
899 }
900
901
902 u2 ConstantPool::signature_ref_index_at(int cp_index) {
903 jint ref_index = name_and_type_at(cp_index);
904 return extract_high_short_from_int(ref_index);
905 }
906
907
908 Klass* ConstantPool::klass_ref_at(int which, Bytecodes::Code code, TRAPS) {
909 return klass_at(klass_ref_index_at(which, code), THREAD);
910 }
911
912 Symbol* ConstantPool::klass_name_at(int cp_index) const {
913 return symbol_at(klass_slot_at(cp_index).name_index());
914 }
915
916 Symbol* ConstantPool::klass_ref_at_noresolve(int which, Bytecodes::Code code) {
917 jint ref_index = klass_ref_index_at(which, code);
918 return klass_at_noresolve(ref_index);
919 }
920
921 Symbol* ConstantPool::uncached_klass_ref_at_noresolve(int cp_index) {
922 jint ref_index = uncached_klass_ref_index_at(cp_index);
923 return klass_at_noresolve(ref_index);
924 }
925
926 char* ConstantPool::string_at_noresolve(int cp_index) {
927 return unresolved_string_at(cp_index)->as_C_string();
928 }
929
930 BasicType ConstantPool::basic_type_for_signature_at(int cp_index) const {
931 return Signature::basic_type(symbol_at(cp_index));
932 }
933
934
935 void ConstantPool::resolve_string_constants_impl(const constantPoolHandle& this_cp, TRAPS) {
936 for (int index = 1; index < this_cp->length(); index++) { // Index 0 is unused
937 if (this_cp->tag_at(index).is_string()) {
938 this_cp->string_at(index, CHECK);
939 }
940 }
941 }
942
943 static const char* exception_message(const constantPoolHandle& this_cp, int which, constantTag tag, oop pending_exception) {
944 // Note: caller needs ResourceMark
945
946 // Dig out the detailed message to reuse if possible
947 const char* msg = java_lang_Throwable::message_as_utf8(pending_exception);
948 if (msg != nullptr) {
949 return msg;
950 }
951
952 Symbol* message = nullptr;
953 // Return specific message for the tag
954 switch (tag.value()) {
955 case JVM_CONSTANT_UnresolvedClass:
956 // return the class name in the error message
957 message = this_cp->klass_name_at(which);
958 break;
959 case JVM_CONSTANT_MethodHandle:
960 // return the method handle name in the error message
961 message = this_cp->method_handle_name_ref_at(which);
962 break;
963 case JVM_CONSTANT_MethodType:
964 // return the method type signature in the error message
965 message = this_cp->method_type_signature_at(which);
966 break;
967 case JVM_CONSTANT_Dynamic:
968 // return the name of the condy in the error message
969 message = this_cp->uncached_name_ref_at(which);
970 break;
971 default:
972 ShouldNotReachHere();
973 }
974
975 return message != nullptr ? message->as_C_string() : nullptr;
976 }
977
978 static void add_resolution_error(JavaThread* current, const constantPoolHandle& this_cp, int which,
979 constantTag tag, oop pending_exception) {
980
981 ResourceMark rm(current);
982 Symbol* error = pending_exception->klass()->name();
983 oop cause = java_lang_Throwable::cause(pending_exception);
984
985 // Also dig out the exception cause, if present.
986 Symbol* cause_sym = nullptr;
987 const char* cause_msg = nullptr;
988 if (cause != nullptr && cause != pending_exception) {
989 cause_sym = cause->klass()->name();
990 cause_msg = java_lang_Throwable::message_as_utf8(cause);
991 }
992
993 const char* message = exception_message(this_cp, which, tag, pending_exception);
994 SystemDictionary::add_resolution_error(this_cp, which, error, message, cause_sym, cause_msg);
995 }
996
997
998 void ConstantPool::throw_resolution_error(const constantPoolHandle& this_cp, int which, TRAPS) {
999 ResourceMark rm(THREAD);
1000 const char* message = nullptr;
1001 Symbol* cause = nullptr;
1002 const char* cause_msg = nullptr;
1003 Symbol* error = SystemDictionary::find_resolution_error(this_cp, which, &message, &cause, &cause_msg);
1004 assert(error != nullptr, "checking");
1005
1006 CLEAR_PENDING_EXCEPTION;
1007 if (message != nullptr) {
1008 if (cause != nullptr) {
1009 Handle h_cause = Exceptions::new_exception(THREAD, cause, cause_msg);
1010 THROW_MSG_CAUSE(error, message, h_cause);
1011 } else {
1012 THROW_MSG(error, message);
1013 }
1014 } else {
1015 if (cause != nullptr) {
1016 Handle h_cause = Exceptions::new_exception(THREAD, cause, cause_msg);
1017 THROW_CAUSE(error, h_cause);
1018 } else {
1019 THROW(error);
1020 }
1021 }
1022 }
1023
1024 // If resolution for Class, Dynamic constant, MethodHandle or MethodType fails, save the
1025 // exception in the resolution error table, so that the same exception is thrown again.
1026 void ConstantPool::save_and_throw_exception(const constantPoolHandle& this_cp, int cp_index,
1027 constantTag tag, TRAPS) {
1028
1029 int error_tag = tag.error_value();
1030
1031 if (!PENDING_EXCEPTION->
1032 is_a(vmClasses::LinkageError_klass())) {
1033 // Just throw the exception and don't prevent these classes from
1034 // being loaded due to virtual machine errors like StackOverflow
1035 // and OutOfMemoryError, etc, or if the thread was hit by stop()
1036 // Needs clarification to section 5.4.3 of the VM spec (see 6308271)
1037 } else if (this_cp->tag_at(cp_index).value() != error_tag) {
1038 add_resolution_error(THREAD, this_cp, cp_index, tag, PENDING_EXCEPTION);
1039 // CAS in the tag. If a thread beat us to registering this error that's fine.
1040 // If another thread resolved the reference, this is a race condition. This
1041 // thread may have had a security manager or something temporary.
1042 // This doesn't deterministically get an error. So why do we save this?
1043 // We save this because jvmti can add classes to the bootclass path after
1044 // this error, so it needs to get the same error if the error is first.
1045 jbyte old_tag = AtomicAccess::cmpxchg((jbyte*)this_cp->tag_addr_at(cp_index),
1046 (jbyte)tag.value(),
1047 (jbyte)error_tag);
1048 if (old_tag != error_tag && old_tag != tag.value()) {
1049 // MethodHandles and MethodType doesn't change to resolved version.
1050 assert(this_cp->tag_at(cp_index).is_klass(), "Wrong tag value");
1051 // Forget the exception and use the resolved class.
1052 CLEAR_PENDING_EXCEPTION;
1053 }
1054 } else {
1055 // some other thread put this in error state
1056 throw_resolution_error(this_cp, cp_index, CHECK);
1057 }
1058 }
1059
1060 constantTag ConstantPool::constant_tag_at(int cp_index) {
1061 constantTag tag = tag_at(cp_index);
1062 if (tag.is_dynamic_constant()) {
1063 BasicType bt = basic_type_for_constant_at(cp_index);
1064 return constantTag(constantTag::type2tag(bt));
1065 }
1066 return tag;
1067 }
1068
1069 BasicType ConstantPool::basic_type_for_constant_at(int cp_index) {
1070 constantTag tag = tag_at(cp_index);
1071 if (tag.is_dynamic_constant() ||
1072 tag.is_dynamic_constant_in_error()) {
1073 // have to look at the signature for this one
1074 Symbol* constant_type = uncached_signature_ref_at(cp_index);
1075 return Signature::basic_type(constant_type);
1076 }
1077 return tag.basic_type();
1078 }
1079
1080 // Called to resolve constants in the constant pool and return an oop.
1081 // Some constant pool entries cache their resolved oop. This is also
1082 // called to create oops from constants to use in arguments for invokedynamic
1083 oop ConstantPool::resolve_constant_at_impl(const constantPoolHandle& this_cp,
1084 int cp_index, int cache_index,
1085 bool* status_return, TRAPS) {
1086 oop result_oop = nullptr;
1087
1088 if (cache_index == _possible_index_sentinel) {
1089 // It is possible that this constant is one which is cached in the objects.
1090 // We'll do a linear search. This should be OK because this usage is rare.
1091 // FIXME: If bootstrap specifiers stress this code, consider putting in
1092 // a reverse index. Binary search over a short array should do it.
1093 assert(cp_index > 0, "valid constant pool index");
1094 cache_index = this_cp->cp_to_object_index(cp_index);
1095 }
1096 assert(cache_index == _no_index_sentinel || cache_index >= 0, "");
1097 assert(cp_index == _no_index_sentinel || cp_index >= 0, "");
1098
1099 if (cache_index >= 0) {
1100 result_oop = this_cp->resolved_reference_at(cache_index);
1101 if (result_oop != nullptr) {
1102 if (result_oop == Universe::the_null_sentinel()) {
1103 DEBUG_ONLY(int temp_index = (cp_index >= 0 ? cp_index : this_cp->object_to_cp_index(cache_index)));
1104 assert(this_cp->tag_at(temp_index).is_dynamic_constant(), "only condy uses the null sentinel");
1105 result_oop = nullptr;
1106 }
1107 if (status_return != nullptr) (*status_return) = true;
1108 return result_oop;
1109 // That was easy...
1110 }
1111 cp_index = this_cp->object_to_cp_index(cache_index);
1112 }
1113
1114 jvalue prim_value; // temp used only in a few cases below
1115
1116 constantTag tag = this_cp->tag_at(cp_index);
1117
1118 if (status_return != nullptr) {
1119 // don't trigger resolution if the constant might need it
1120 switch (tag.value()) {
1121 case JVM_CONSTANT_Class:
1122 assert(this_cp->resolved_klass_at(cp_index) != nullptr, "must be resolved");
1123 break;
1124 case JVM_CONSTANT_String:
1125 case JVM_CONSTANT_Integer:
1126 case JVM_CONSTANT_Float:
1127 case JVM_CONSTANT_Long:
1128 case JVM_CONSTANT_Double:
1129 // these guys trigger OOM at worst
1130 break;
1131 default:
1132 (*status_return) = false;
1133 return nullptr;
1134 }
1135 // from now on there is either success or an OOME
1136 (*status_return) = true;
1137 }
1138
1139 switch (tag.value()) {
1140
1141 case JVM_CONSTANT_UnresolvedClass:
1142 case JVM_CONSTANT_Class:
1143 {
1144 assert(cache_index == _no_index_sentinel, "should not have been set");
1145 Klass* resolved = klass_at_impl(this_cp, cp_index, CHECK_NULL);
1146 // ldc wants the java mirror.
1147 result_oop = resolved->java_mirror();
1148 break;
1149 }
1150
1151 case JVM_CONSTANT_Dynamic:
1152 { PerfTraceTimedEvent timer(ClassLoader::perf_resolve_invokedynamic_time(),
1153 ClassLoader::perf_resolve_invokedynamic_count());
1154
1155 // Resolve the Dynamically-Computed constant to invoke the BSM in order to obtain the resulting oop.
1156 BootstrapInfo bootstrap_specifier(this_cp, cp_index);
1157
1158 // The initial step in resolving an unresolved symbolic reference to a
1159 // dynamically-computed constant is to resolve the symbolic reference to a
1160 // method handle which will be the bootstrap method for the dynamically-computed
1161 // constant. If resolution of the java.lang.invoke.MethodHandle for the bootstrap
1162 // method fails, then a MethodHandleInError is stored at the corresponding
1163 // bootstrap method's CP index for the CONSTANT_MethodHandle_info. No need to
1164 // set a DynamicConstantInError here since any subsequent use of this
1165 // bootstrap method will encounter the resolution of MethodHandleInError.
1166 // Both the first, (resolution of the BSM and its static arguments), and the second tasks,
1167 // (invocation of the BSM), of JVMS Section 5.4.3.6 occur within invoke_bootstrap_method()
1168 // for the bootstrap_specifier created above.
1169 SystemDictionary::invoke_bootstrap_method(bootstrap_specifier, THREAD);
1170 Exceptions::wrap_dynamic_exception(/* is_indy */ false, THREAD);
1171 if (HAS_PENDING_EXCEPTION) {
1172 // Resolution failure of the dynamically-computed constant, save_and_throw_exception
1173 // will check for a LinkageError and store a DynamicConstantInError.
1174 save_and_throw_exception(this_cp, cp_index, tag, CHECK_NULL);
1175 }
1176 result_oop = bootstrap_specifier.resolved_value()();
1177 BasicType type = Signature::basic_type(bootstrap_specifier.signature());
1178 if (!is_reference_type(type)) {
1179 // Make sure the primitive value is properly boxed.
1180 // This is a JDK responsibility.
1181 const char* fail = nullptr;
1182 if (result_oop == nullptr) {
1183 fail = "null result instead of box";
1184 } else if (!is_java_primitive(type)) {
1185 // FIXME: support value types via unboxing
1186 fail = "can only handle references and primitives";
1187 } else if (!java_lang_boxing_object::is_instance(result_oop, type)) {
1188 fail = "primitive is not properly boxed";
1189 }
1190 if (fail != nullptr) {
1191 // Since this exception is not a LinkageError, throw exception
1192 // but do not save a DynamicInError resolution result.
1193 // See section 5.4.3 of the VM spec.
1194 THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), fail);
1195 }
1196 }
1197
1198 LogTarget(Debug, methodhandles, condy) lt_condy;
1199 if (lt_condy.is_enabled()) {
1200 LogStream ls(lt_condy);
1201 bootstrap_specifier.print_msg_on(&ls, "resolve_constant_at_impl");
1202 }
1203 break;
1204 }
1205
1206 case JVM_CONSTANT_String:
1207 assert(cache_index != _no_index_sentinel, "should have been set");
1208 result_oop = string_at_impl(this_cp, cp_index, cache_index, CHECK_NULL);
1209 break;
1210
1211 case JVM_CONSTANT_MethodHandle:
1212 { PerfTraceTimedEvent timer(ClassLoader::perf_resolve_method_handle_time(),
1213 ClassLoader::perf_resolve_method_handle_count());
1214
1215 int ref_kind = this_cp->method_handle_ref_kind_at(cp_index);
1216 int callee_index = this_cp->method_handle_klass_index_at(cp_index);
1217 Symbol* name = this_cp->method_handle_name_ref_at(cp_index);
1218 Symbol* signature = this_cp->method_handle_signature_ref_at(cp_index);
1219 constantTag m_tag = this_cp->tag_at(this_cp->method_handle_index_at(cp_index));
1220 { ResourceMark rm(THREAD);
1221 log_debug(class, resolve)("resolve JVM_CONSTANT_MethodHandle:%d [%d/%d/%d] %s.%s",
1222 ref_kind, cp_index, this_cp->method_handle_index_at(cp_index),
1223 callee_index, name->as_C_string(), signature->as_C_string());
1224 }
1225
1226 Klass* callee = klass_at_impl(this_cp, callee_index, THREAD);
1227 if (HAS_PENDING_EXCEPTION) {
1228 save_and_throw_exception(this_cp, cp_index, tag, CHECK_NULL);
1229 }
1230
1231 // Check constant pool method consistency
1232 if ((callee->is_interface() && m_tag.is_method()) ||
1233 (!callee->is_interface() && m_tag.is_interface_method())) {
1234 ResourceMark rm(THREAD);
1235 stringStream ss;
1236 ss.print("Inconsistent constant pool data in classfile for class %s. "
1237 "Method '", callee->name()->as_C_string());
1238 signature->print_as_signature_external_return_type(&ss);
1239 ss.print(" %s(", name->as_C_string());
1240 signature->print_as_signature_external_parameters(&ss);
1241 ss.print(")' at index %d is %s and should be %s",
1242 cp_index,
1243 callee->is_interface() ? "CONSTANT_MethodRef" : "CONSTANT_InterfaceMethodRef",
1244 callee->is_interface() ? "CONSTANT_InterfaceMethodRef" : "CONSTANT_MethodRef");
1245 // Names are all known to be < 64k so we know this formatted message is not excessively large.
1246 Exceptions::fthrow(THREAD_AND_LOCATION, vmSymbols::java_lang_IncompatibleClassChangeError(), "%s", ss.as_string());
1247 save_and_throw_exception(this_cp, cp_index, tag, CHECK_NULL);
1248 }
1249
1250 Klass* klass = this_cp->pool_holder();
1251 HandleMark hm(THREAD);
1252 Handle value = SystemDictionary::link_method_handle_constant(klass, ref_kind,
1253 callee, name, signature,
1254 THREAD);
1255 if (HAS_PENDING_EXCEPTION) {
1256 save_and_throw_exception(this_cp, cp_index, tag, CHECK_NULL);
1257 }
1258 result_oop = value();
1259 break;
1260 }
1261
1262 case JVM_CONSTANT_MethodType:
1263 { PerfTraceTimedEvent timer(ClassLoader::perf_resolve_method_type_time(),
1264 ClassLoader::perf_resolve_method_type_count());
1265
1266 Symbol* signature = this_cp->method_type_signature_at(cp_index);
1267 { ResourceMark rm(THREAD);
1268 log_debug(class, resolve)("resolve JVM_CONSTANT_MethodType [%d/%d] %s",
1269 cp_index, this_cp->method_type_index_at(cp_index),
1270 signature->as_C_string());
1271 }
1272 Klass* klass = this_cp->pool_holder();
1273 HandleMark hm(THREAD);
1274 Handle value = SystemDictionary::find_method_handle_type(signature, klass, THREAD);
1275 result_oop = value();
1276 if (HAS_PENDING_EXCEPTION) {
1277 save_and_throw_exception(this_cp, cp_index, tag, CHECK_NULL);
1278 }
1279 break;
1280 }
1281
1282 case JVM_CONSTANT_Integer:
1283 assert(cache_index == _no_index_sentinel, "should not have been set");
1284 prim_value.i = this_cp->int_at(cp_index);
1285 result_oop = java_lang_boxing_object::create(T_INT, &prim_value, CHECK_NULL);
1286 break;
1287
1288 case JVM_CONSTANT_Float:
1289 assert(cache_index == _no_index_sentinel, "should not have been set");
1290 prim_value.f = this_cp->float_at(cp_index);
1291 result_oop = java_lang_boxing_object::create(T_FLOAT, &prim_value, CHECK_NULL);
1292 break;
1293
1294 case JVM_CONSTANT_Long:
1295 assert(cache_index == _no_index_sentinel, "should not have been set");
1296 prim_value.j = this_cp->long_at(cp_index);
1297 result_oop = java_lang_boxing_object::create(T_LONG, &prim_value, CHECK_NULL);
1298 break;
1299
1300 case JVM_CONSTANT_Double:
1301 assert(cache_index == _no_index_sentinel, "should not have been set");
1302 prim_value.d = this_cp->double_at(cp_index);
1303 result_oop = java_lang_boxing_object::create(T_DOUBLE, &prim_value, CHECK_NULL);
1304 break;
1305
1306 case JVM_CONSTANT_UnresolvedClassInError:
1307 case JVM_CONSTANT_DynamicInError:
1308 case JVM_CONSTANT_MethodHandleInError:
1309 case JVM_CONSTANT_MethodTypeInError:
1310 throw_resolution_error(this_cp, cp_index, CHECK_NULL);
1311 break;
1312
1313 default:
1314 fatal("unexpected constant tag at CP %p[%d/%d] = %d", this_cp(), cp_index, cache_index, tag.value());
1315 break;
1316 }
1317
1318 if (cache_index >= 0) {
1319 // Benign race condition: resolved_references may already be filled in.
1320 // The important thing here is that all threads pick up the same result.
1321 // It doesn't matter which racing thread wins, as long as only one
1322 // result is used by all threads, and all future queries.
1323 oop new_result = (result_oop == nullptr ? Universe::the_null_sentinel() : result_oop);
1324 oop old_result = this_cp->set_resolved_reference_at(cache_index, new_result);
1325 if (old_result == nullptr) {
1326 return result_oop; // was installed
1327 } else {
1328 // Return the winning thread's result. This can be different than
1329 // the result here for MethodHandles.
1330 if (old_result == Universe::the_null_sentinel())
1331 old_result = nullptr;
1332 return old_result;
1333 }
1334 } else {
1335 assert(result_oop != Universe::the_null_sentinel(), "");
1336 return result_oop;
1337 }
1338 }
1339
1340 oop ConstantPool::uncached_string_at(int cp_index, TRAPS) {
1341 Symbol* sym = unresolved_string_at(cp_index);
1342 oop str = StringTable::intern(sym, CHECK_(nullptr));
1343 assert(java_lang_String::is_instance(str), "must be string");
1344 return str;
1345 }
1346
1347 void ConstantPool::copy_bootstrap_arguments_at_impl(const constantPoolHandle& this_cp, int cp_index,
1348 int start_arg, int end_arg,
1349 objArrayHandle info, int pos,
1350 bool must_resolve, Handle if_not_available,
1351 TRAPS) {
1352 int limit = pos + end_arg - start_arg;
1353 // checks: cp_index in range [0..this_cp->length),
1354 // tag at cp_index, start..end in range [0..this_cp->bootstrap_argument_count],
1355 // info array non-null, pos..limit in [0..info.length]
1356 if ((0 >= cp_index || cp_index >= this_cp->length()) ||
1357 !(this_cp->tag_at(cp_index).is_invoke_dynamic() ||
1358 this_cp->tag_at(cp_index).is_dynamic_constant()) ||
1359 (0 > start_arg || start_arg > end_arg) ||
1360 (end_arg > this_cp->bootstrap_argument_count_at(cp_index)) ||
1361 (0 > pos || pos > limit) ||
1362 (info.is_null() || limit > info->length())) {
1363 // An index or something else went wrong; throw an error.
1364 // Since this is an internal API, we don't expect this,
1365 // so we don't bother to craft a nice message.
1366 THROW_MSG(vmSymbols::java_lang_LinkageError(), "bad BSM argument access");
1367 }
1368 // now we can loop safely
1369 int info_i = pos;
1370 for (int i = start_arg; i < end_arg; i++) {
1371 int arg_index = this_cp->bootstrap_argument_index_at(cp_index, i);
1372 oop arg_oop;
1373 if (must_resolve) {
1374 arg_oop = this_cp->resolve_possibly_cached_constant_at(arg_index, CHECK);
1375 } else {
1376 bool found_it = false;
1377 arg_oop = this_cp->find_cached_constant_at(arg_index, found_it, CHECK);
1378 if (!found_it) arg_oop = if_not_available();
1379 }
1380 info->obj_at_put(info_i++, arg_oop);
1381 }
1382 }
1383
1384 oop ConstantPool::string_at_impl(const constantPoolHandle& this_cp, int cp_index, int obj_index, TRAPS) {
1385 // If the string has already been interned, this entry will be non-null
1386 oop str = this_cp->resolved_reference_at(obj_index);
1387 assert(str != Universe::the_null_sentinel(), "");
1388 if (str != nullptr) return str;
1389 Symbol* sym = this_cp->unresolved_string_at(cp_index);
1390 str = StringTable::intern(sym, CHECK_(nullptr));
1391 this_cp->string_at_put(obj_index, str);
1392 assert(java_lang_String::is_instance(str), "must be string");
1393 return str;
1394 }
1395
1396
1397 bool ConstantPool::klass_name_at_matches(const InstanceKlass* k, int cp_index) {
1398 // Names are interned, so we can compare Symbol*s directly
1399 Symbol* cp_name = klass_name_at(cp_index);
1400 return (cp_name == k->name());
1401 }
1402
1403
1404 // Iterate over symbols and decrement ones which are Symbol*s
1405 // This is done during GC.
1406 // Only decrement the UTF8 symbols. Strings point to
1407 // these symbols but didn't increment the reference count.
1408 void ConstantPool::unreference_symbols() {
1409 for (int index = 1; index < length(); index++) { // Index 0 is unused
1410 constantTag tag = tag_at(index);
1411 if (tag.is_symbol()) {
1412 symbol_at(index)->decrement_refcount();
1413 }
1414 }
1415 }
1416
1417
1418 // Compare this constant pool's entry at index1 to the constant pool
1419 // cp2's entry at index2.
1420 bool ConstantPool::compare_entry_to(int index1, const constantPoolHandle& cp2,
1421 int index2) {
1422
1423 // The error tags are equivalent to non-error tags when comparing
1424 jbyte t1 = tag_at(index1).non_error_value();
1425 jbyte t2 = cp2->tag_at(index2).non_error_value();
1426
1427 // Some classes are pre-resolved (like Throwable) which may lead to
1428 // consider it as a different entry. We then revert them back temporarily
1429 // to ensure proper comparison.
1430 if (t1 == JVM_CONSTANT_Class) {
1431 t1 = JVM_CONSTANT_UnresolvedClass;
1432 }
1433 if (t2 == JVM_CONSTANT_Class) {
1434 t2 = JVM_CONSTANT_UnresolvedClass;
1435 }
1436
1437 if (t1 != t2) {
1438 // Not the same entry type so there is nothing else to check. Note
1439 // that this style of checking will consider resolved/unresolved
1440 // class pairs as different.
1441 // From the ConstantPool* API point of view, this is correct
1442 // behavior. See VM_RedefineClasses::merge_constant_pools() to see how this
1443 // plays out in the context of ConstantPool* merging.
1444 return false;
1445 }
1446
1447 switch (t1) {
1448 case JVM_CONSTANT_ClassIndex:
1449 {
1450 int recur1 = klass_index_at(index1);
1451 int recur2 = cp2->klass_index_at(index2);
1452 if (compare_entry_to(recur1, cp2, recur2)) {
1453 return true;
1454 }
1455 } break;
1456
1457 case JVM_CONSTANT_Double:
1458 {
1459 jdouble d1 = double_at(index1);
1460 jdouble d2 = cp2->double_at(index2);
1461 if (d1 == d2) {
1462 return true;
1463 }
1464 } break;
1465
1466 case JVM_CONSTANT_Fieldref:
1467 case JVM_CONSTANT_InterfaceMethodref:
1468 case JVM_CONSTANT_Methodref:
1469 {
1470 int recur1 = uncached_klass_ref_index_at(index1);
1471 int recur2 = cp2->uncached_klass_ref_index_at(index2);
1472 bool match = compare_entry_to(recur1, cp2, recur2);
1473 if (match) {
1474 recur1 = uncached_name_and_type_ref_index_at(index1);
1475 recur2 = cp2->uncached_name_and_type_ref_index_at(index2);
1476 if (compare_entry_to(recur1, cp2, recur2)) {
1477 return true;
1478 }
1479 }
1480 } break;
1481
1482 case JVM_CONSTANT_Float:
1483 {
1484 jfloat f1 = float_at(index1);
1485 jfloat f2 = cp2->float_at(index2);
1486 if (f1 == f2) {
1487 return true;
1488 }
1489 } break;
1490
1491 case JVM_CONSTANT_Integer:
1492 {
1493 jint i1 = int_at(index1);
1494 jint i2 = cp2->int_at(index2);
1495 if (i1 == i2) {
1496 return true;
1497 }
1498 } break;
1499
1500 case JVM_CONSTANT_Long:
1501 {
1502 jlong l1 = long_at(index1);
1503 jlong l2 = cp2->long_at(index2);
1504 if (l1 == l2) {
1505 return true;
1506 }
1507 } break;
1508
1509 case JVM_CONSTANT_NameAndType:
1510 {
1511 int recur1 = name_ref_index_at(index1);
1512 int recur2 = cp2->name_ref_index_at(index2);
1513 if (compare_entry_to(recur1, cp2, recur2)) {
1514 recur1 = signature_ref_index_at(index1);
1515 recur2 = cp2->signature_ref_index_at(index2);
1516 if (compare_entry_to(recur1, cp2, recur2)) {
1517 return true;
1518 }
1519 }
1520 } break;
1521
1522 case JVM_CONSTANT_StringIndex:
1523 {
1524 int recur1 = string_index_at(index1);
1525 int recur2 = cp2->string_index_at(index2);
1526 if (compare_entry_to(recur1, cp2, recur2)) {
1527 return true;
1528 }
1529 } break;
1530
1531 case JVM_CONSTANT_UnresolvedClass:
1532 {
1533 Symbol* k1 = klass_name_at(index1);
1534 Symbol* k2 = cp2->klass_name_at(index2);
1535 if (k1 == k2) {
1536 return true;
1537 }
1538 } break;
1539
1540 case JVM_CONSTANT_MethodType:
1541 {
1542 int k1 = method_type_index_at(index1);
1543 int k2 = cp2->method_type_index_at(index2);
1544 if (compare_entry_to(k1, cp2, k2)) {
1545 return true;
1546 }
1547 } break;
1548
1549 case JVM_CONSTANT_MethodHandle:
1550 {
1551 int k1 = method_handle_ref_kind_at(index1);
1552 int k2 = cp2->method_handle_ref_kind_at(index2);
1553 if (k1 == k2) {
1554 int i1 = method_handle_index_at(index1);
1555 int i2 = cp2->method_handle_index_at(index2);
1556 if (compare_entry_to(i1, cp2, i2)) {
1557 return true;
1558 }
1559 }
1560 } break;
1561
1562 case JVM_CONSTANT_Dynamic:
1563 {
1564 int k1 = bootstrap_name_and_type_ref_index_at(index1);
1565 int k2 = cp2->bootstrap_name_and_type_ref_index_at(index2);
1566 int i1 = bootstrap_methods_attribute_index(index1);
1567 int i2 = cp2->bootstrap_methods_attribute_index(index2);
1568 bool match_entry = compare_entry_to(k1, cp2, k2);
1569 bool match_bsm = compare_bootstrap_entry_to(i1, cp2, i2);
1570 return (match_entry && match_bsm);
1571 } break;
1572
1573 case JVM_CONSTANT_InvokeDynamic:
1574 {
1575 int k1 = bootstrap_name_and_type_ref_index_at(index1);
1576 int k2 = cp2->bootstrap_name_and_type_ref_index_at(index2);
1577 int i1 = bootstrap_methods_attribute_index(index1);
1578 int i2 = cp2->bootstrap_methods_attribute_index(index2);
1579 bool match_entry = compare_entry_to(k1, cp2, k2);
1580 bool match_bsm = compare_bootstrap_entry_to(i1, cp2, i2);
1581 return (match_entry && match_bsm);
1582 } break;
1583
1584 case JVM_CONSTANT_String:
1585 {
1586 Symbol* s1 = unresolved_string_at(index1);
1587 Symbol* s2 = cp2->unresolved_string_at(index2);
1588 if (s1 == s2) {
1589 return true;
1590 }
1591 } break;
1592
1593 case JVM_CONSTANT_Utf8:
1594 {
1595 Symbol* s1 = symbol_at(index1);
1596 Symbol* s2 = cp2->symbol_at(index2);
1597 if (s1 == s2) {
1598 return true;
1599 }
1600 } break;
1601
1602 // Invalid is used as the tag for the second constant pool entry
1603 // occupied by JVM_CONSTANT_Double or JVM_CONSTANT_Long. It should
1604 // not be seen by itself.
1605 case JVM_CONSTANT_Invalid: // fall through
1606
1607 default:
1608 ShouldNotReachHere();
1609 break;
1610 }
1611
1612 return false;
1613 } // end compare_entry_to()
1614
1615 // Extend the BSMAttributeEntries with the length and size of the ext_cp BSMAttributeEntries.
1616 // Used in RedefineClasses for CP merge.
1617 BSMAttributeEntries::InsertionIterator
1618 ConstantPool::start_extension(const constantPoolHandle& ext_cp, TRAPS) {
1619 BSMAttributeEntries::InsertionIterator iter =
1620 bsm_entries().start_extension(ext_cp->bsm_entries(), pool_holder()->class_loader_data(),
1621 CHECK_(BSMAttributeEntries::InsertionIterator()));
1622 return iter;
1623 }
1624
1625
1626 void ConstantPool::end_extension(BSMAttributeEntries::InsertionIterator iter, TRAPS) {
1627 bsm_entries().end_extension(iter, pool_holder()->class_loader_data(), THREAD);
1628 }
1629
1630
1631 void ConstantPool::copy_bsm_entries(const constantPoolHandle& from_cp,
1632 const constantPoolHandle& to_cp,
1633 TRAPS) {
1634 to_cp->bsm_entries().append(from_cp->bsm_entries(),
1635 to_cp->pool_holder()->class_loader_data(),
1636 THREAD);
1637 }
1638
1639
1640 // Copy this constant pool's entries at start_i to end_i (inclusive)
1641 // to the constant pool to_cp's entries starting at to_i. A total of
1642 // (end_i - start_i) + 1 entries are copied.
1643 void ConstantPool::copy_cp_to_impl(const constantPoolHandle& from_cp, int start_i, int end_i,
1644 const constantPoolHandle& to_cp, int to_i, TRAPS) {
1645
1646
1647 int dest_cpi = to_i; // leave original alone for debug purposes
1648
1649 for (int src_cpi = start_i; src_cpi <= end_i; /* see loop bottom */ ) {
1650 copy_entry_to(from_cp, src_cpi, to_cp, dest_cpi);
1651
1652 switch (from_cp->tag_at(src_cpi).value()) {
1653 case JVM_CONSTANT_Double:
1654 case JVM_CONSTANT_Long:
1655 // double and long take two constant pool entries
1656 src_cpi += 2;
1657 dest_cpi += 2;
1658 break;
1659
1660 default:
1661 // all others take one constant pool entry
1662 src_cpi++;
1663 dest_cpi++;
1664 break;
1665 }
1666 }
1667 copy_bsm_entries(from_cp, to_cp, THREAD);
1668
1669 } // end copy_cp_to_impl()
1670
1671
1672 // Copy this constant pool's entry at from_i to the constant pool
1673 // to_cp's entry at to_i.
1674 void ConstantPool::copy_entry_to(const constantPoolHandle& from_cp, int from_i,
1675 const constantPoolHandle& to_cp, int to_i) {
1676
1677 int tag = from_cp->tag_at(from_i).value();
1678 switch (tag) {
1679 case JVM_CONSTANT_ClassIndex:
1680 {
1681 jint ki = from_cp->klass_index_at(from_i);
1682 to_cp->klass_index_at_put(to_i, ki);
1683 } break;
1684
1685 case JVM_CONSTANT_Double:
1686 {
1687 jdouble d = from_cp->double_at(from_i);
1688 to_cp->double_at_put(to_i, d);
1689 // double takes two constant pool entries so init second entry's tag
1690 to_cp->tag_at_put(to_i + 1, JVM_CONSTANT_Invalid);
1691 } break;
1692
1693 case JVM_CONSTANT_Fieldref:
1694 {
1695 int class_index = from_cp->uncached_klass_ref_index_at(from_i);
1696 int name_and_type_index = from_cp->uncached_name_and_type_ref_index_at(from_i);
1697 to_cp->field_at_put(to_i, class_index, name_and_type_index);
1698 } break;
1699
1700 case JVM_CONSTANT_Float:
1701 {
1702 jfloat f = from_cp->float_at(from_i);
1703 to_cp->float_at_put(to_i, f);
1704 } break;
1705
1706 case JVM_CONSTANT_Integer:
1707 {
1708 jint i = from_cp->int_at(from_i);
1709 to_cp->int_at_put(to_i, i);
1710 } break;
1711
1712 case JVM_CONSTANT_InterfaceMethodref:
1713 {
1714 int class_index = from_cp->uncached_klass_ref_index_at(from_i);
1715 int name_and_type_index = from_cp->uncached_name_and_type_ref_index_at(from_i);
1716 to_cp->interface_method_at_put(to_i, class_index, name_and_type_index);
1717 } break;
1718
1719 case JVM_CONSTANT_Long:
1720 {
1721 jlong l = from_cp->long_at(from_i);
1722 to_cp->long_at_put(to_i, l);
1723 // long takes two constant pool entries so init second entry's tag
1724 to_cp->tag_at_put(to_i + 1, JVM_CONSTANT_Invalid);
1725 } break;
1726
1727 case JVM_CONSTANT_Methodref:
1728 {
1729 int class_index = from_cp->uncached_klass_ref_index_at(from_i);
1730 int name_and_type_index = from_cp->uncached_name_and_type_ref_index_at(from_i);
1731 to_cp->method_at_put(to_i, class_index, name_and_type_index);
1732 } break;
1733
1734 case JVM_CONSTANT_NameAndType:
1735 {
1736 int name_ref_index = from_cp->name_ref_index_at(from_i);
1737 int signature_ref_index = from_cp->signature_ref_index_at(from_i);
1738 to_cp->name_and_type_at_put(to_i, name_ref_index, signature_ref_index);
1739 } break;
1740
1741 case JVM_CONSTANT_StringIndex:
1742 {
1743 jint si = from_cp->string_index_at(from_i);
1744 to_cp->string_index_at_put(to_i, si);
1745 } break;
1746
1747 case JVM_CONSTANT_Class:
1748 case JVM_CONSTANT_UnresolvedClass:
1749 case JVM_CONSTANT_UnresolvedClassInError:
1750 {
1751 // Revert to JVM_CONSTANT_ClassIndex
1752 int name_index = from_cp->klass_slot_at(from_i).name_index();
1753 assert(from_cp->tag_at(name_index).is_symbol(), "sanity");
1754 to_cp->klass_index_at_put(to_i, name_index);
1755 } break;
1756
1757 case JVM_CONSTANT_String:
1758 {
1759 Symbol* s = from_cp->unresolved_string_at(from_i);
1760 to_cp->unresolved_string_at_put(to_i, s);
1761 } break;
1762
1763 case JVM_CONSTANT_Utf8:
1764 {
1765 Symbol* s = from_cp->symbol_at(from_i);
1766 // Need to increase refcount, the old one will be thrown away and deferenced
1767 s->increment_refcount();
1768 to_cp->symbol_at_put(to_i, s);
1769 } break;
1770
1771 case JVM_CONSTANT_MethodType:
1772 case JVM_CONSTANT_MethodTypeInError:
1773 {
1774 jint k = from_cp->method_type_index_at(from_i);
1775 to_cp->method_type_index_at_put(to_i, k);
1776 } break;
1777
1778 case JVM_CONSTANT_MethodHandle:
1779 case JVM_CONSTANT_MethodHandleInError:
1780 {
1781 int k1 = from_cp->method_handle_ref_kind_at(from_i);
1782 int k2 = from_cp->method_handle_index_at(from_i);
1783 to_cp->method_handle_index_at_put(to_i, k1, k2);
1784 } break;
1785
1786 case JVM_CONSTANT_Dynamic:
1787 case JVM_CONSTANT_DynamicInError:
1788 {
1789 int k1 = from_cp->bootstrap_methods_attribute_index(from_i);
1790 int k2 = from_cp->bootstrap_name_and_type_ref_index_at(from_i);
1791 k1 += to_cp->bsm_entries().array_length(); // to_cp might already have a BSM attribute
1792 to_cp->dynamic_constant_at_put(to_i, k1, k2);
1793 } break;
1794
1795 case JVM_CONSTANT_InvokeDynamic:
1796 {
1797 int k1 = from_cp->bootstrap_methods_attribute_index(from_i);
1798 int k2 = from_cp->bootstrap_name_and_type_ref_index_at(from_i);
1799 k1 += to_cp->bsm_entries().array_length(); // to_cp might already have a BSM attribute
1800 to_cp->invoke_dynamic_at_put(to_i, k1, k2);
1801 } break;
1802
1803 // Invalid is used as the tag for the second constant pool entry
1804 // occupied by JVM_CONSTANT_Double or JVM_CONSTANT_Long. It should
1805 // not be seen by itself.
1806 case JVM_CONSTANT_Invalid: // fall through
1807
1808 default:
1809 {
1810 ShouldNotReachHere();
1811 } break;
1812 }
1813 } // end copy_entry_to()
1814
1815 // Search constant pool search_cp for an entry that matches this
1816 // constant pool's entry at pattern_i. Returns the index of a
1817 // matching entry or zero (0) if there is no matching entry.
1818 int ConstantPool::find_matching_entry(int pattern_i,
1819 const constantPoolHandle& search_cp) {
1820
1821 // index zero (0) is not used
1822 for (int i = 1; i < search_cp->length(); i++) {
1823 bool found = compare_entry_to(pattern_i, search_cp, i);
1824 if (found) {
1825 return i;
1826 }
1827 }
1828
1829 return 0; // entry not found; return unused index zero (0)
1830 } // end find_matching_entry()
1831
1832
1833 // Compare this constant pool's bootstrap specifier at idx1 to the constant pool
1834 // cp2's bootstrap specifier at idx2.
1835 bool ConstantPool::compare_bootstrap_entry_to(int idx1, const constantPoolHandle& cp2, int idx2) {
1836 const BSMAttributeEntry* const e1 = bsm_attribute_entry(idx1);
1837 const BSMAttributeEntry* const e2 = cp2->bsm_attribute_entry(idx2);
1838 int k1 = e1->bootstrap_method_index();
1839 int k2 = e2->bootstrap_method_index();
1840 bool match = compare_entry_to(k1, cp2, k2);
1841
1842 if (!match) {
1843 return false;
1844 }
1845
1846 const int argc = e1->argument_count();
1847 if (argc != e2->argument_count()) {
1848 return false;
1849 }
1850
1851 for (int j = 0; j < argc; j++) {
1852 k1 = e1->argument(j);
1853 k2 = e2->argument(j);
1854 match = compare_entry_to(k1, cp2, k2);
1855 if (!match) {
1856 return false;
1857 }
1858 }
1859
1860 return true; // got through loop; all elements equal
1861 } // end compare_bootstrap_entry_to()
1862
1863 // Search constant pool search_cp for a bootstrap specifier that matches
1864 // this constant pool's bootstrap specifier data at pattern_i index.
1865 // Return the index of a matching bootstrap attribute record or (-1) if there is no match.
1866 int ConstantPool::find_matching_bsm_entry(int pattern_i,
1867 const constantPoolHandle& search_cp, int offset_limit) {
1868 for (int i = 0; i < offset_limit; i++) {
1869 bool found = compare_bootstrap_entry_to(pattern_i, search_cp, i);
1870 if (found) {
1871 return i;
1872 }
1873 }
1874 return -1; // bootstrap specifier data not found; return unused index (-1)
1875 } // end find_matching_bsm_entry()
1876
1877
1878 #ifndef PRODUCT
1879
1880 const char* ConstantPool::printable_name_at(int cp_index) {
1881
1882 constantTag tag = tag_at(cp_index);
1883
1884 if (tag.is_string()) {
1885 return string_at_noresolve(cp_index);
1886 } else if (tag.is_klass() || tag.is_unresolved_klass()) {
1887 return klass_name_at(cp_index)->as_C_string();
1888 } else if (tag.is_symbol()) {
1889 return symbol_at(cp_index)->as_C_string();
1890 }
1891 return "";
1892 }
1893
1894 #endif // PRODUCT
1895
1896
1897 // Returns size of constant pool entry.
1898 jint ConstantPool::cpool_entry_size(jint idx) {
1899 switch(tag_at(idx).value()) {
1900 case JVM_CONSTANT_Invalid:
1901 case JVM_CONSTANT_Unicode:
1902 return 1;
1903
1904 case JVM_CONSTANT_Utf8:
1905 return 3 + symbol_at(idx)->utf8_length();
1906
1907 case JVM_CONSTANT_Class:
1908 case JVM_CONSTANT_String:
1909 case JVM_CONSTANT_ClassIndex:
1910 case JVM_CONSTANT_UnresolvedClass:
1911 case JVM_CONSTANT_UnresolvedClassInError:
1912 case JVM_CONSTANT_StringIndex:
1913 case JVM_CONSTANT_MethodType:
1914 case JVM_CONSTANT_MethodTypeInError:
1915 return 3;
1916
1917 case JVM_CONSTANT_MethodHandle:
1918 case JVM_CONSTANT_MethodHandleInError:
1919 return 4; //tag, ref_kind, ref_index
1920
1921 case JVM_CONSTANT_Integer:
1922 case JVM_CONSTANT_Float:
1923 case JVM_CONSTANT_Fieldref:
1924 case JVM_CONSTANT_Methodref:
1925 case JVM_CONSTANT_InterfaceMethodref:
1926 case JVM_CONSTANT_NameAndType:
1927 return 5;
1928
1929 case JVM_CONSTANT_Dynamic:
1930 case JVM_CONSTANT_DynamicInError:
1931 case JVM_CONSTANT_InvokeDynamic:
1932 // u1 tag, u2 bsm, u2 nt
1933 return 5;
1934
1935 case JVM_CONSTANT_Long:
1936 case JVM_CONSTANT_Double:
1937 return 9;
1938 }
1939 assert(false, "cpool_entry_size: Invalid constant pool entry tag");
1940 return 1;
1941 } /* end cpool_entry_size */
1942
1943
1944 // SymbolHash is used to find a constant pool index from a string.
1945 // This function fills in SymbolHashs, one for utf8s and one for
1946 // class names, returns size of the cpool raw bytes.
1947 jint ConstantPool::hash_entries_to(SymbolHash *symmap,
1948 SymbolHash *classmap) {
1949 jint size = 0;
1950
1951 for (u2 idx = 1; idx < length(); idx++) {
1952 u2 tag = tag_at(idx).value();
1953 size += cpool_entry_size(idx);
1954
1955 switch(tag) {
1956 case JVM_CONSTANT_Utf8: {
1957 Symbol* sym = symbol_at(idx);
1958 symmap->add_if_absent(sym, idx);
1959 break;
1960 }
1961 case JVM_CONSTANT_Class:
1962 case JVM_CONSTANT_UnresolvedClass:
1963 case JVM_CONSTANT_UnresolvedClassInError: {
1964 Symbol* sym = klass_name_at(idx);
1965 classmap->add_if_absent(sym, idx);
1966 break;
1967 }
1968 case JVM_CONSTANT_Long:
1969 case JVM_CONSTANT_Double: {
1970 idx++; // Both Long and Double take two cpool slots
1971 break;
1972 }
1973 }
1974 }
1975 return size;
1976 } /* end hash_utf8_entries_to */
1977
1978
1979 // Copy cpool bytes.
1980 // Returns:
1981 // 0, in case of OutOfMemoryError
1982 // -1, in case of internal error
1983 // > 0, count of the raw cpool bytes that have been copied
1984 int ConstantPool::copy_cpool_bytes(int cpool_size,
1985 SymbolHash* tbl,
1986 unsigned char *bytes) {
1987 u2 idx1, idx2;
1988 jint size = 0;
1989 jint cnt = length();
1990 unsigned char *start_bytes = bytes;
1991
1992 for (jint idx = 1; idx < cnt; idx++) {
1993 u1 tag = tag_at(idx).value();
1994 jint ent_size = cpool_entry_size(idx);
1995
1996 assert(size + ent_size <= cpool_size, "Size mismatch");
1997
1998 *bytes = tag;
1999 switch(tag) {
2000 case JVM_CONSTANT_Invalid: {
2001 break;
2002 }
2003 case JVM_CONSTANT_Unicode: {
2004 assert(false, "Wrong constant pool tag: JVM_CONSTANT_Unicode");
2005 break;
2006 }
2007 case JVM_CONSTANT_Utf8: {
2008 Symbol* sym = symbol_at(idx);
2009 char* str = sym->as_utf8();
2010 // Warning! It's crashing on x86 with len = sym->utf8_length()
2011 int len = (int) strlen(str);
2012 Bytes::put_Java_u2((address) (bytes+1), (u2) len);
2013 for (int i = 0; i < len; i++) {
2014 bytes[3+i] = (u1) str[i];
2015 }
2016 break;
2017 }
2018 case JVM_CONSTANT_Integer: {
2019 jint val = int_at(idx);
2020 Bytes::put_Java_u4((address) (bytes+1), *(u4*)&val);
2021 break;
2022 }
2023 case JVM_CONSTANT_Float: {
2024 jfloat val = float_at(idx);
2025 Bytes::put_Java_u4((address) (bytes+1), *(u4*)&val);
2026 break;
2027 }
2028 case JVM_CONSTANT_Long: {
2029 jlong val = long_at(idx);
2030 Bytes::put_Java_u8((address) (bytes+1), *(u8*)&val);
2031 idx++; // Long takes two cpool slots
2032 break;
2033 }
2034 case JVM_CONSTANT_Double: {
2035 jdouble val = double_at(idx);
2036 Bytes::put_Java_u8((address) (bytes+1), *(u8*)&val);
2037 idx++; // Double takes two cpool slots
2038 break;
2039 }
2040 case JVM_CONSTANT_Class:
2041 case JVM_CONSTANT_UnresolvedClass:
2042 case JVM_CONSTANT_UnresolvedClassInError: {
2043 *bytes = JVM_CONSTANT_Class;
2044 Symbol* sym = klass_name_at(idx);
2045 idx1 = tbl->symbol_to_value(sym);
2046 assert(idx1 != 0, "Have not found a hashtable entry");
2047 Bytes::put_Java_u2((address) (bytes+1), idx1);
2048 break;
2049 }
2050 case JVM_CONSTANT_String: {
2051 *bytes = JVM_CONSTANT_String;
2052 Symbol* sym = unresolved_string_at(idx);
2053 idx1 = tbl->symbol_to_value(sym);
2054 assert(idx1 != 0, "Have not found a hashtable entry");
2055 Bytes::put_Java_u2((address) (bytes+1), idx1);
2056 break;
2057 }
2058 case JVM_CONSTANT_Fieldref:
2059 case JVM_CONSTANT_Methodref:
2060 case JVM_CONSTANT_InterfaceMethodref: {
2061 idx1 = uncached_klass_ref_index_at(idx);
2062 idx2 = uncached_name_and_type_ref_index_at(idx);
2063 Bytes::put_Java_u2((address) (bytes+1), idx1);
2064 Bytes::put_Java_u2((address) (bytes+3), idx2);
2065 break;
2066 }
2067 case JVM_CONSTANT_NameAndType: {
2068 idx1 = name_ref_index_at(idx);
2069 idx2 = signature_ref_index_at(idx);
2070 Bytes::put_Java_u2((address) (bytes+1), idx1);
2071 Bytes::put_Java_u2((address) (bytes+3), idx2);
2072 break;
2073 }
2074 case JVM_CONSTANT_ClassIndex: {
2075 *bytes = JVM_CONSTANT_Class;
2076 idx1 = checked_cast<u2>(klass_index_at(idx));
2077 Bytes::put_Java_u2((address) (bytes+1), idx1);
2078 break;
2079 }
2080 case JVM_CONSTANT_StringIndex: {
2081 *bytes = JVM_CONSTANT_String;
2082 idx1 = checked_cast<u2>(string_index_at(idx));
2083 Bytes::put_Java_u2((address) (bytes+1), idx1);
2084 break;
2085 }
2086 case JVM_CONSTANT_MethodHandle:
2087 case JVM_CONSTANT_MethodHandleInError: {
2088 *bytes = JVM_CONSTANT_MethodHandle;
2089 int kind = method_handle_ref_kind_at(idx);
2090 idx1 = checked_cast<u2>(method_handle_index_at(idx));
2091 *(bytes+1) = (unsigned char) kind;
2092 Bytes::put_Java_u2((address) (bytes+2), idx1);
2093 break;
2094 }
2095 case JVM_CONSTANT_MethodType:
2096 case JVM_CONSTANT_MethodTypeInError: {
2097 *bytes = JVM_CONSTANT_MethodType;
2098 idx1 = checked_cast<u2>(method_type_index_at(idx));
2099 Bytes::put_Java_u2((address) (bytes+1), idx1);
2100 break;
2101 }
2102 case JVM_CONSTANT_Dynamic:
2103 case JVM_CONSTANT_DynamicInError: {
2104 *bytes = tag;
2105 idx1 = extract_low_short_from_int(*int_at_addr(idx));
2106 idx2 = extract_high_short_from_int(*int_at_addr(idx));
2107 assert(idx2 == bootstrap_name_and_type_ref_index_at(idx), "correct half of u4");
2108 Bytes::put_Java_u2((address) (bytes+1), idx1);
2109 Bytes::put_Java_u2((address) (bytes+3), idx2);
2110 break;
2111 }
2112 case JVM_CONSTANT_InvokeDynamic: {
2113 *bytes = tag;
2114 idx1 = extract_low_short_from_int(*int_at_addr(idx));
2115 idx2 = extract_high_short_from_int(*int_at_addr(idx));
2116 assert(idx2 == bootstrap_name_and_type_ref_index_at(idx), "correct half of u4");
2117 Bytes::put_Java_u2((address) (bytes+1), idx1);
2118 Bytes::put_Java_u2((address) (bytes+3), idx2);
2119 break;
2120 }
2121 }
2122 bytes += ent_size;
2123 size += ent_size;
2124 }
2125 assert(size == cpool_size, "Size mismatch");
2126
2127 return (int)(bytes - start_bytes);
2128 } /* end copy_cpool_bytes */
2129
2130 bool ConstantPool::is_maybe_on_stack() const {
2131 // This method uses the similar logic as nmethod::is_maybe_on_stack()
2132 if (!Continuations::enabled()) {
2133 return false;
2134 }
2135
2136 // If the condition below is true, it means that the nmethod was found to
2137 // be alive the previous completed marking cycle.
2138 return cache()->gc_epoch() >= CodeCache::previous_completed_gc_marking_cycle();
2139 }
2140
2141 // For redefinition, if any methods found in loom stack chunks, the gc_epoch is
2142 // recorded in their constant pool cache. The on_stack-ness of the constant pool controls whether
2143 // memory for the method is reclaimed.
2144 bool ConstantPool::on_stack() const {
2145 if ((_flags &_on_stack) != 0) {
2146 return true;
2147 }
2148
2149 if (_cache == nullptr) {
2150 return false;
2151 }
2152
2153 return is_maybe_on_stack();
2154 }
2155
2156 void ConstantPool::set_on_stack(const bool value) {
2157 if (value) {
2158 // Only record if it's not already set.
2159 if (!on_stack()) {
2160 assert(!in_aot_cache(), "should always be set for constant pools in AOT cache");
2161 _flags |= _on_stack;
2162 MetadataOnStackMark::record(this);
2163 }
2164 } else {
2165 // Clearing is done single-threadedly.
2166 if (!in_aot_cache()) {
2167 _flags &= (u2)(~_on_stack);
2168 }
2169 }
2170 }
2171
2172 // Printing
2173
2174 void ConstantPool::print_on(outputStream* st) const {
2175 assert(is_constantPool(), "must be constantPool");
2176 st->print_cr("%s", internal_name());
2177 if (flags() != 0) {
2178 st->print(" - flags: 0x%x", flags());
2179 if (has_preresolution()) st->print(" has_preresolution");
2180 if (on_stack()) st->print(" on_stack");
2181 st->cr();
2182 }
2183 if (pool_holder() != nullptr) {
2184 st->print_cr(" - holder: " PTR_FORMAT, p2i(pool_holder()));
2185 }
2186 st->print_cr(" - cache: " PTR_FORMAT, p2i(cache()));
2187 st->print_cr(" - resolved_references: " PTR_FORMAT, p2i(resolved_references_or_null()));
2188 st->print_cr(" - reference_map: " PTR_FORMAT, p2i(reference_map()));
2189 st->print_cr(" - resolved_klasses: " PTR_FORMAT, p2i(resolved_klasses()));
2190 st->print_cr(" - cp length: %d", length());
2191
2192 for (int index = 1; index < length(); index++) { // Index 0 is unused
2193 ((ConstantPool*)this)->print_entry_on(index, st);
2194 switch (tag_at(index).value()) {
2195 case JVM_CONSTANT_Long :
2196 case JVM_CONSTANT_Double :
2197 index++; // Skip entry following eigth-byte constant
2198 }
2199
2200 }
2201 st->cr();
2202 }
2203
2204 // Print one constant pool entry
2205 void ConstantPool::print_entry_on(const int cp_index, outputStream* st) {
2206 EXCEPTION_MARK;
2207 st->print(" - %3d : ", cp_index);
2208 tag_at(cp_index).print_on(st);
2209 st->print(" : ");
2210 switch (tag_at(cp_index).value()) {
2211 case JVM_CONSTANT_Class :
2212 { Klass* k = klass_at(cp_index, CATCH);
2213 guarantee(k != nullptr, "need klass");
2214 k->print_value_on(st);
2215 st->print(" {" PTR_FORMAT "}", p2i(k));
2216 }
2217 break;
2218 case JVM_CONSTANT_Fieldref :
2219 case JVM_CONSTANT_Methodref :
2220 case JVM_CONSTANT_InterfaceMethodref :
2221 st->print("klass_index=%d", uncached_klass_ref_index_at(cp_index));
2222 st->print(" name_and_type_index=%d", uncached_name_and_type_ref_index_at(cp_index));
2223 break;
2224 case JVM_CONSTANT_String :
2225 unresolved_string_at(cp_index)->print_value_on(st);
2226 break;
2227 case JVM_CONSTANT_Integer :
2228 st->print("%d", int_at(cp_index));
2229 break;
2230 case JVM_CONSTANT_Float :
2231 st->print("%f", float_at(cp_index));
2232 break;
2233 case JVM_CONSTANT_Long :
2234 st->print_jlong(long_at(cp_index));
2235 break;
2236 case JVM_CONSTANT_Double :
2237 st->print("%lf", double_at(cp_index));
2238 break;
2239 case JVM_CONSTANT_NameAndType :
2240 st->print("name_index=%d", name_ref_index_at(cp_index));
2241 st->print(" signature_index=%d", signature_ref_index_at(cp_index));
2242 break;
2243 case JVM_CONSTANT_Utf8 :
2244 symbol_at(cp_index)->print_value_on(st);
2245 break;
2246 case JVM_CONSTANT_ClassIndex: {
2247 int name_index = *int_at_addr(cp_index);
2248 st->print("klass_index=%d ", name_index);
2249 symbol_at(name_index)->print_value_on(st);
2250 }
2251 break;
2252 case JVM_CONSTANT_UnresolvedClass : // fall-through
2253 case JVM_CONSTANT_UnresolvedClassInError: {
2254 CPKlassSlot kslot = klass_slot_at(cp_index);
2255 int resolved_klass_index = kslot.resolved_klass_index();
2256 int name_index = kslot.name_index();
2257 assert(tag_at(name_index).is_symbol(), "sanity");
2258 symbol_at(name_index)->print_value_on(st);
2259 }
2260 break;
2261 case JVM_CONSTANT_MethodHandle :
2262 case JVM_CONSTANT_MethodHandleInError :
2263 st->print("ref_kind=%d", method_handle_ref_kind_at(cp_index));
2264 st->print(" ref_index=%d", method_handle_index_at(cp_index));
2265 break;
2266 case JVM_CONSTANT_MethodType :
2267 case JVM_CONSTANT_MethodTypeInError :
2268 st->print("signature_index=%d", method_type_index_at(cp_index));
2269 break;
2270 case JVM_CONSTANT_Dynamic :
2271 case JVM_CONSTANT_DynamicInError :
2272 {
2273 st->print("bootstrap_method_index=%d", bootstrap_method_ref_index_at(cp_index));
2274 st->print(" type_index=%d", bootstrap_name_and_type_ref_index_at(cp_index));
2275 int argc = bootstrap_argument_count_at(cp_index);
2276 if (argc > 0) {
2277 for (int arg_i = 0; arg_i < argc; arg_i++) {
2278 int arg = bootstrap_argument_index_at(cp_index, arg_i);
2279 st->print((arg_i == 0 ? " arguments={%d" : ", %d"), arg);
2280 }
2281 st->print("}");
2282 }
2283 }
2284 break;
2285 case JVM_CONSTANT_InvokeDynamic :
2286 {
2287 st->print("bootstrap_method_index=%d", bootstrap_method_ref_index_at(cp_index));
2288 st->print(" name_and_type_index=%d", bootstrap_name_and_type_ref_index_at(cp_index));
2289 int argc = bootstrap_argument_count_at(cp_index);
2290 if (argc > 0) {
2291 for (int arg_i = 0; arg_i < argc; arg_i++) {
2292 int arg = bootstrap_argument_index_at(cp_index, arg_i);
2293 st->print((arg_i == 0 ? " arguments={%d" : ", %d"), arg);
2294 }
2295 st->print("}");
2296 }
2297 }
2298 break;
2299 default:
2300 ShouldNotReachHere();
2301 break;
2302 }
2303 st->cr();
2304 }
2305
2306 void ConstantPool::print_value_on(outputStream* st) const {
2307 assert(is_constantPool(), "must be constantPool");
2308 st->print("constant pool [%d]", length());
2309 if (has_preresolution()) st->print("/preresolution");
2310 if (!bsm_entries().is_empty()) st->print("/BSMs[%d]", bsm_entries().bootstrap_methods()->length());
2311 print_address_on(st);
2312 if (pool_holder() != nullptr) {
2313 st->print(" for ");
2314 pool_holder()->print_value_on(st);
2315 bool extra = (pool_holder()->constants() != this);
2316 if (extra) st->print(" (extra)");
2317 }
2318 if (cache() != nullptr) {
2319 st->print(" cache=" PTR_FORMAT, p2i(cache()));
2320 }
2321 }
2322
2323 // Verification
2324
2325 void ConstantPool::verify_on(outputStream* st) {
2326 guarantee(is_constantPool(), "object must be constant pool");
2327 for (int i = 0; i< length(); i++) {
2328 constantTag tag = tag_at(i);
2329 if (tag.is_klass() || tag.is_unresolved_klass()) {
2330 guarantee(klass_name_at(i)->refcount() != 0, "should have nonzero reference count");
2331 } else if (tag.is_symbol()) {
2332 Symbol* entry = symbol_at(i);
2333 guarantee(entry->refcount() != 0, "should have nonzero reference count");
2334 } else if (tag.is_string()) {
2335 Symbol* entry = unresolved_string_at(i);
2336 guarantee(entry->refcount() != 0, "should have nonzero reference count");
2337 }
2338 }
2339 if (pool_holder() != nullptr) {
2340 // Note: pool_holder() can be null in temporary constant pools
2341 // used during constant pool merging
2342 guarantee(pool_holder()->is_klass(), "should be klass");
2343 }
2344 }
2345
2346 void BSMAttributeEntries::deallocate_contents(ClassLoaderData* loader_data) {
2347 MetadataFactory::free_array<u4>(loader_data, this->_offsets);
2348 MetadataFactory::free_array<u2>(loader_data, this->_bootstrap_methods);
2349 this->_offsets = nullptr;
2350 this->_bootstrap_methods = nullptr;
2351 }
2352
2353 void BSMAttributeEntries::copy_into(InsertionIterator& iter, int num_entries) const {
2354 assert(num_entries + iter._cur_offset <= iter._insert_into->_offsets->length(), "must");
2355 for (int i = 0; i < num_entries; i++) {
2356 const BSMAttributeEntry* e = entry(i);
2357 BSMAttributeEntry* e_new = iter.reserve_new_entry(e->bootstrap_method_index(), e->argument_count());
2358 assert(e_new != nullptr, "must be");
2359 e->copy_args_into(e_new);
2360 }
2361 }
2362
2363 BSMAttributeEntries::InsertionIterator
2364 BSMAttributeEntries::start_extension(const BSMAttributeEntries& other, ClassLoaderData* loader_data, TRAPS) {
2365 InsertionIterator iter = start_extension(other.number_of_entries(), other.array_length(),
2366 loader_data, CHECK_(BSMAttributeEntries::InsertionIterator()));
2367 return iter;
2368 }
2369
2370 BSMAttributeEntries::InsertionIterator
2371 BSMAttributeEntries::start_extension(int number_of_entries, int array_length,
2372 ClassLoaderData* loader_data, TRAPS) {
2373 InsertionIterator extension_iterator(this, this->number_of_entries(), this->array_length());
2374 int new_number_of_entries = this->number_of_entries() + number_of_entries;
2375 int new_array_length = this->array_length() + array_length;
2376 int invalid_index = new_array_length;
2377
2378 Array<u4>* new_offsets =
2379 MetadataFactory::new_array<u4>(loader_data, new_number_of_entries, invalid_index, CHECK_(InsertionIterator()));
2380 Array<u2>* new_array = MetadataFactory::new_array<u2>(loader_data, new_array_length, CHECK_(InsertionIterator()));
2381 { // Copy over all the old BSMAEntry's and their respective offsets
2382 BSMAttributeEntries carrier(new_offsets, new_array);
2383 InsertionIterator copy_iter(&carrier, 0, 0);
2384 copy_into(copy_iter, this->number_of_entries());
2385 }
2386 // Replace content
2387 deallocate_contents(loader_data);
2388 _offsets = new_offsets;
2389 _bootstrap_methods = new_array;
2390 return extension_iterator;
2391 }
2392
2393
2394 void BSMAttributeEntries::append(const BSMAttributeEntries& other, ClassLoaderData* loader_data, TRAPS) {
2395 if (other.number_of_entries() == 0) {
2396 return; // Done!
2397 }
2398 InsertionIterator iter = start_extension(other, loader_data, CHECK);
2399 other.copy_into(iter, other.number_of_entries());
2400 end_extension(iter, loader_data, THREAD);
2401 }
2402
2403 void BSMAttributeEntries::end_extension(InsertionIterator& iter, ClassLoaderData* loader_data, TRAPS) {
2404 assert(iter._insert_into == this, "must be");
2405 assert(iter._cur_offset <= this->_offsets->length(), "must be");
2406 assert(iter._cur_array <= this->_bootstrap_methods->length(), "must be");
2407
2408 // Did we fill up all of the available space? If so, do nothing.
2409 if (iter._cur_offset == this->_offsets->length() &&
2410 iter._cur_array == this->_bootstrap_methods->length()) {
2411 return;
2412 }
2413
2414 // We used less, truncate by allocating new arrays
2415 Array<u4>* new_offsets =
2416 MetadataFactory::new_array<u4>(loader_data, iter._cur_offset, 0, CHECK);
2417 Array<u2>* new_array =
2418 MetadataFactory::new_array<u2>(loader_data, iter._cur_array, CHECK);
2419 { // Copy over the constructed BSMAEntry's
2420 BSMAttributeEntries carrier(new_offsets, new_array);
2421 InsertionIterator copy_iter(&carrier, 0, 0);
2422 copy_into(copy_iter, iter._cur_offset);
2423 }
2424
2425 deallocate_contents(loader_data);
2426 _offsets = new_offsets;
2427 _bootstrap_methods = new_array;
2428 }