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 argc;
1182   int limit = pos + end_arg - start_arg;
1183   // checks: index in range [0..this_cp->length),
1184   // tag at index, start..end in range [0..argc],
1185   // info array non-null, pos..limit in [0..info.length]
1186   if ((0 >= index    || index >= this_cp->length())  ||
1187       !(this_cp->tag_at(index).is_invoke_dynamic()    ||
1188         this_cp->tag_at(index).is_dynamic_constant()) ||
1189       (0 > start_arg || start_arg > end_arg) ||
1190       (end_arg > (argc = this_cp->bootstrap_argument_count_at(index))) ||
1191       (0 > pos       || pos > limit)         ||
1192       (info.is_null() || limit > info->length())) {
1193     // An index or something else went wrong; throw an error.
1194     // Since this is an internal API, we don't expect this,
1195     // so we don't bother to craft a nice message.
1196     THROW_MSG(vmSymbols::java_lang_LinkageError(), "bad BSM argument access");
1197   }
1198   // now we can loop safely
1199   int info_i = pos;
1200   for (int i = start_arg; i < end_arg; i++) {
1201     int arg_index = this_cp->bootstrap_argument_index_at(index, i);
1202     oop arg_oop;
1203     if (must_resolve) {
1204       arg_oop = this_cp->resolve_possibly_cached_constant_at(arg_index, CHECK);
1205     } else {
1206       bool found_it = false;
1207       arg_oop = this_cp->find_cached_constant_at(arg_index, found_it, CHECK);
1208       if (!found_it)  arg_oop = if_not_available();
1209     }
1210     info->obj_at_put(info_i++, arg_oop);
1211   }
1212 }
1213 
1214 oop ConstantPool::string_at_impl(const constantPoolHandle& this_cp, int which, int obj_index, TRAPS) {
1215   // If the string has already been interned, this entry will be non-null
1216   oop str = this_cp->resolved_references()->obj_at(obj_index);
1217   assert(str != Universe::the_null_sentinel(), "");
1218   if (str != NULL) return str;
1219   Symbol* sym = this_cp->unresolved_string_at(which);
1220   str = StringTable::intern(sym, CHECK_(NULL));
1221   this_cp->string_at_put(which, obj_index, str);
1222   assert(java_lang_String::is_instance(str), "must be string");
1223   return str;
1224 }
1225 
1226 
1227 bool ConstantPool::klass_name_at_matches(const InstanceKlass* k, int which) {
1228   // Names are interned, so we can compare Symbol*s directly
1229   Symbol* cp_name = klass_name_at(which);
1230   return (cp_name == k->name());
1231 }
1232 
1233 
1234 // Iterate over symbols and decrement ones which are Symbol*s
1235 // This is done during GC.
1236 // Only decrement the UTF8 symbols. Strings point to
1237 // these symbols but didn't increment the reference count.
1238 void ConstantPool::unreference_symbols() {
1239   for (int index = 1; index < length(); index++) { // Index 0 is unused
1240     constantTag tag = tag_at(index);
1241     if (tag.is_symbol()) {
1242       symbol_at(index)->decrement_refcount();
1243     }
1244   }
1245 }
1246 
1247 
1248 // Compare this constant pool's entry at index1 to the constant pool
1249 // cp2's entry at index2.
1250 bool ConstantPool::compare_entry_to(int index1, const constantPoolHandle& cp2,
1251        int index2) {
1252 
1253   // The error tags are equivalent to non-error tags when comparing
1254   jbyte t1 = tag_at(index1).non_error_value();
1255   jbyte t2 = cp2->tag_at(index2).non_error_value();
1256 
1257   if (t1 != t2) {
1258     // Not the same entry type so there is nothing else to check. Note
1259     // that this style of checking will consider resolved/unresolved
1260     // class pairs as different.
1261     // From the ConstantPool* API point of view, this is correct
1262     // behavior. See VM_RedefineClasses::merge_constant_pools() to see how this
1263     // plays out in the context of ConstantPool* merging.
1264     return false;
1265   }
1266 
1267   switch (t1) {
1268   case JVM_CONSTANT_Class:
1269   {
1270     Klass* k1 = resolved_klass_at(index1);
1271     Klass* k2 = cp2->resolved_klass_at(index2);
1272     if (k1 == k2) {
1273       return true;
1274     }
1275   } break;
1276 
1277   case JVM_CONSTANT_ClassIndex:
1278   {
1279     int recur1 = klass_index_at(index1);
1280     int recur2 = cp2->klass_index_at(index2);
1281     if (compare_entry_to(recur1, cp2, recur2)) {
1282       return true;
1283     }
1284   } break;
1285 
1286   case JVM_CONSTANT_Double:
1287   {
1288     jdouble d1 = double_at(index1);
1289     jdouble d2 = cp2->double_at(index2);
1290     if (d1 == d2) {
1291       return true;
1292     }
1293   } break;
1294 
1295   case JVM_CONSTANT_Fieldref:
1296   case JVM_CONSTANT_InterfaceMethodref:
1297   case JVM_CONSTANT_Methodref:
1298   {
1299     int recur1 = uncached_klass_ref_index_at(index1);
1300     int recur2 = cp2->uncached_klass_ref_index_at(index2);
1301     bool match = compare_entry_to(recur1, cp2, recur2);
1302     if (match) {
1303       recur1 = uncached_name_and_type_ref_index_at(index1);
1304       recur2 = cp2->uncached_name_and_type_ref_index_at(index2);
1305       if (compare_entry_to(recur1, cp2, recur2)) {
1306         return true;
1307       }
1308     }
1309   } break;
1310 
1311   case JVM_CONSTANT_Float:
1312   {
1313     jfloat f1 = float_at(index1);
1314     jfloat f2 = cp2->float_at(index2);
1315     if (f1 == f2) {
1316       return true;
1317     }
1318   } break;
1319 
1320   case JVM_CONSTANT_Integer:
1321   {
1322     jint i1 = int_at(index1);
1323     jint i2 = cp2->int_at(index2);
1324     if (i1 == i2) {
1325       return true;
1326     }
1327   } break;
1328 
1329   case JVM_CONSTANT_Long:
1330   {
1331     jlong l1 = long_at(index1);
1332     jlong l2 = cp2->long_at(index2);
1333     if (l1 == l2) {
1334       return true;
1335     }
1336   } break;
1337 
1338   case JVM_CONSTANT_NameAndType:
1339   {
1340     int recur1 = name_ref_index_at(index1);
1341     int recur2 = cp2->name_ref_index_at(index2);
1342     if (compare_entry_to(recur1, cp2, recur2)) {
1343       recur1 = signature_ref_index_at(index1);
1344       recur2 = cp2->signature_ref_index_at(index2);
1345       if (compare_entry_to(recur1, cp2, recur2)) {
1346         return true;
1347       }
1348     }
1349   } break;
1350 
1351   case JVM_CONSTANT_StringIndex:
1352   {
1353     int recur1 = string_index_at(index1);
1354     int recur2 = cp2->string_index_at(index2);
1355     if (compare_entry_to(recur1, cp2, recur2)) {
1356       return true;
1357     }
1358   } break;
1359 
1360   case JVM_CONSTANT_UnresolvedClass:
1361   {
1362     Symbol* k1 = klass_name_at(index1);
1363     Symbol* k2 = cp2->klass_name_at(index2);
1364     if (k1 == k2) {
1365       return true;
1366     }
1367   } break;
1368 
1369   case JVM_CONSTANT_MethodType:
1370   {
1371     int k1 = method_type_index_at(index1);
1372     int k2 = cp2->method_type_index_at(index2);
1373     if (compare_entry_to(k1, cp2, k2)) {
1374       return true;
1375     }
1376   } break;
1377 
1378   case JVM_CONSTANT_MethodHandle:
1379   {
1380     int k1 = method_handle_ref_kind_at(index1);
1381     int k2 = cp2->method_handle_ref_kind_at(index2);
1382     if (k1 == k2) {
1383       int i1 = method_handle_index_at(index1);
1384       int i2 = cp2->method_handle_index_at(index2);
1385       if (compare_entry_to(i1, cp2, i2)) {
1386         return true;
1387       }
1388     }
1389   } break;
1390 
1391   case JVM_CONSTANT_Dynamic:
1392   {
1393     int k1 = bootstrap_name_and_type_ref_index_at(index1);
1394     int k2 = cp2->bootstrap_name_and_type_ref_index_at(index2);
1395     int i1 = bootstrap_methods_attribute_index(index1);
1396     int i2 = cp2->bootstrap_methods_attribute_index(index2);
1397     bool match_entry = compare_entry_to(k1, cp2, k2);
1398     bool match_operand = compare_operand_to(i1, cp2, i2);
1399     return (match_entry && match_operand);
1400   } break;
1401 
1402   case JVM_CONSTANT_InvokeDynamic:
1403   {
1404     int k1 = bootstrap_name_and_type_ref_index_at(index1);
1405     int k2 = cp2->bootstrap_name_and_type_ref_index_at(index2);
1406     int i1 = bootstrap_methods_attribute_index(index1);
1407     int i2 = cp2->bootstrap_methods_attribute_index(index2);
1408     bool match_entry = compare_entry_to(k1, cp2, k2);
1409     bool match_operand = compare_operand_to(i1, cp2, i2);
1410     return (match_entry && match_operand);
1411   } break;
1412 
1413   case JVM_CONSTANT_String:
1414   {
1415     Symbol* s1 = unresolved_string_at(index1);
1416     Symbol* s2 = cp2->unresolved_string_at(index2);
1417     if (s1 == s2) {
1418       return true;
1419     }
1420   } break;
1421 
1422   case JVM_CONSTANT_Utf8:
1423   {
1424     Symbol* s1 = symbol_at(index1);
1425     Symbol* s2 = cp2->symbol_at(index2);
1426     if (s1 == s2) {
1427       return true;
1428     }
1429   } break;
1430 
1431   // Invalid is used as the tag for the second constant pool entry
1432   // occupied by JVM_CONSTANT_Double or JVM_CONSTANT_Long. It should
1433   // not be seen by itself.
1434   case JVM_CONSTANT_Invalid: // fall through
1435 
1436   default:
1437     ShouldNotReachHere();
1438     break;
1439   }
1440 
1441   return false;
1442 } // end compare_entry_to()
1443 
1444 
1445 // Resize the operands array with delta_len and delta_size.
1446 // Used in RedefineClasses for CP merge.
1447 void ConstantPool::resize_operands(int delta_len, int delta_size, TRAPS) {
1448   int old_len  = operand_array_length(operands());
1449   int new_len  = old_len + delta_len;
1450   int min_len  = (delta_len > 0) ? old_len : new_len;
1451 
1452   int old_size = operands()->length();
1453   int new_size = old_size + delta_size;
1454   int min_size = (delta_size > 0) ? old_size : new_size;
1455 
1456   ClassLoaderData* loader_data = pool_holder()->class_loader_data();
1457   Array<u2>* new_ops = MetadataFactory::new_array<u2>(loader_data, new_size, CHECK);
1458 
1459   // Set index in the resized array for existing elements only
1460   for (int idx = 0; idx < min_len; idx++) {
1461     int offset = operand_offset_at(idx);                       // offset in original array
1462     operand_offset_at_put(new_ops, idx, offset + 2*delta_len); // offset in resized array
1463   }
1464   // Copy the bootstrap specifiers only
1465   Copy::conjoint_memory_atomic(operands()->adr_at(2*old_len),
1466                                new_ops->adr_at(2*new_len),
1467                                (min_size - 2*min_len) * sizeof(u2));
1468   // Explicitly deallocate old operands array.
1469   // Note, it is not needed for 7u backport.
1470   if ( operands() != NULL) { // the safety check
1471     MetadataFactory::free_array<u2>(loader_data, operands());
1472   }
1473   set_operands(new_ops);
1474 } // end resize_operands()
1475 
1476 
1477 // Extend the operands array with the length and size of the ext_cp operands.
1478 // Used in RedefineClasses for CP merge.
1479 void ConstantPool::extend_operands(const constantPoolHandle& ext_cp, TRAPS) {
1480   int delta_len = operand_array_length(ext_cp->operands());
1481   if (delta_len == 0) {
1482     return; // nothing to do
1483   }
1484   int delta_size = ext_cp->operands()->length();
1485 
1486   assert(delta_len  > 0 && delta_size > 0, "extended operands array must be bigger");
1487 
1488   if (operand_array_length(operands()) == 0) {
1489     ClassLoaderData* loader_data = pool_holder()->class_loader_data();
1490     Array<u2>* new_ops = MetadataFactory::new_array<u2>(loader_data, delta_size, CHECK);
1491     // The first element index defines the offset of second part
1492     operand_offset_at_put(new_ops, 0, 2*delta_len); // offset in new array
1493     set_operands(new_ops);
1494   } else {
1495     resize_operands(delta_len, delta_size, CHECK);
1496   }
1497 
1498 } // end extend_operands()
1499 
1500 
1501 // Shrink the operands array to a smaller array with new_len length.
1502 // Used in RedefineClasses for CP merge.
1503 void ConstantPool::shrink_operands(int new_len, TRAPS) {
1504   int old_len = operand_array_length(operands());
1505   if (new_len == old_len) {
1506     return; // nothing to do
1507   }
1508   assert(new_len < old_len, "shrunken operands array must be smaller");
1509 
1510   int free_base  = operand_next_offset_at(new_len - 1);
1511   int delta_len  = new_len - old_len;
1512   int delta_size = 2*delta_len + free_base - operands()->length();
1513 
1514   resize_operands(delta_len, delta_size, CHECK);
1515 
1516 } // end shrink_operands()
1517 
1518 
1519 void ConstantPool::copy_operands(const constantPoolHandle& from_cp,
1520                                  const constantPoolHandle& to_cp,
1521                                  TRAPS) {
1522 
1523   int from_oplen = operand_array_length(from_cp->operands());
1524   int old_oplen  = operand_array_length(to_cp->operands());
1525   if (from_oplen != 0) {
1526     ClassLoaderData* loader_data = to_cp->pool_holder()->class_loader_data();
1527     // append my operands to the target's operands array
1528     if (old_oplen == 0) {
1529       // Can't just reuse from_cp's operand list because of deallocation issues
1530       int len = from_cp->operands()->length();
1531       Array<u2>* new_ops = MetadataFactory::new_array<u2>(loader_data, len, CHECK);
1532       Copy::conjoint_memory_atomic(
1533           from_cp->operands()->adr_at(0), new_ops->adr_at(0), len * sizeof(u2));
1534       to_cp->set_operands(new_ops);
1535     } else {
1536       int old_len  = to_cp->operands()->length();
1537       int from_len = from_cp->operands()->length();
1538       int old_off  = old_oplen * sizeof(u2);
1539       int from_off = from_oplen * sizeof(u2);
1540       // Use the metaspace for the destination constant pool
1541       Array<u2>* new_operands = MetadataFactory::new_array<u2>(loader_data, old_len + from_len, CHECK);
1542       int fillp = 0, len = 0;
1543       // first part of dest
1544       Copy::conjoint_memory_atomic(to_cp->operands()->adr_at(0),
1545                                    new_operands->adr_at(fillp),
1546                                    (len = old_off) * sizeof(u2));
1547       fillp += len;
1548       // first part of src
1549       Copy::conjoint_memory_atomic(from_cp->operands()->adr_at(0),
1550                                    new_operands->adr_at(fillp),
1551                                    (len = from_off) * sizeof(u2));
1552       fillp += len;
1553       // second part of dest
1554       Copy::conjoint_memory_atomic(to_cp->operands()->adr_at(old_off),
1555                                    new_operands->adr_at(fillp),
1556                                    (len = old_len - old_off) * sizeof(u2));
1557       fillp += len;
1558       // second part of src
1559       Copy::conjoint_memory_atomic(from_cp->operands()->adr_at(from_off),
1560                                    new_operands->adr_at(fillp),
1561                                    (len = from_len - from_off) * sizeof(u2));
1562       fillp += len;
1563       assert(fillp == new_operands->length(), "");
1564 
1565       // Adjust indexes in the first part of the copied operands array.
1566       for (int j = 0; j < from_oplen; j++) {
1567         int offset = operand_offset_at(new_operands, old_oplen + j);
1568         assert(offset == operand_offset_at(from_cp->operands(), j), "correct copy");
1569         offset += old_len;  // every new tuple is preceded by old_len extra u2's
1570         operand_offset_at_put(new_operands, old_oplen + j, offset);
1571       }
1572 
1573       // replace target operands array with combined array
1574       to_cp->set_operands(new_operands);
1575     }
1576   }
1577 } // end copy_operands()
1578 
1579 
1580 // Copy this constant pool's entries at start_i to end_i (inclusive)
1581 // to the constant pool to_cp's entries starting at to_i. A total of
1582 // (end_i - start_i) + 1 entries are copied.
1583 void ConstantPool::copy_cp_to_impl(const constantPoolHandle& from_cp, int start_i, int end_i,
1584        const constantPoolHandle& to_cp, int to_i, TRAPS) {
1585 
1586 
1587   int dest_i = to_i;  // leave original alone for debug purposes
1588 
1589   for (int src_i = start_i; src_i <= end_i; /* see loop bottom */ ) {
1590     copy_entry_to(from_cp, src_i, to_cp, dest_i);
1591 
1592     switch (from_cp->tag_at(src_i).value()) {
1593     case JVM_CONSTANT_Double:
1594     case JVM_CONSTANT_Long:
1595       // double and long take two constant pool entries
1596       src_i += 2;
1597       dest_i += 2;
1598       break;
1599 
1600     default:
1601       // all others take one constant pool entry
1602       src_i++;
1603       dest_i++;
1604       break;
1605     }
1606   }
1607   copy_operands(from_cp, to_cp, CHECK);
1608 
1609 } // end copy_cp_to_impl()
1610 
1611 
1612 // Copy this constant pool's entry at from_i to the constant pool
1613 // to_cp's entry at to_i.
1614 void ConstantPool::copy_entry_to(const constantPoolHandle& from_cp, int from_i,
1615                                         const constantPoolHandle& to_cp, int to_i) {
1616 
1617   int tag = from_cp->tag_at(from_i).value();
1618   switch (tag) {
1619   case JVM_CONSTANT_ClassIndex:
1620   {
1621     jint ki = from_cp->klass_index_at(from_i);
1622     to_cp->klass_index_at_put(to_i, ki);
1623   } break;
1624 
1625   case JVM_CONSTANT_Double:
1626   {
1627     jdouble d = from_cp->double_at(from_i);
1628     to_cp->double_at_put(to_i, d);
1629     // double takes two constant pool entries so init second entry's tag
1630     to_cp->tag_at_put(to_i + 1, JVM_CONSTANT_Invalid);
1631   } break;
1632 
1633   case JVM_CONSTANT_Fieldref:
1634   {
1635     int class_index = from_cp->uncached_klass_ref_index_at(from_i);
1636     int name_and_type_index = from_cp->uncached_name_and_type_ref_index_at(from_i);
1637     to_cp->field_at_put(to_i, class_index, name_and_type_index);
1638   } break;
1639 
1640   case JVM_CONSTANT_Float:
1641   {
1642     jfloat f = from_cp->float_at(from_i);
1643     to_cp->float_at_put(to_i, f);
1644   } break;
1645 
1646   case JVM_CONSTANT_Integer:
1647   {
1648     jint i = from_cp->int_at(from_i);
1649     to_cp->int_at_put(to_i, i);
1650   } break;
1651 
1652   case JVM_CONSTANT_InterfaceMethodref:
1653   {
1654     int class_index = from_cp->uncached_klass_ref_index_at(from_i);
1655     int name_and_type_index = from_cp->uncached_name_and_type_ref_index_at(from_i);
1656     to_cp->interface_method_at_put(to_i, class_index, name_and_type_index);
1657   } break;
1658 
1659   case JVM_CONSTANT_Long:
1660   {
1661     jlong l = from_cp->long_at(from_i);
1662     to_cp->long_at_put(to_i, l);
1663     // long takes two constant pool entries so init second entry's tag
1664     to_cp->tag_at_put(to_i + 1, JVM_CONSTANT_Invalid);
1665   } break;
1666 
1667   case JVM_CONSTANT_Methodref:
1668   {
1669     int class_index = from_cp->uncached_klass_ref_index_at(from_i);
1670     int name_and_type_index = from_cp->uncached_name_and_type_ref_index_at(from_i);
1671     to_cp->method_at_put(to_i, class_index, name_and_type_index);
1672   } break;
1673 
1674   case JVM_CONSTANT_NameAndType:
1675   {
1676     int name_ref_index = from_cp->name_ref_index_at(from_i);
1677     int signature_ref_index = from_cp->signature_ref_index_at(from_i);
1678     to_cp->name_and_type_at_put(to_i, name_ref_index, signature_ref_index);
1679   } break;
1680 
1681   case JVM_CONSTANT_StringIndex:
1682   {
1683     jint si = from_cp->string_index_at(from_i);
1684     to_cp->string_index_at_put(to_i, si);
1685   } break;
1686 
1687   case JVM_CONSTANT_Class:
1688   case JVM_CONSTANT_UnresolvedClass:
1689   case JVM_CONSTANT_UnresolvedClassInError:
1690   {
1691     // Revert to JVM_CONSTANT_ClassIndex
1692     int name_index = from_cp->klass_slot_at(from_i).name_index();
1693     assert(from_cp->tag_at(name_index).is_symbol(), "sanity");
1694     to_cp->klass_index_at_put(to_i, name_index);
1695   } break;
1696 
1697   case JVM_CONSTANT_String:
1698   {
1699     Symbol* s = from_cp->unresolved_string_at(from_i);
1700     to_cp->unresolved_string_at_put(to_i, s);
1701   } break;
1702 
1703   case JVM_CONSTANT_Utf8:
1704   {
1705     Symbol* s = from_cp->symbol_at(from_i);
1706     // Need to increase refcount, the old one will be thrown away and deferenced
1707     s->increment_refcount();
1708     to_cp->symbol_at_put(to_i, s);
1709   } break;
1710 
1711   case JVM_CONSTANT_MethodType:
1712   case JVM_CONSTANT_MethodTypeInError:
1713   {
1714     jint k = from_cp->method_type_index_at(from_i);
1715     to_cp->method_type_index_at_put(to_i, k);
1716   } break;
1717 
1718   case JVM_CONSTANT_MethodHandle:
1719   case JVM_CONSTANT_MethodHandleInError:
1720   {
1721     int k1 = from_cp->method_handle_ref_kind_at(from_i);
1722     int k2 = from_cp->method_handle_index_at(from_i);
1723     to_cp->method_handle_index_at_put(to_i, k1, k2);
1724   } break;
1725 
1726   case JVM_CONSTANT_Dynamic:
1727   case JVM_CONSTANT_DynamicInError:
1728   {
1729     int k1 = from_cp->bootstrap_methods_attribute_index(from_i);
1730     int k2 = from_cp->bootstrap_name_and_type_ref_index_at(from_i);
1731     k1 += operand_array_length(to_cp->operands());  // to_cp might already have operands
1732     to_cp->dynamic_constant_at_put(to_i, k1, k2);
1733   } break;
1734 
1735   case JVM_CONSTANT_InvokeDynamic:
1736   {
1737     int k1 = from_cp->bootstrap_methods_attribute_index(from_i);
1738     int k2 = from_cp->bootstrap_name_and_type_ref_index_at(from_i);
1739     k1 += operand_array_length(to_cp->operands());  // to_cp might already have operands
1740     to_cp->invoke_dynamic_at_put(to_i, k1, k2);
1741   } break;
1742 
1743   // Invalid is used as the tag for the second constant pool entry
1744   // occupied by JVM_CONSTANT_Double or JVM_CONSTANT_Long. It should
1745   // not be seen by itself.
1746   case JVM_CONSTANT_Invalid: // fall through
1747 
1748   default:
1749   {
1750     ShouldNotReachHere();
1751   } break;
1752   }
1753 } // end copy_entry_to()
1754 
1755 // Search constant pool search_cp for an entry that matches this
1756 // constant pool's entry at pattern_i. Returns the index of a
1757 // matching entry or zero (0) if there is no matching entry.
1758 int ConstantPool::find_matching_entry(int pattern_i,
1759       const constantPoolHandle& search_cp) {
1760 
1761   // index zero (0) is not used
1762   for (int i = 1; i < search_cp->length(); i++) {
1763     bool found = compare_entry_to(pattern_i, search_cp, i);
1764     if (found) {
1765       return i;
1766     }
1767   }
1768 
1769   return 0;  // entry not found; return unused index zero (0)
1770 } // end find_matching_entry()
1771 
1772 
1773 // Compare this constant pool's bootstrap specifier at idx1 to the constant pool
1774 // cp2's bootstrap specifier at idx2.
1775 bool ConstantPool::compare_operand_to(int idx1, const constantPoolHandle& cp2, int idx2) {
1776   int k1 = operand_bootstrap_method_ref_index_at(idx1);
1777   int k2 = cp2->operand_bootstrap_method_ref_index_at(idx2);
1778   bool match = compare_entry_to(k1, cp2, k2);
1779 
1780   if (!match) {
1781     return false;
1782   }
1783   int argc = operand_argument_count_at(idx1);
1784   if (argc == cp2->operand_argument_count_at(idx2)) {
1785     for (int j = 0; j < argc; j++) {
1786       k1 = operand_argument_index_at(idx1, j);
1787       k2 = cp2->operand_argument_index_at(idx2, j);
1788       match = compare_entry_to(k1, cp2, k2);
1789       if (!match) {
1790         return false;
1791       }
1792     }
1793     return true;           // got through loop; all elements equal
1794   }
1795   return false;
1796 } // end compare_operand_to()
1797 
1798 // Search constant pool search_cp for a bootstrap specifier that matches
1799 // this constant pool's bootstrap specifier data at pattern_i index.
1800 // Return the index of a matching bootstrap attribute record or (-1) if there is no match.
1801 int ConstantPool::find_matching_operand(int pattern_i,
1802                     const constantPoolHandle& search_cp, int search_len) {
1803   for (int i = 0; i < search_len; i++) {
1804     bool found = compare_operand_to(pattern_i, search_cp, i);
1805     if (found) {
1806       return i;
1807     }
1808   }
1809   return -1;  // bootstrap specifier data not found; return unused index (-1)
1810 } // end find_matching_operand()
1811 
1812 
1813 #ifndef PRODUCT
1814 
1815 const char* ConstantPool::printable_name_at(int which) {
1816 
1817   constantTag tag = tag_at(which);
1818 
1819   if (tag.is_string()) {
1820     return string_at_noresolve(which);
1821   } else if (tag.is_klass() || tag.is_unresolved_klass()) {
1822     return klass_name_at(which)->as_C_string();
1823   } else if (tag.is_symbol()) {
1824     return symbol_at(which)->as_C_string();
1825   }
1826   return "";
1827 }
1828 
1829 #endif // PRODUCT
1830 
1831 
1832 // JVMTI GetConstantPool support
1833 
1834 // For debugging of constant pool
1835 const bool debug_cpool = false;
1836 
1837 #define DBG(code) do { if (debug_cpool) { (code); } } while(0)
1838 
1839 static void print_cpool_bytes(jint cnt, u1 *bytes) {
1840   const char* WARN_MSG = "Must not be such entry!";
1841   jint size = 0;
1842   u2   idx1, idx2;
1843 
1844   for (jint idx = 1; idx < cnt; idx++) {
1845     jint ent_size = 0;
1846     u1   tag  = *bytes++;
1847     size++;                       // count tag
1848 
1849     printf("const #%03d, tag: %02d ", idx, tag);
1850     switch(tag) {
1851       case JVM_CONSTANT_Invalid: {
1852         printf("Invalid");
1853         break;
1854       }
1855       case JVM_CONSTANT_Unicode: {
1856         printf("Unicode      %s", WARN_MSG);
1857         break;
1858       }
1859       case JVM_CONSTANT_Utf8: {
1860         u2 len = Bytes::get_Java_u2(bytes);
1861         char str[128];
1862         if (len > 127) {
1863            len = 127;
1864         }
1865         strncpy(str, (char *) (bytes+2), len);
1866         str[len] = '\0';
1867         printf("Utf8          \"%s\"", str);
1868         ent_size = 2 + len;
1869         break;
1870       }
1871       case JVM_CONSTANT_Integer: {
1872         u4 val = Bytes::get_Java_u4(bytes);
1873         printf("int          %d", *(int *) &val);
1874         ent_size = 4;
1875         break;
1876       }
1877       case JVM_CONSTANT_Float: {
1878         u4 val = Bytes::get_Java_u4(bytes);
1879         printf("float        %5.3ff", *(float *) &val);
1880         ent_size = 4;
1881         break;
1882       }
1883       case JVM_CONSTANT_Long: {
1884         u8 val = Bytes::get_Java_u8(bytes);
1885         printf("long         " INT64_FORMAT, (int64_t) *(jlong *) &val);
1886         ent_size = 8;
1887         idx++; // Long takes two cpool slots
1888         break;
1889       }
1890       case JVM_CONSTANT_Double: {
1891         u8 val = Bytes::get_Java_u8(bytes);
1892         printf("double       %5.3fd", *(jdouble *)&val);
1893         ent_size = 8;
1894         idx++; // Double takes two cpool slots
1895         break;
1896       }
1897       case JVM_CONSTANT_Class: {
1898         idx1 = Bytes::get_Java_u2(bytes);
1899         printf("class        #%03d", idx1);
1900         ent_size = 2;
1901         break;
1902       }
1903       case JVM_CONSTANT_String: {
1904         idx1 = Bytes::get_Java_u2(bytes);
1905         printf("String       #%03d", idx1);
1906         ent_size = 2;
1907         break;
1908       }
1909       case JVM_CONSTANT_Fieldref: {
1910         idx1 = Bytes::get_Java_u2(bytes);
1911         idx2 = Bytes::get_Java_u2(bytes+2);
1912         printf("Field        #%03d, #%03d", (int) idx1, (int) idx2);
1913         ent_size = 4;
1914         break;
1915       }
1916       case JVM_CONSTANT_Methodref: {
1917         idx1 = Bytes::get_Java_u2(bytes);
1918         idx2 = Bytes::get_Java_u2(bytes+2);
1919         printf("Method       #%03d, #%03d", idx1, idx2);
1920         ent_size = 4;
1921         break;
1922       }
1923       case JVM_CONSTANT_InterfaceMethodref: {
1924         idx1 = Bytes::get_Java_u2(bytes);
1925         idx2 = Bytes::get_Java_u2(bytes+2);
1926         printf("InterfMethod #%03d, #%03d", idx1, idx2);
1927         ent_size = 4;
1928         break;
1929       }
1930       case JVM_CONSTANT_NameAndType: {
1931         idx1 = Bytes::get_Java_u2(bytes);
1932         idx2 = Bytes::get_Java_u2(bytes+2);
1933         printf("NameAndType  #%03d, #%03d", idx1, idx2);
1934         ent_size = 4;
1935         break;
1936       }
1937       case JVM_CONSTANT_ClassIndex: {
1938         printf("ClassIndex  %s", WARN_MSG);
1939         break;
1940       }
1941       case JVM_CONSTANT_UnresolvedClass: {
1942         printf("UnresolvedClass: %s", WARN_MSG);
1943         break;
1944       }
1945       case JVM_CONSTANT_UnresolvedClassInError: {
1946         printf("UnresolvedClassInErr: %s", WARN_MSG);
1947         break;
1948       }
1949       case JVM_CONSTANT_StringIndex: {
1950         printf("StringIndex: %s", WARN_MSG);
1951         break;
1952       }
1953     }
1954     printf(";\n");
1955     bytes += ent_size;
1956     size  += ent_size;
1957   }
1958   printf("Cpool size: %d\n", size);
1959   fflush(0);
1960   return;
1961 } /* end print_cpool_bytes */
1962 
1963 
1964 // Returns size of constant pool entry.
1965 jint ConstantPool::cpool_entry_size(jint idx) {
1966   switch(tag_at(idx).value()) {
1967     case JVM_CONSTANT_Invalid:
1968     case JVM_CONSTANT_Unicode:
1969       return 1;
1970 
1971     case JVM_CONSTANT_Utf8:
1972       return 3 + symbol_at(idx)->utf8_length();
1973 
1974     case JVM_CONSTANT_Class:
1975     case JVM_CONSTANT_String:
1976     case JVM_CONSTANT_ClassIndex:
1977     case JVM_CONSTANT_UnresolvedClass:
1978     case JVM_CONSTANT_UnresolvedClassInError:
1979     case JVM_CONSTANT_StringIndex:
1980     case JVM_CONSTANT_MethodType:
1981     case JVM_CONSTANT_MethodTypeInError:
1982       return 3;
1983 
1984     case JVM_CONSTANT_MethodHandle:
1985     case JVM_CONSTANT_MethodHandleInError:
1986       return 4; //tag, ref_kind, ref_index
1987 
1988     case JVM_CONSTANT_Integer:
1989     case JVM_CONSTANT_Float:
1990     case JVM_CONSTANT_Fieldref:
1991     case JVM_CONSTANT_Methodref:
1992     case JVM_CONSTANT_InterfaceMethodref:
1993     case JVM_CONSTANT_NameAndType:
1994       return 5;
1995 
1996     case JVM_CONSTANT_Dynamic:
1997     case JVM_CONSTANT_DynamicInError:
1998     case JVM_CONSTANT_InvokeDynamic:
1999       // u1 tag, u2 bsm, u2 nt
2000       return 5;
2001 
2002     case JVM_CONSTANT_Long:
2003     case JVM_CONSTANT_Double:
2004       return 9;
2005   }
2006   assert(false, "cpool_entry_size: Invalid constant pool entry tag");
2007   return 1;
2008 } /* end cpool_entry_size */
2009 
2010 
2011 // SymbolHashMap is used to find a constant pool index from a string.
2012 // This function fills in SymbolHashMaps, one for utf8s and one for
2013 // class names, returns size of the cpool raw bytes.
2014 jint ConstantPool::hash_entries_to(SymbolHashMap *symmap,
2015                                           SymbolHashMap *classmap) {
2016   jint size = 0;
2017 
2018   for (u2 idx = 1; idx < length(); idx++) {
2019     u2 tag = tag_at(idx).value();
2020     size += cpool_entry_size(idx);
2021 
2022     switch(tag) {
2023       case JVM_CONSTANT_Utf8: {
2024         Symbol* sym = symbol_at(idx);
2025         symmap->add_entry(sym, idx);
2026         DBG(printf("adding symbol entry %s = %d\n", sym->as_utf8(), idx));
2027         break;
2028       }
2029       case JVM_CONSTANT_Class:
2030       case JVM_CONSTANT_UnresolvedClass:
2031       case JVM_CONSTANT_UnresolvedClassInError: {
2032         Symbol* sym = klass_name_at(idx);
2033         classmap->add_entry(sym, idx);
2034         DBG(printf("adding class entry %s = %d\n", sym->as_utf8(), idx));
2035         break;
2036       }
2037       case JVM_CONSTANT_Long:
2038       case JVM_CONSTANT_Double: {
2039         idx++; // Both Long and Double take two cpool slots
2040         break;
2041       }
2042     }
2043   }
2044   return size;
2045 } /* end hash_utf8_entries_to */
2046 
2047 
2048 // Copy cpool bytes.
2049 // Returns:
2050 //    0, in case of OutOfMemoryError
2051 //   -1, in case of internal error
2052 //  > 0, count of the raw cpool bytes that have been copied
2053 int ConstantPool::copy_cpool_bytes(int cpool_size,
2054                                           SymbolHashMap* tbl,
2055                                           unsigned char *bytes) {
2056   u2   idx1, idx2;
2057   jint size  = 0;
2058   jint cnt   = length();
2059   unsigned char *start_bytes = bytes;
2060 
2061   for (jint idx = 1; idx < cnt; idx++) {
2062     u1   tag      = tag_at(idx).value();
2063     jint ent_size = cpool_entry_size(idx);
2064 
2065     assert(size + ent_size <= cpool_size, "Size mismatch");
2066 
2067     *bytes = tag;
2068     DBG(printf("#%03hd tag=%03hd, ", (short)idx, (short)tag));
2069     switch(tag) {
2070       case JVM_CONSTANT_Invalid: {
2071         DBG(printf("JVM_CONSTANT_Invalid"));
2072         break;
2073       }
2074       case JVM_CONSTANT_Unicode: {
2075         assert(false, "Wrong constant pool tag: JVM_CONSTANT_Unicode");
2076         DBG(printf("JVM_CONSTANT_Unicode"));
2077         break;
2078       }
2079       case JVM_CONSTANT_Utf8: {
2080         Symbol* sym = symbol_at(idx);
2081         char*     str = sym->as_utf8();
2082         // Warning! It's crashing on x86 with len = sym->utf8_length()
2083         int       len = (int) strlen(str);
2084         Bytes::put_Java_u2((address) (bytes+1), (u2) len);
2085         for (int i = 0; i < len; i++) {
2086             bytes[3+i] = (u1) str[i];
2087         }
2088         DBG(printf("JVM_CONSTANT_Utf8: %s ", str));
2089         break;
2090       }
2091       case JVM_CONSTANT_Integer: {
2092         jint val = int_at(idx);
2093         Bytes::put_Java_u4((address) (bytes+1), *(u4*)&val);
2094         break;
2095       }
2096       case JVM_CONSTANT_Float: {
2097         jfloat val = float_at(idx);
2098         Bytes::put_Java_u4((address) (bytes+1), *(u4*)&val);
2099         break;
2100       }
2101       case JVM_CONSTANT_Long: {
2102         jlong val = long_at(idx);
2103         Bytes::put_Java_u8((address) (bytes+1), *(u8*)&val);
2104         idx++;             // Long takes two cpool slots
2105         break;
2106       }
2107       case JVM_CONSTANT_Double: {
2108         jdouble val = double_at(idx);
2109         Bytes::put_Java_u8((address) (bytes+1), *(u8*)&val);
2110         idx++;             // Double takes two cpool slots
2111         break;
2112       }
2113       case JVM_CONSTANT_Class:
2114       case JVM_CONSTANT_UnresolvedClass:
2115       case JVM_CONSTANT_UnresolvedClassInError: {
2116         *bytes = JVM_CONSTANT_Class;
2117         Symbol* sym = klass_name_at(idx);
2118         idx1 = tbl->symbol_to_value(sym);
2119         assert(idx1 != 0, "Have not found a hashtable entry");
2120         Bytes::put_Java_u2((address) (bytes+1), idx1);
2121         DBG(printf("JVM_CONSTANT_Class: idx=#%03hd, %s", idx1, sym->as_utf8()));
2122         break;
2123       }
2124       case JVM_CONSTANT_String: {
2125         *bytes = JVM_CONSTANT_String;
2126         Symbol* sym = unresolved_string_at(idx);
2127         idx1 = tbl->symbol_to_value(sym);
2128         assert(idx1 != 0, "Have not found a hashtable entry");
2129         Bytes::put_Java_u2((address) (bytes+1), idx1);
2130         DBG(printf("JVM_CONSTANT_String: idx=#%03hd, %s", idx1, sym->as_utf8()));
2131         break;
2132       }
2133       case JVM_CONSTANT_Fieldref:
2134       case JVM_CONSTANT_Methodref:
2135       case JVM_CONSTANT_InterfaceMethodref: {
2136         idx1 = uncached_klass_ref_index_at(idx);
2137         idx2 = uncached_name_and_type_ref_index_at(idx);
2138         Bytes::put_Java_u2((address) (bytes+1), idx1);
2139         Bytes::put_Java_u2((address) (bytes+3), idx2);
2140         DBG(printf("JVM_CONSTANT_Methodref: %hd %hd", idx1, idx2));
2141         break;
2142       }
2143       case JVM_CONSTANT_NameAndType: {
2144         idx1 = name_ref_index_at(idx);
2145         idx2 = signature_ref_index_at(idx);
2146         Bytes::put_Java_u2((address) (bytes+1), idx1);
2147         Bytes::put_Java_u2((address) (bytes+3), idx2);
2148         DBG(printf("JVM_CONSTANT_NameAndType: %hd %hd", idx1, idx2));
2149         break;
2150       }
2151       case JVM_CONSTANT_ClassIndex: {
2152         *bytes = JVM_CONSTANT_Class;
2153         idx1 = klass_index_at(idx);
2154         Bytes::put_Java_u2((address) (bytes+1), idx1);
2155         DBG(printf("JVM_CONSTANT_ClassIndex: %hd", idx1));
2156         break;
2157       }
2158       case JVM_CONSTANT_StringIndex: {
2159         *bytes = JVM_CONSTANT_String;
2160         idx1 = string_index_at(idx);
2161         Bytes::put_Java_u2((address) (bytes+1), idx1);
2162         DBG(printf("JVM_CONSTANT_StringIndex: %hd", idx1));
2163         break;
2164       }
2165       case JVM_CONSTANT_MethodHandle:
2166       case JVM_CONSTANT_MethodHandleInError: {
2167         *bytes = JVM_CONSTANT_MethodHandle;
2168         int kind = method_handle_ref_kind_at(idx);
2169         idx1 = method_handle_index_at(idx);
2170         *(bytes+1) = (unsigned char) kind;
2171         Bytes::put_Java_u2((address) (bytes+2), idx1);
2172         DBG(printf("JVM_CONSTANT_MethodHandle: %d %hd", kind, idx1));
2173         break;
2174       }
2175       case JVM_CONSTANT_MethodType:
2176       case JVM_CONSTANT_MethodTypeInError: {
2177         *bytes = JVM_CONSTANT_MethodType;
2178         idx1 = method_type_index_at(idx);
2179         Bytes::put_Java_u2((address) (bytes+1), idx1);
2180         DBG(printf("JVM_CONSTANT_MethodType: %hd", idx1));
2181         break;
2182       }
2183       case JVM_CONSTANT_Dynamic:
2184       case JVM_CONSTANT_DynamicInError: {
2185         *bytes = tag;
2186         idx1 = extract_low_short_from_int(*int_at_addr(idx));
2187         idx2 = extract_high_short_from_int(*int_at_addr(idx));
2188         assert(idx2 == bootstrap_name_and_type_ref_index_at(idx), "correct half of u4");
2189         Bytes::put_Java_u2((address) (bytes+1), idx1);
2190         Bytes::put_Java_u2((address) (bytes+3), idx2);
2191         DBG(printf("JVM_CONSTANT_Dynamic: %hd %hd", idx1, idx2));
2192         break;
2193       }
2194       case JVM_CONSTANT_InvokeDynamic: {
2195         *bytes = tag;
2196         idx1 = extract_low_short_from_int(*int_at_addr(idx));
2197         idx2 = extract_high_short_from_int(*int_at_addr(idx));
2198         assert(idx2 == bootstrap_name_and_type_ref_index_at(idx), "correct half of u4");
2199         Bytes::put_Java_u2((address) (bytes+1), idx1);
2200         Bytes::put_Java_u2((address) (bytes+3), idx2);
2201         DBG(printf("JVM_CONSTANT_InvokeDynamic: %hd %hd", idx1, idx2));
2202         break;
2203       }
2204     }
2205     DBG(printf("\n"));
2206     bytes += ent_size;
2207     size  += ent_size;
2208   }
2209   assert(size == cpool_size, "Size mismatch");
2210 
2211   // Keep temorarily for debugging until it's stable.
2212   DBG(print_cpool_bytes(cnt, start_bytes));
2213   return (int)(bytes - start_bytes);
2214 } /* end copy_cpool_bytes */
2215 
2216 #undef DBG
2217 
2218 
2219 void ConstantPool::set_on_stack(const bool value) {
2220   if (value) {
2221     // Only record if it's not already set.
2222     if (!on_stack()) {
2223       assert(!is_shared(), "should always be set for shared constant pools");
2224       _flags |= _on_stack;
2225       MetadataOnStackMark::record(this);
2226     }
2227   } else {
2228     // Clearing is done single-threadedly.
2229     if (!is_shared()) {
2230       _flags &= ~_on_stack;
2231     }
2232   }
2233 }
2234 
2235 // Printing
2236 
2237 void ConstantPool::print_on(outputStream* st) const {
2238   assert(is_constantPool(), "must be constantPool");
2239   st->print_cr("%s", internal_name());
2240   if (flags() != 0) {
2241     st->print(" - flags: 0x%x", flags());
2242     if (has_preresolution()) st->print(" has_preresolution");
2243     if (on_stack()) st->print(" on_stack");
2244     st->cr();
2245   }
2246   if (pool_holder() != NULL) {
2247     st->print_cr(" - holder: " INTPTR_FORMAT, p2i(pool_holder()));
2248   }
2249   st->print_cr(" - cache: " INTPTR_FORMAT, p2i(cache()));
2250   st->print_cr(" - resolved_references: " INTPTR_FORMAT, p2i(resolved_references()));
2251   st->print_cr(" - reference_map: " INTPTR_FORMAT, p2i(reference_map()));
2252   st->print_cr(" - resolved_klasses: " INTPTR_FORMAT, p2i(resolved_klasses()));
2253 
2254   for (int index = 1; index < length(); index++) {      // Index 0 is unused
2255     ((ConstantPool*)this)->print_entry_on(index, st);
2256     switch (tag_at(index).value()) {
2257       case JVM_CONSTANT_Long :
2258       case JVM_CONSTANT_Double :
2259         index++;   // Skip entry following eigth-byte constant
2260     }
2261 
2262   }
2263   st->cr();
2264 }
2265 
2266 // Print one constant pool entry
2267 void ConstantPool::print_entry_on(const int index, outputStream* st) {
2268   EXCEPTION_MARK;
2269   st->print(" - %3d : ", index);
2270   tag_at(index).print_on(st);
2271   st->print(" : ");
2272   switch (tag_at(index).value()) {
2273     case JVM_CONSTANT_Class :
2274       { Klass* k = klass_at(index, CATCH);
2275         guarantee(k != NULL, "need klass");
2276         k->print_value_on(st);
2277         st->print(" {" PTR_FORMAT "}", p2i(k));
2278       }
2279       break;
2280     case JVM_CONSTANT_Fieldref :
2281     case JVM_CONSTANT_Methodref :
2282     case JVM_CONSTANT_InterfaceMethodref :
2283       st->print("klass_index=%d", uncached_klass_ref_index_at(index));
2284       st->print(" name_and_type_index=%d", uncached_name_and_type_ref_index_at(index));
2285       break;
2286     case JVM_CONSTANT_String :
2287       unresolved_string_at(index)->print_value_on(st);
2288       break;
2289     case JVM_CONSTANT_Integer :
2290       st->print("%d", int_at(index));
2291       break;
2292     case JVM_CONSTANT_Float :
2293       st->print("%f", float_at(index));
2294       break;
2295     case JVM_CONSTANT_Long :
2296       st->print_jlong(long_at(index));
2297       break;
2298     case JVM_CONSTANT_Double :
2299       st->print("%lf", double_at(index));
2300       break;
2301     case JVM_CONSTANT_NameAndType :
2302       st->print("name_index=%d", name_ref_index_at(index));
2303       st->print(" signature_index=%d", signature_ref_index_at(index));
2304       break;
2305     case JVM_CONSTANT_Utf8 :
2306       symbol_at(index)->print_value_on(st);
2307       break;
2308     case JVM_CONSTANT_ClassIndex: {
2309         int name_index = *int_at_addr(index);
2310         st->print("klass_index=%d ", name_index);
2311         symbol_at(name_index)->print_value_on(st);
2312       }
2313       break;
2314     case JVM_CONSTANT_UnresolvedClass :               // fall-through
2315     case JVM_CONSTANT_UnresolvedClassInError: {
2316         CPKlassSlot kslot = klass_slot_at(index);
2317         int resolved_klass_index = kslot.resolved_klass_index();
2318         int name_index = kslot.name_index();
2319         assert(tag_at(name_index).is_symbol(), "sanity");
2320         symbol_at(name_index)->print_value_on(st);
2321       }
2322       break;
2323     case JVM_CONSTANT_MethodHandle :
2324     case JVM_CONSTANT_MethodHandleInError :
2325       st->print("ref_kind=%d", method_handle_ref_kind_at(index));
2326       st->print(" ref_index=%d", method_handle_index_at(index));
2327       break;
2328     case JVM_CONSTANT_MethodType :
2329     case JVM_CONSTANT_MethodTypeInError :
2330       st->print("signature_index=%d", method_type_index_at(index));
2331       break;
2332     case JVM_CONSTANT_Dynamic :
2333     case JVM_CONSTANT_DynamicInError :
2334       {
2335         st->print("bootstrap_method_index=%d", bootstrap_method_ref_index_at(index));
2336         st->print(" type_index=%d", bootstrap_name_and_type_ref_index_at(index));
2337         int argc = bootstrap_argument_count_at(index);
2338         if (argc > 0) {
2339           for (int arg_i = 0; arg_i < argc; arg_i++) {
2340             int arg = bootstrap_argument_index_at(index, arg_i);
2341             st->print((arg_i == 0 ? " arguments={%d" : ", %d"), arg);
2342           }
2343           st->print("}");
2344         }
2345       }
2346       break;
2347     case JVM_CONSTANT_InvokeDynamic :
2348       {
2349         st->print("bootstrap_method_index=%d", bootstrap_method_ref_index_at(index));
2350         st->print(" name_and_type_index=%d", bootstrap_name_and_type_ref_index_at(index));
2351         int argc = bootstrap_argument_count_at(index);
2352         if (argc > 0) {
2353           for (int arg_i = 0; arg_i < argc; arg_i++) {
2354             int arg = bootstrap_argument_index_at(index, arg_i);
2355             st->print((arg_i == 0 ? " arguments={%d" : ", %d"), arg);
2356           }
2357           st->print("}");
2358         }
2359       }
2360       break;
2361     default:
2362       ShouldNotReachHere();
2363       break;
2364   }
2365   st->cr();
2366 }
2367 
2368 void ConstantPool::print_value_on(outputStream* st) const {
2369   assert(is_constantPool(), "must be constantPool");
2370   st->print("constant pool [%d]", length());
2371   if (has_preresolution()) st->print("/preresolution");
2372   if (operands() != NULL)  st->print("/operands[%d]", operands()->length());
2373   print_address_on(st);
2374   if (pool_holder() != NULL) {
2375     st->print(" for ");
2376     pool_holder()->print_value_on(st);
2377     bool extra = (pool_holder()->constants() != this);
2378     if (extra)  st->print(" (extra)");
2379   }
2380   if (cache() != NULL) {
2381     st->print(" cache=" PTR_FORMAT, p2i(cache()));
2382   }
2383 }
2384 
2385 // Verification
2386 
2387 void ConstantPool::verify_on(outputStream* st) {
2388   guarantee(is_constantPool(), "object must be constant pool");
2389   for (int i = 0; i< length();  i++) {
2390     constantTag tag = tag_at(i);
2391     if (tag.is_klass() || tag.is_unresolved_klass()) {
2392       guarantee(klass_name_at(i)->refcount() != 0, "should have nonzero reference count");
2393     } else if (tag.is_symbol()) {
2394       Symbol* entry = symbol_at(i);
2395       guarantee(entry->refcount() != 0, "should have nonzero reference count");
2396     } else if (tag.is_string()) {
2397       Symbol* entry = unresolved_string_at(i);
2398       guarantee(entry->refcount() != 0, "should have nonzero reference count");
2399     }
2400   }
2401   if (pool_holder() != NULL) {
2402     // Note: pool_holder() can be NULL in temporary constant pools
2403     // used during constant pool merging
2404     guarantee(pool_holder()->is_klass(),    "should be klass");
2405   }
2406 }
2407 
2408 
2409 SymbolHashMap::~SymbolHashMap() {
2410   SymbolHashMapEntry* next;
2411   for (int i = 0; i < _table_size; i++) {
2412     for (SymbolHashMapEntry* cur = bucket(i); cur != NULL; cur = next) {
2413       next = cur->next();
2414       delete(cur);
2415     }
2416   }
2417   FREE_C_HEAP_ARRAY(SymbolHashMapBucket, _buckets);
2418 }
2419 
2420 void SymbolHashMap::add_entry(Symbol* sym, u2 value) {
2421   char *str = sym->as_utf8();
2422   unsigned int hash = compute_hash(str, sym->utf8_length());
2423   unsigned int index = hash % table_size();
2424 
2425   // check if already in map
2426   // we prefer the first entry since it is more likely to be what was used in
2427   // the class file
2428   for (SymbolHashMapEntry *en = bucket(index); en != NULL; en = en->next()) {
2429     assert(en->symbol() != NULL, "SymbolHashMapEntry symbol is NULL");
2430     if (en->hash() == hash && en->symbol() == sym) {
2431         return;  // already there
2432     }
2433   }
2434 
2435   SymbolHashMapEntry* entry = new SymbolHashMapEntry(hash, sym, value);
2436   entry->set_next(bucket(index));
2437   _buckets[index].set_entry(entry);
2438   assert(entry->symbol() != NULL, "SymbolHashMapEntry symbol is NULL");
2439 }
2440 
2441 SymbolHashMapEntry* SymbolHashMap::find_entry(Symbol* sym) {
2442   assert(sym != NULL, "SymbolHashMap::find_entry - symbol is NULL");
2443   char *str = sym->as_utf8();
2444   int   len = sym->utf8_length();
2445   unsigned int hash = SymbolHashMap::compute_hash(str, len);
2446   unsigned int index = hash % table_size();
2447   for (SymbolHashMapEntry *en = bucket(index); en != NULL; en = en->next()) {
2448     assert(en->symbol() != NULL, "SymbolHashMapEntry symbol is NULL");
2449     if (en->hash() == hash && en->symbol() == sym) {
2450       return en;
2451     }
2452   }
2453   return NULL;
2454 }
2455 
2456 void SymbolHashMap::initialize_table(int table_size) {
2457   _table_size = table_size;
2458   _buckets = NEW_C_HEAP_ARRAY(SymbolHashMapBucket, table_size, mtSymbol);
2459   for (int index = 0; index < table_size; index++) {
2460     _buckets[index].clear();
2461   }
2462 }