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