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