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