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