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