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