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