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