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