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