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