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