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