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