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