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