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