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