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