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