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