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