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   OrderAccess::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   OrderAccess::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   OrderAccess::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     if (k != NULL) {
 560       // Make sure that resolving is legal
 561       EXCEPTION_MARK;
 562       // return NULL if verification fails
 563       verify_constant_pool_resolve(this_cp, k, THREAD);
 564       if (HAS_PENDING_EXCEPTION) {
 565         CLEAR_PENDING_EXCEPTION;
 566         return NULL;
 567       }
 568       return k;
 569     } else {
 570       return k;
 571     }
 572   }
 573 }
 574 
 575 Method* ConstantPool::method_at_if_loaded(const constantPoolHandle& cpool,
 576                                                    int which) {
 577   if (cpool->cache() == NULL)  return NULL;  // nothing to load yet
 578   int cache_index = decode_cpcache_index(which, true);
 579   if (!(cache_index >= 0 && cache_index < cpool->cache()->length())) {
 580     // FIXME: should be an assert
 581     log_debug(class, resolve)("bad operand %d in:", which); cpool->print();
 582     return NULL;
 583   }
 584   ConstantPoolCacheEntry* e = cpool->cache()->entry_at(cache_index);
 585   return e->method_if_resolved(cpool);
 586 }
 587 
 588 
 589 bool ConstantPool::has_appendix_at_if_loaded(const constantPoolHandle& cpool, int which) {
 590   if (cpool->cache() == NULL)  return false;  // nothing to load yet
 591   int cache_index = decode_cpcache_index(which, true);
 592   ConstantPoolCacheEntry* e = cpool->cache()->entry_at(cache_index);
 593   return e->has_appendix();
 594 }
 595 
 596 oop ConstantPool::appendix_at_if_loaded(const constantPoolHandle& cpool, int which) {
 597   if (cpool->cache() == NULL)  return NULL;  // nothing to load yet
 598   int cache_index = decode_cpcache_index(which, true);
 599   ConstantPoolCacheEntry* e = cpool->cache()->entry_at(cache_index);
 600   return e->appendix_if_resolved(cpool);
 601 }
 602 
 603 
 604 bool ConstantPool::has_local_signature_at_if_loaded(const constantPoolHandle& cpool, int which) {
 605   if (cpool->cache() == NULL)  return false;  // nothing to load yet
 606   int cache_index = decode_cpcache_index(which, true);
 607   ConstantPoolCacheEntry* e = cpool->cache()->entry_at(cache_index);
 608   return e->has_local_signature();
 609 }
 610 
 611 Symbol* ConstantPool::impl_name_ref_at(int which, bool uncached) {
 612   int name_index = name_ref_index_at(impl_name_and_type_ref_index_at(which, uncached));
 613   return symbol_at(name_index);
 614 }
 615 
 616 
 617 Symbol* ConstantPool::impl_signature_ref_at(int which, bool uncached) {
 618   int signature_index = signature_ref_index_at(impl_name_and_type_ref_index_at(which, uncached));
 619   return symbol_at(signature_index);
 620 }
 621 
 622 int ConstantPool::impl_name_and_type_ref_index_at(int which, bool uncached) {
 623   int i = which;
 624   if (!uncached && cache() != NULL) {
 625     if (ConstantPool::is_invokedynamic_index(which)) {
 626       // Invokedynamic index is index into the constant pool cache
 627       int pool_index = invokedynamic_bootstrap_ref_index_at(which);
 628       pool_index = bootstrap_name_and_type_ref_index_at(pool_index);
 629       assert(tag_at(pool_index).is_name_and_type(), "");
 630       return pool_index;
 631     }
 632     // change byte-ordering and go via cache
 633     i = remap_instruction_operand_from_cache(which);
 634   } else {
 635     if (tag_at(which).has_bootstrap()) {
 636       int pool_index = bootstrap_name_and_type_ref_index_at(which);
 637       assert(tag_at(pool_index).is_name_and_type(), "");
 638       return pool_index;
 639     }
 640   }
 641   assert(tag_at(i).is_field_or_method(), "Corrupted constant pool");
 642   assert(!tag_at(i).has_bootstrap(), "Must be handled above");
 643   jint ref_index = *int_at_addr(i);
 644   return extract_high_short_from_int(ref_index);
 645 }
 646 
 647 constantTag ConstantPool::impl_tag_ref_at(int which, bool uncached) {
 648   int pool_index = which;
 649   if (!uncached && cache() != NULL) {
 650     if (ConstantPool::is_invokedynamic_index(which)) {
 651       // Invokedynamic index is index into resolved_references
 652       pool_index = invokedynamic_bootstrap_ref_index_at(which);
 653     } else {
 654       // change byte-ordering and go via cache
 655       pool_index = remap_instruction_operand_from_cache(which);
 656     }
 657   }
 658   return tag_at(pool_index);
 659 }
 660 
 661 int ConstantPool::impl_klass_ref_index_at(int which, bool uncached) {
 662   guarantee(!ConstantPool::is_invokedynamic_index(which),
 663             "an invokedynamic instruction does not have a klass");
 664   int i = which;
 665   if (!uncached && cache() != NULL) {
 666     // change byte-ordering and go via cache
 667     i = remap_instruction_operand_from_cache(which);
 668   }
 669   assert(tag_at(i).is_field_or_method(), "Corrupted constant pool");
 670   jint ref_index = *int_at_addr(i);
 671   return extract_low_short_from_int(ref_index);
 672 }
 673 
 674 
 675 
 676 int ConstantPool::remap_instruction_operand_from_cache(int operand) {
 677   int cpc_index = operand;
 678   DEBUG_ONLY(cpc_index -= CPCACHE_INDEX_TAG);
 679   assert((int)(u2)cpc_index == cpc_index, "clean u2");
 680   int member_index = cache()->entry_at(cpc_index)->constant_pool_index();
 681   return member_index;
 682 }
 683 
 684 
 685 void ConstantPool::verify_constant_pool_resolve(const constantPoolHandle& this_cp, Klass* k, TRAPS) {
 686   if (!(k->is_instance_klass() || k->is_objArray_klass())) {
 687     return;  // short cut, typeArray klass is always accessible
 688   }
 689   Klass* holder = this_cp->pool_holder();
 690   bool fold_type_to_class = true;
 691   LinkResolver::check_klass_accessability(holder, k, fold_type_to_class, CHECK);
 692 }
 693 
 694 
 695 int ConstantPool::name_ref_index_at(int which_nt) {
 696   jint ref_index = name_and_type_at(which_nt);
 697   return extract_low_short_from_int(ref_index);
 698 }
 699 
 700 
 701 int ConstantPool::signature_ref_index_at(int which_nt) {
 702   jint ref_index = name_and_type_at(which_nt);
 703   return extract_high_short_from_int(ref_index);
 704 }
 705 
 706 
 707 Klass* ConstantPool::klass_ref_at(int which, TRAPS) {
 708   return klass_at(klass_ref_index_at(which), THREAD);
 709 }
 710 
 711 Symbol* ConstantPool::klass_name_at(int which) const {
 712   return symbol_at(klass_slot_at(which).name_index());
 713 }
 714 
 715 Symbol* ConstantPool::klass_ref_at_noresolve(int which) {
 716   jint ref_index = klass_ref_index_at(which);
 717   return klass_at_noresolve(ref_index);
 718 }
 719 
 720 Symbol* ConstantPool::uncached_klass_ref_at_noresolve(int which) {
 721   jint ref_index = uncached_klass_ref_index_at(which);
 722   return klass_at_noresolve(ref_index);
 723 }
 724 
 725 char* ConstantPool::string_at_noresolve(int which) {
 726   return unresolved_string_at(which)->as_C_string();
 727 }
 728 
 729 BasicType ConstantPool::basic_type_for_signature_at(int which) const {
 730   return FieldType::basic_type(symbol_at(which));
 731 }
 732 
 733 
 734 void ConstantPool::resolve_string_constants_impl(const constantPoolHandle& this_cp, TRAPS) {
 735   for (int index = 1; index < this_cp->length(); index++) { // Index 0 is unused
 736     if (this_cp->tag_at(index).is_string()) {
 737       this_cp->string_at(index, CHECK);
 738     }
 739   }
 740 }
 741 
 742 Symbol* ConstantPool::exception_message(const constantPoolHandle& this_cp, int which, constantTag tag, oop pending_exception) {
 743   // Dig out the detailed message to reuse if possible
 744   Symbol* message = java_lang_Throwable::detail_message(pending_exception);
 745   if (message != NULL) {
 746     return message;
 747   }
 748 
 749   // Return specific message for the tag
 750   switch (tag.value()) {
 751   case JVM_CONSTANT_UnresolvedClass:
 752     // return the class name in the error message
 753     message = this_cp->klass_name_at(which);
 754     break;
 755   case JVM_CONSTANT_MethodHandle:
 756     // return the method handle name in the error message
 757     message = this_cp->method_handle_name_ref_at(which);
 758     break;
 759   case JVM_CONSTANT_MethodType:
 760     // return the method type signature in the error message
 761     message = this_cp->method_type_signature_at(which);
 762     break;
 763   case JVM_CONSTANT_Dynamic:
 764     // return the name of the condy in the error message
 765     message = this_cp->uncached_name_ref_at(which);
 766     break;
 767   default:
 768     ShouldNotReachHere();
 769   }
 770 
 771   return message;
 772 }
 773 
 774 void ConstantPool::throw_resolution_error(const constantPoolHandle& this_cp, int which, TRAPS) {
 775   Symbol* message = NULL;
 776   Symbol* error = SystemDictionary::find_resolution_error(this_cp, which, &message);
 777   assert(error != NULL, "checking");
 778   CLEAR_PENDING_EXCEPTION;
 779   if (message != NULL) {
 780     ResourceMark rm;
 781     THROW_MSG(error, message->as_C_string());
 782   } else {
 783     THROW(error);
 784   }
 785 }
 786 
 787 // If resolution for Class, Dynamic constant, MethodHandle or MethodType fails, save the
 788 // exception in the resolution error table, so that the same exception is thrown again.
 789 void ConstantPool::save_and_throw_exception(const constantPoolHandle& this_cp, int which,
 790                                             constantTag tag, TRAPS) {
 791   Symbol* error = PENDING_EXCEPTION->klass()->name();
 792 
 793   int error_tag = tag.error_value();
 794 
 795   if (!PENDING_EXCEPTION->
 796     is_a(SystemDictionary::LinkageError_klass())) {
 797     // Just throw the exception and don't prevent these classes from
 798     // being loaded due to virtual machine errors like StackOverflow
 799     // and OutOfMemoryError, etc, or if the thread was hit by stop()
 800     // Needs clarification to section 5.4.3 of the VM spec (see 6308271)
 801   } else if (this_cp->tag_at(which).value() != error_tag) {
 802     Symbol* message = exception_message(this_cp, which, tag, PENDING_EXCEPTION);
 803     SystemDictionary::add_resolution_error(this_cp, which, error, message);
 804     // CAS in the tag.  If a thread beat us to registering this error that's fine.
 805     // If another thread resolved the reference, this is a race condition. This
 806     // thread may have had a security manager or something temporary.
 807     // This doesn't deterministically get an error.   So why do we save this?
 808     // We save this because jvmti can add classes to the bootclass path after
 809     // this error, so it needs to get the same error if the error is first.
 810     jbyte old_tag = Atomic::cmpxchg((jbyte)error_tag,
 811                             (jbyte*)this_cp->tag_addr_at(which), (jbyte)tag.value());
 812     if (old_tag != error_tag && old_tag != tag.value()) {
 813       // MethodHandles and MethodType doesn't change to resolved version.
 814       assert(this_cp->tag_at(which).is_klass(), "Wrong tag value");
 815       // Forget the exception and use the resolved class.
 816       CLEAR_PENDING_EXCEPTION;
 817     }
 818   } else {
 819     // some other thread put this in error state
 820     throw_resolution_error(this_cp, which, CHECK);
 821   }
 822 }
 823 
 824 constantTag ConstantPool::constant_tag_at(int which) {
 825   constantTag tag = tag_at(which);
 826   if (tag.is_dynamic_constant() ||
 827       tag.is_dynamic_constant_in_error()) {
 828     BasicType bt = basic_type_for_constant_at(which);
 829     // dynamic constant could return an array, treat as object
 830     return constantTag::ofBasicType(is_reference_type(bt) ? T_OBJECT : bt);
 831   }
 832   return tag;
 833 }
 834 
 835 BasicType ConstantPool::basic_type_for_constant_at(int which) {
 836   constantTag tag = tag_at(which);
 837   if (tag.is_dynamic_constant() ||
 838       tag.is_dynamic_constant_in_error()) {
 839     // have to look at the signature for this one
 840     Symbol* constant_type = uncached_signature_ref_at(which);
 841     return FieldType::basic_type(constant_type);
 842   }
 843   return tag.basic_type();
 844 }
 845 
 846 // Called to resolve constants in the constant pool and return an oop.
 847 // Some constant pool entries cache their resolved oop. This is also
 848 // called to create oops from constants to use in arguments for invokedynamic
 849 oop ConstantPool::resolve_constant_at_impl(const constantPoolHandle& this_cp,
 850                                            int index, int cache_index,
 851                                            bool* status_return, TRAPS) {
 852   oop result_oop = NULL;
 853   Handle throw_exception;
 854 
 855   if (cache_index == _possible_index_sentinel) {
 856     // It is possible that this constant is one which is cached in the objects.
 857     // We'll do a linear search.  This should be OK because this usage is rare.
 858     // FIXME: If bootstrap specifiers stress this code, consider putting in
 859     // a reverse index.  Binary search over a short array should do it.
 860     assert(index > 0, "valid index");
 861     cache_index = this_cp->cp_to_object_index(index);
 862   }
 863   assert(cache_index == _no_index_sentinel || cache_index >= 0, "");
 864   assert(index == _no_index_sentinel || index >= 0, "");
 865 
 866   if (cache_index >= 0) {
 867     result_oop = this_cp->resolved_references()->obj_at(cache_index);
 868     if (result_oop != NULL) {
 869       if (oopDesc::equals(result_oop, Universe::the_null_sentinel())) {
 870         DEBUG_ONLY(int temp_index = (index >= 0 ? index : this_cp->object_to_cp_index(cache_index)));
 871         assert(this_cp->tag_at(temp_index).is_dynamic_constant(), "only condy uses the null sentinel");
 872         result_oop = NULL;
 873       }
 874       if (status_return != NULL)  (*status_return) = true;
 875       return result_oop;
 876       // That was easy...
 877     }
 878     index = this_cp->object_to_cp_index(cache_index);
 879   }
 880 
 881   jvalue prim_value;  // temp used only in a few cases below
 882 
 883   constantTag tag = this_cp->tag_at(index);
 884 
 885   if (status_return != NULL) {
 886     // don't trigger resolution if the constant might need it
 887     switch (tag.value()) {
 888     case JVM_CONSTANT_Class:
 889     {
 890       CPKlassSlot kslot = this_cp->klass_slot_at(index);
 891       int resolved_klass_index = kslot.resolved_klass_index();
 892       if (this_cp->resolved_klasses()->at(resolved_klass_index) == NULL) {
 893         (*status_return) = false;
 894         return NULL;
 895       }
 896       // the klass is waiting in the CP; go get it
 897       break;
 898     }
 899     case JVM_CONSTANT_String:
 900     case JVM_CONSTANT_Integer:
 901     case JVM_CONSTANT_Float:
 902     case JVM_CONSTANT_Long:
 903     case JVM_CONSTANT_Double:
 904       // these guys trigger OOM at worst
 905       break;
 906     default:
 907       (*status_return) = false;
 908       return NULL;
 909     }
 910     // from now on there is either success or an OOME
 911     (*status_return) = true;
 912   }
 913 
 914   switch (tag.value()) {
 915 
 916   case JVM_CONSTANT_UnresolvedClass:
 917   case JVM_CONSTANT_UnresolvedClassInError:
 918   case JVM_CONSTANT_Class:
 919     {
 920       assert(cache_index == _no_index_sentinel, "should not have been set");
 921       Klass* resolved = klass_at_impl(this_cp, index, true, CHECK_NULL);
 922       // ldc wants the java mirror.
 923       result_oop = resolved->java_mirror();
 924       break;
 925     }
 926 
 927   case JVM_CONSTANT_Dynamic:
 928     {
 929       // Resolve the Dynamically-Computed constant to invoke the BSM in order to obtain the resulting oop.
 930       BootstrapInfo bootstrap_specifier(this_cp, index);
 931 
 932       // The initial step in resolving an unresolved symbolic reference to a
 933       // dynamically-computed constant is to resolve the symbolic reference to a
 934       // method handle which will be the bootstrap method for the dynamically-computed
 935       // constant. If resolution of the java.lang.invoke.MethodHandle for the bootstrap
 936       // method fails, then a MethodHandleInError is stored at the corresponding
 937       // bootstrap method's CP index for the CONSTANT_MethodHandle_info. No need to
 938       // set a DynamicConstantInError here since any subsequent use of this
 939       // bootstrap method will encounter the resolution of MethodHandleInError.
 940       // Both the first, (resolution of the BSM and its static arguments), and the second tasks,
 941       // (invocation of the BSM), of JVMS Section 5.4.3.6 occur within invoke_bootstrap_method()
 942       // for the bootstrap_specifier created above.
 943       SystemDictionary::invoke_bootstrap_method(bootstrap_specifier, THREAD);
 944       Exceptions::wrap_dynamic_exception(THREAD);
 945       if (HAS_PENDING_EXCEPTION) {
 946         // Resolution failure of the dynamically-computed constant, save_and_throw_exception
 947         // will check for a LinkageError and store a DynamicConstantInError.
 948         save_and_throw_exception(this_cp, index, tag, CHECK_NULL);
 949       }
 950       result_oop = bootstrap_specifier.resolved_value()();
 951       BasicType type = FieldType::basic_type(bootstrap_specifier.signature());
 952       if (!is_reference_type(type)) {
 953         // Make sure the primitive value is properly boxed.
 954         // This is a JDK responsibility.
 955         const char* fail = NULL;
 956         if (result_oop == NULL) {
 957           fail = "null result instead of box";
 958         } else if (!is_java_primitive(type)) {
 959           // FIXME: support value types via unboxing
 960           fail = "can only handle references and primitives";
 961         } else if (!java_lang_boxing_object::is_instance(result_oop, type)) {
 962           fail = "primitive is not properly boxed";
 963         }
 964         if (fail != NULL) {
 965           // Since this exception is not a LinkageError, throw exception
 966           // but do not save a DynamicInError resolution result.
 967           // See section 5.4.3 of the VM spec.
 968           THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), fail);
 969         }
 970       }
 971 
 972       if (TraceMethodHandles) {
 973         bootstrap_specifier.print_msg_on(tty, "resolve_constant_at_impl");
 974       }
 975       break;
 976     }
 977 
 978   case JVM_CONSTANT_String:
 979     assert(cache_index != _no_index_sentinel, "should have been set");
 980     if (this_cp->is_pseudo_string_at(index)) {
 981       result_oop = this_cp->pseudo_string_at(index, cache_index);
 982       break;
 983     }
 984     result_oop = string_at_impl(this_cp, index, cache_index, CHECK_NULL);
 985     break;
 986 
 987   case JVM_CONSTANT_DynamicInError:
 988   case JVM_CONSTANT_MethodHandleInError:
 989   case JVM_CONSTANT_MethodTypeInError:
 990     {
 991       throw_resolution_error(this_cp, index, CHECK_NULL);
 992       break;
 993     }
 994 
 995   case JVM_CONSTANT_MethodHandle:
 996     {
 997       int ref_kind                 = this_cp->method_handle_ref_kind_at(index);
 998       int callee_index             = this_cp->method_handle_klass_index_at(index);
 999       Symbol*  name =      this_cp->method_handle_name_ref_at(index);
1000       Symbol*  signature = this_cp->method_handle_signature_ref_at(index);
1001       constantTag m_tag  = this_cp->tag_at(this_cp->method_handle_index_at(index));
1002       { ResourceMark rm(THREAD);
1003         log_debug(class, resolve)("resolve JVM_CONSTANT_MethodHandle:%d [%d/%d/%d] %s.%s",
1004                               ref_kind, index, this_cp->method_handle_index_at(index),
1005                               callee_index, name->as_C_string(), signature->as_C_string());
1006       }
1007 
1008       Klass* callee = klass_at_impl(this_cp, callee_index, true, CHECK_NULL);
1009 
1010       // Check constant pool method consistency
1011       if ((callee->is_interface() && m_tag.is_method()) ||
1012           ((!callee->is_interface() && m_tag.is_interface_method()))) {
1013         ResourceMark rm(THREAD);
1014         stringStream ss;
1015         ss.print("Inconsistent constant pool data in classfile for class %s. "
1016                  "Method '", callee->name()->as_C_string());
1017         signature->print_as_signature_external_return_type(&ss);
1018         ss.print(" %s(", name->as_C_string());
1019         signature->print_as_signature_external_parameters(&ss);
1020         ss.print(")' at index %d is %s and should be %s",
1021                  index,
1022                  callee->is_interface() ? "CONSTANT_MethodRef" : "CONSTANT_InterfaceMethodRef",
1023                  callee->is_interface() ? "CONSTANT_InterfaceMethodRef" : "CONSTANT_MethodRef");
1024         THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());
1025       }
1026 
1027       Klass* klass = this_cp->pool_holder();
1028       Handle value = SystemDictionary::link_method_handle_constant(klass, ref_kind,
1029                                                                    callee, name, signature,
1030                                                                    THREAD);
1031       result_oop = value();
1032       if (HAS_PENDING_EXCEPTION) {
1033         save_and_throw_exception(this_cp, index, tag, CHECK_NULL);
1034       }
1035       break;
1036     }
1037 
1038   case JVM_CONSTANT_MethodType:
1039     {
1040       Symbol*  signature = this_cp->method_type_signature_at(index);
1041       { ResourceMark rm(THREAD);
1042         log_debug(class, resolve)("resolve JVM_CONSTANT_MethodType [%d/%d] %s",
1043                               index, this_cp->method_type_index_at(index),
1044                               signature->as_C_string());
1045       }
1046       Klass* klass = this_cp->pool_holder();
1047       Handle value = SystemDictionary::find_method_handle_type(signature, klass, THREAD);
1048       result_oop = value();
1049       if (HAS_PENDING_EXCEPTION) {
1050         save_and_throw_exception(this_cp, index, tag, CHECK_NULL);
1051       }
1052       break;
1053     }
1054 
1055   case JVM_CONSTANT_Integer:
1056     assert(cache_index == _no_index_sentinel, "should not have been set");
1057     prim_value.i = this_cp->int_at(index);
1058     result_oop = java_lang_boxing_object::create(T_INT, &prim_value, CHECK_NULL);
1059     break;
1060 
1061   case JVM_CONSTANT_Float:
1062     assert(cache_index == _no_index_sentinel, "should not have been set");
1063     prim_value.f = this_cp->float_at(index);
1064     result_oop = java_lang_boxing_object::create(T_FLOAT, &prim_value, CHECK_NULL);
1065     break;
1066 
1067   case JVM_CONSTANT_Long:
1068     assert(cache_index == _no_index_sentinel, "should not have been set");
1069     prim_value.j = this_cp->long_at(index);
1070     result_oop = java_lang_boxing_object::create(T_LONG, &prim_value, CHECK_NULL);
1071     break;
1072 
1073   case JVM_CONSTANT_Double:
1074     assert(cache_index == _no_index_sentinel, "should not have been set");
1075     prim_value.d = this_cp->double_at(index);
1076     result_oop = java_lang_boxing_object::create(T_DOUBLE, &prim_value, CHECK_NULL);
1077     break;
1078 
1079   default:
1080     DEBUG_ONLY( tty->print_cr("*** %p: tag at CP[%d/%d] = %d",
1081                               this_cp(), index, cache_index, tag.value()));
1082     assert(false, "unexpected constant tag");
1083     break;
1084   }
1085 
1086   if (cache_index >= 0) {
1087     // Benign race condition:  resolved_references may already be filled in.
1088     // The important thing here is that all threads pick up the same result.
1089     // It doesn't matter which racing thread wins, as long as only one
1090     // result is used by all threads, and all future queries.
1091     oop new_result = (result_oop == NULL ? Universe::the_null_sentinel() : result_oop);
1092     oop old_result = this_cp->resolved_references()
1093       ->atomic_compare_exchange_oop(cache_index, new_result, NULL);
1094     if (old_result == NULL) {
1095       return result_oop;  // was installed
1096     } else {
1097       // Return the winning thread's result.  This can be different than
1098       // the result here for MethodHandles.
1099       if (oopDesc::equals(old_result, Universe::the_null_sentinel()))
1100         old_result = NULL;
1101       return old_result;
1102     }
1103   } else {
1104     assert(!oopDesc::equals(result_oop, Universe::the_null_sentinel()), "");
1105     return result_oop;
1106   }
1107 }
1108 
1109 oop ConstantPool::uncached_string_at(int which, TRAPS) {
1110   Symbol* sym = unresolved_string_at(which);
1111   oop str = StringTable::intern(sym, CHECK_(NULL));
1112   assert(java_lang_String::is_instance(str), "must be string");
1113   return str;
1114 }
1115 
1116 void ConstantPool::copy_bootstrap_arguments_at_impl(const constantPoolHandle& this_cp, int index,
1117                                                     int start_arg, int end_arg,
1118                                                     objArrayHandle info, int pos,
1119                                                     bool must_resolve, Handle if_not_available,
1120                                                     TRAPS) {
1121   int argc;
1122   int limit = pos + end_arg - start_arg;
1123   // checks: index in range [0..this_cp->length),
1124   // tag at index, start..end in range [0..argc],
1125   // info array non-null, pos..limit in [0..info.length]
1126   if ((0 >= index    || index >= this_cp->length())  ||
1127       !(this_cp->tag_at(index).is_invoke_dynamic()    ||
1128         this_cp->tag_at(index).is_dynamic_constant()) ||
1129       (0 > start_arg || start_arg > end_arg) ||
1130       (end_arg > (argc = this_cp->bootstrap_argument_count_at(index))) ||
1131       (0 > pos       || pos > limit)         ||
1132       (info.is_null() || limit > info->length())) {
1133     // An index or something else went wrong; throw an error.
1134     // Since this is an internal API, we don't expect this,
1135     // so we don't bother to craft a nice message.
1136     THROW_MSG(vmSymbols::java_lang_LinkageError(), "bad BSM argument access");
1137   }
1138   // now we can loop safely
1139   int info_i = pos;
1140   for (int i = start_arg; i < end_arg; i++) {
1141     int arg_index = this_cp->bootstrap_argument_index_at(index, i);
1142     oop arg_oop;
1143     if (must_resolve) {
1144       arg_oop = this_cp->resolve_possibly_cached_constant_at(arg_index, CHECK);
1145     } else {
1146       bool found_it = false;
1147       arg_oop = this_cp->find_cached_constant_at(arg_index, found_it, CHECK);
1148       if (!found_it)  arg_oop = if_not_available();
1149     }
1150     info->obj_at_put(info_i++, arg_oop);
1151   }
1152 }
1153 
1154 oop ConstantPool::string_at_impl(const constantPoolHandle& this_cp, int which, int obj_index, TRAPS) {
1155   // If the string has already been interned, this entry will be non-null
1156   oop str = this_cp->resolved_references()->obj_at(obj_index);
1157   assert(!oopDesc::equals(str, Universe::the_null_sentinel()), "");
1158   if (str != NULL) return str;
1159   Symbol* sym = this_cp->unresolved_string_at(which);
1160   str = StringTable::intern(sym, CHECK_(NULL));
1161   this_cp->string_at_put(which, obj_index, str);
1162   assert(java_lang_String::is_instance(str), "must be string");
1163   return str;
1164 }
1165 
1166 
1167 bool ConstantPool::klass_name_at_matches(const InstanceKlass* k, int which) {
1168   // Names are interned, so we can compare Symbol*s directly
1169   Symbol* cp_name = klass_name_at(which);
1170   return (cp_name == k->name());
1171 }
1172 
1173 
1174 // Iterate over symbols and decrement ones which are Symbol*s
1175 // This is done during GC.
1176 // Only decrement the UTF8 symbols. Strings point to
1177 // these symbols but didn't increment the reference count.
1178 void ConstantPool::unreference_symbols() {
1179   for (int index = 1; index < length(); index++) { // Index 0 is unused
1180     constantTag tag = tag_at(index);
1181     if (tag.is_symbol()) {
1182       symbol_at(index)->decrement_refcount();
1183     }
1184   }
1185 }
1186 
1187 
1188 // Compare this constant pool's entry at index1 to the constant pool
1189 // cp2's entry at index2.
1190 bool ConstantPool::compare_entry_to(int index1, const constantPoolHandle& cp2,
1191        int index2, TRAPS) {
1192 
1193   // The error tags are equivalent to non-error tags when comparing
1194   jbyte t1 = tag_at(index1).non_error_value();
1195   jbyte t2 = cp2->tag_at(index2).non_error_value();
1196 
1197   if (t1 != t2) {
1198     // Not the same entry type so there is nothing else to check. Note
1199     // that this style of checking will consider resolved/unresolved
1200     // class pairs as different.
1201     // From the ConstantPool* API point of view, this is correct
1202     // behavior. See VM_RedefineClasses::merge_constant_pools() to see how this
1203     // plays out in the context of ConstantPool* merging.
1204     return false;
1205   }
1206 
1207   switch (t1) {
1208   case JVM_CONSTANT_Class:
1209   {
1210     Klass* k1 = klass_at(index1, CHECK_false);
1211     Klass* k2 = cp2->klass_at(index2, CHECK_false);
1212     if (k1 == k2) {
1213       return true;
1214     }
1215   } break;
1216 
1217   case JVM_CONSTANT_ClassIndex:
1218   {
1219     int recur1 = klass_index_at(index1);
1220     int recur2 = cp2->klass_index_at(index2);
1221     bool match = compare_entry_to(recur1, cp2, recur2, CHECK_false);
1222     if (match) {
1223       return true;
1224     }
1225   } break;
1226 
1227   case JVM_CONSTANT_Double:
1228   {
1229     jdouble d1 = double_at(index1);
1230     jdouble d2 = cp2->double_at(index2);
1231     if (d1 == d2) {
1232       return true;
1233     }
1234   } break;
1235 
1236   case JVM_CONSTANT_Fieldref:
1237   case JVM_CONSTANT_InterfaceMethodref:
1238   case JVM_CONSTANT_Methodref:
1239   {
1240     int recur1 = uncached_klass_ref_index_at(index1);
1241     int recur2 = cp2->uncached_klass_ref_index_at(index2);
1242     bool match = compare_entry_to(recur1, cp2, recur2, CHECK_false);
1243     if (match) {
1244       recur1 = uncached_name_and_type_ref_index_at(index1);
1245       recur2 = cp2->uncached_name_and_type_ref_index_at(index2);
1246       match = compare_entry_to(recur1, cp2, recur2, CHECK_false);
1247       if (match) {
1248         return true;
1249       }
1250     }
1251   } break;
1252 
1253   case JVM_CONSTANT_Float:
1254   {
1255     jfloat f1 = float_at(index1);
1256     jfloat f2 = cp2->float_at(index2);
1257     if (f1 == f2) {
1258       return true;
1259     }
1260   } break;
1261 
1262   case JVM_CONSTANT_Integer:
1263   {
1264     jint i1 = int_at(index1);
1265     jint i2 = cp2->int_at(index2);
1266     if (i1 == i2) {
1267       return true;
1268     }
1269   } break;
1270 
1271   case JVM_CONSTANT_Long:
1272   {
1273     jlong l1 = long_at(index1);
1274     jlong l2 = cp2->long_at(index2);
1275     if (l1 == l2) {
1276       return true;
1277     }
1278   } break;
1279 
1280   case JVM_CONSTANT_NameAndType:
1281   {
1282     int recur1 = name_ref_index_at(index1);
1283     int recur2 = cp2->name_ref_index_at(index2);
1284     bool match = compare_entry_to(recur1, cp2, recur2, CHECK_false);
1285     if (match) {
1286       recur1 = signature_ref_index_at(index1);
1287       recur2 = cp2->signature_ref_index_at(index2);
1288       match = compare_entry_to(recur1, cp2, recur2, CHECK_false);
1289       if (match) {
1290         return true;
1291       }
1292     }
1293   } break;
1294 
1295   case JVM_CONSTANT_StringIndex:
1296   {
1297     int recur1 = string_index_at(index1);
1298     int recur2 = cp2->string_index_at(index2);
1299     bool match = compare_entry_to(recur1, cp2, recur2, CHECK_false);
1300     if (match) {
1301       return true;
1302     }
1303   } break;
1304 
1305   case JVM_CONSTANT_UnresolvedClass:
1306   {
1307     Symbol* k1 = klass_name_at(index1);
1308     Symbol* k2 = cp2->klass_name_at(index2);
1309     if (k1 == k2) {
1310       return true;
1311     }
1312   } break;
1313 
1314   case JVM_CONSTANT_MethodType:
1315   {
1316     int k1 = method_type_index_at(index1);
1317     int k2 = cp2->method_type_index_at(index2);
1318     bool match = compare_entry_to(k1, cp2, k2, CHECK_false);
1319     if (match) {
1320       return true;
1321     }
1322   } break;
1323 
1324   case JVM_CONSTANT_MethodHandle:
1325   {
1326     int k1 = method_handle_ref_kind_at(index1);
1327     int k2 = cp2->method_handle_ref_kind_at(index2);
1328     if (k1 == k2) {
1329       int i1 = method_handle_index_at(index1);
1330       int i2 = cp2->method_handle_index_at(index2);
1331       bool match = compare_entry_to(i1, cp2, i2, CHECK_false);
1332       if (match) {
1333         return true;
1334       }
1335     }
1336   } break;
1337 
1338   case JVM_CONSTANT_Dynamic:
1339   {
1340     int k1 = bootstrap_name_and_type_ref_index_at(index1);
1341     int k2 = cp2->bootstrap_name_and_type_ref_index_at(index2);
1342     int i1 = bootstrap_methods_attribute_index(index1);
1343     int i2 = cp2->bootstrap_methods_attribute_index(index2);
1344     // separate statements and variables because CHECK_false is used
1345     bool match_entry = compare_entry_to(k1, cp2, k2, CHECK_false);
1346     bool match_operand = compare_operand_to(i1, cp2, i2, CHECK_false);
1347     return (match_entry && match_operand);
1348   } break;
1349 
1350   case JVM_CONSTANT_InvokeDynamic:
1351   {
1352     int k1 = bootstrap_name_and_type_ref_index_at(index1);
1353     int k2 = cp2->bootstrap_name_and_type_ref_index_at(index2);
1354     int i1 = bootstrap_methods_attribute_index(index1);
1355     int i2 = cp2->bootstrap_methods_attribute_index(index2);
1356     // separate statements and variables because CHECK_false is used
1357     bool match_entry = compare_entry_to(k1, cp2, k2, CHECK_false);
1358     bool match_operand = compare_operand_to(i1, cp2, i2, CHECK_false);
1359     return (match_entry && match_operand);
1360   } break;
1361 
1362   case JVM_CONSTANT_String:
1363   {
1364     Symbol* s1 = unresolved_string_at(index1);
1365     Symbol* s2 = cp2->unresolved_string_at(index2);
1366     if (s1 == s2) {
1367       return true;
1368     }
1369   } break;
1370 
1371   case JVM_CONSTANT_Utf8:
1372   {
1373     Symbol* s1 = symbol_at(index1);
1374     Symbol* s2 = cp2->symbol_at(index2);
1375     if (s1 == s2) {
1376       return true;
1377     }
1378   } break;
1379 
1380   // Invalid is used as the tag for the second constant pool entry
1381   // occupied by JVM_CONSTANT_Double or JVM_CONSTANT_Long. It should
1382   // not be seen by itself.
1383   case JVM_CONSTANT_Invalid: // fall through
1384 
1385   default:
1386     ShouldNotReachHere();
1387     break;
1388   }
1389 
1390   return false;
1391 } // end compare_entry_to()
1392 
1393 
1394 // Resize the operands array with delta_len and delta_size.
1395 // Used in RedefineClasses for CP merge.
1396 void ConstantPool::resize_operands(int delta_len, int delta_size, TRAPS) {
1397   int old_len  = operand_array_length(operands());
1398   int new_len  = old_len + delta_len;
1399   int min_len  = (delta_len > 0) ? old_len : new_len;
1400 
1401   int old_size = operands()->length();
1402   int new_size = old_size + delta_size;
1403   int min_size = (delta_size > 0) ? old_size : new_size;
1404 
1405   ClassLoaderData* loader_data = pool_holder()->class_loader_data();
1406   Array<u2>* new_ops = MetadataFactory::new_array<u2>(loader_data, new_size, CHECK);
1407 
1408   // Set index in the resized array for existing elements only
1409   for (int idx = 0; idx < min_len; idx++) {
1410     int offset = operand_offset_at(idx);                       // offset in original array
1411     operand_offset_at_put(new_ops, idx, offset + 2*delta_len); // offset in resized array
1412   }
1413   // Copy the bootstrap specifiers only
1414   Copy::conjoint_memory_atomic(operands()->adr_at(2*old_len),
1415                                new_ops->adr_at(2*new_len),
1416                                (min_size - 2*min_len) * sizeof(u2));
1417   // Explicitly deallocate old operands array.
1418   // Note, it is not needed for 7u backport.
1419   if ( operands() != NULL) { // the safety check
1420     MetadataFactory::free_array<u2>(loader_data, operands());
1421   }
1422   set_operands(new_ops);
1423 } // end resize_operands()
1424 
1425 
1426 // Extend the operands array with the length and size of the ext_cp operands.
1427 // Used in RedefineClasses for CP merge.
1428 void ConstantPool::extend_operands(const constantPoolHandle& ext_cp, TRAPS) {
1429   int delta_len = operand_array_length(ext_cp->operands());
1430   if (delta_len == 0) {
1431     return; // nothing to do
1432   }
1433   int delta_size = ext_cp->operands()->length();
1434 
1435   assert(delta_len  > 0 && delta_size > 0, "extended operands array must be bigger");
1436 
1437   if (operand_array_length(operands()) == 0) {
1438     ClassLoaderData* loader_data = pool_holder()->class_loader_data();
1439     Array<u2>* new_ops = MetadataFactory::new_array<u2>(loader_data, delta_size, CHECK);
1440     // The first element index defines the offset of second part
1441     operand_offset_at_put(new_ops, 0, 2*delta_len); // offset in new array
1442     set_operands(new_ops);
1443   } else {
1444     resize_operands(delta_len, delta_size, CHECK);
1445   }
1446 
1447 } // end extend_operands()
1448 
1449 
1450 // Shrink the operands array to a smaller array with new_len length.
1451 // Used in RedefineClasses for CP merge.
1452 void ConstantPool::shrink_operands(int new_len, TRAPS) {
1453   int old_len = operand_array_length(operands());
1454   if (new_len == old_len) {
1455     return; // nothing to do
1456   }
1457   assert(new_len < old_len, "shrunken operands array must be smaller");
1458 
1459   int free_base  = operand_next_offset_at(new_len - 1);
1460   int delta_len  = new_len - old_len;
1461   int delta_size = 2*delta_len + free_base - operands()->length();
1462 
1463   resize_operands(delta_len, delta_size, CHECK);
1464 
1465 } // end shrink_operands()
1466 
1467 
1468 void ConstantPool::copy_operands(const constantPoolHandle& from_cp,
1469                                  const constantPoolHandle& to_cp,
1470                                  TRAPS) {
1471 
1472   int from_oplen = operand_array_length(from_cp->operands());
1473   int old_oplen  = operand_array_length(to_cp->operands());
1474   if (from_oplen != 0) {
1475     ClassLoaderData* loader_data = to_cp->pool_holder()->class_loader_data();
1476     // append my operands to the target's operands array
1477     if (old_oplen == 0) {
1478       // Can't just reuse from_cp's operand list because of deallocation issues
1479       int len = from_cp->operands()->length();
1480       Array<u2>* new_ops = MetadataFactory::new_array<u2>(loader_data, len, CHECK);
1481       Copy::conjoint_memory_atomic(
1482           from_cp->operands()->adr_at(0), new_ops->adr_at(0), len * sizeof(u2));
1483       to_cp->set_operands(new_ops);
1484     } else {
1485       int old_len  = to_cp->operands()->length();
1486       int from_len = from_cp->operands()->length();
1487       int old_off  = old_oplen * sizeof(u2);
1488       int from_off = from_oplen * sizeof(u2);
1489       // Use the metaspace for the destination constant pool
1490       Array<u2>* new_operands = MetadataFactory::new_array<u2>(loader_data, old_len + from_len, CHECK);
1491       int fillp = 0, len = 0;
1492       // first part of dest
1493       Copy::conjoint_memory_atomic(to_cp->operands()->adr_at(0),
1494                                    new_operands->adr_at(fillp),
1495                                    (len = old_off) * sizeof(u2));
1496       fillp += len;
1497       // first part of src
1498       Copy::conjoint_memory_atomic(from_cp->operands()->adr_at(0),
1499                                    new_operands->adr_at(fillp),
1500                                    (len = from_off) * sizeof(u2));
1501       fillp += len;
1502       // second part of dest
1503       Copy::conjoint_memory_atomic(to_cp->operands()->adr_at(old_off),
1504                                    new_operands->adr_at(fillp),
1505                                    (len = old_len - old_off) * sizeof(u2));
1506       fillp += len;
1507       // second part of src
1508       Copy::conjoint_memory_atomic(from_cp->operands()->adr_at(from_off),
1509                                    new_operands->adr_at(fillp),
1510                                    (len = from_len - from_off) * sizeof(u2));
1511       fillp += len;
1512       assert(fillp == new_operands->length(), "");
1513 
1514       // Adjust indexes in the first part of the copied operands array.
1515       for (int j = 0; j < from_oplen; j++) {
1516         int offset = operand_offset_at(new_operands, old_oplen + j);
1517         assert(offset == operand_offset_at(from_cp->operands(), j), "correct copy");
1518         offset += old_len;  // every new tuple is preceded by old_len extra u2's
1519         operand_offset_at_put(new_operands, old_oplen + j, offset);
1520       }
1521 
1522       // replace target operands array with combined array
1523       to_cp->set_operands(new_operands);
1524     }
1525   }
1526 } // end copy_operands()
1527 
1528 
1529 // Copy this constant pool's entries at start_i to end_i (inclusive)
1530 // to the constant pool to_cp's entries starting at to_i. A total of
1531 // (end_i - start_i) + 1 entries are copied.
1532 void ConstantPool::copy_cp_to_impl(const constantPoolHandle& from_cp, int start_i, int end_i,
1533        const constantPoolHandle& to_cp, int to_i, TRAPS) {
1534 
1535 
1536   int dest_i = to_i;  // leave original alone for debug purposes
1537 
1538   for (int src_i = start_i; src_i <= end_i; /* see loop bottom */ ) {
1539     copy_entry_to(from_cp, src_i, to_cp, dest_i, CHECK);
1540 
1541     switch (from_cp->tag_at(src_i).value()) {
1542     case JVM_CONSTANT_Double:
1543     case JVM_CONSTANT_Long:
1544       // double and long take two constant pool entries
1545       src_i += 2;
1546       dest_i += 2;
1547       break;
1548 
1549     default:
1550       // all others take one constant pool entry
1551       src_i++;
1552       dest_i++;
1553       break;
1554     }
1555   }
1556   copy_operands(from_cp, to_cp, CHECK);
1557 
1558 } // end copy_cp_to_impl()
1559 
1560 
1561 // Copy this constant pool's entry at from_i to the constant pool
1562 // to_cp's entry at to_i.
1563 void ConstantPool::copy_entry_to(const constantPoolHandle& from_cp, int from_i,
1564                                         const constantPoolHandle& to_cp, int to_i,
1565                                         TRAPS) {
1566 
1567   int tag = from_cp->tag_at(from_i).value();
1568   switch (tag) {
1569   case JVM_CONSTANT_ClassIndex:
1570   {
1571     jint ki = from_cp->klass_index_at(from_i);
1572     to_cp->klass_index_at_put(to_i, ki);
1573   } break;
1574 
1575   case JVM_CONSTANT_Double:
1576   {
1577     jdouble d = from_cp->double_at(from_i);
1578     to_cp->double_at_put(to_i, d);
1579     // double takes two constant pool entries so init second entry's tag
1580     to_cp->tag_at_put(to_i + 1, JVM_CONSTANT_Invalid);
1581   } break;
1582 
1583   case JVM_CONSTANT_Fieldref:
1584   {
1585     int class_index = from_cp->uncached_klass_ref_index_at(from_i);
1586     int name_and_type_index = from_cp->uncached_name_and_type_ref_index_at(from_i);
1587     to_cp->field_at_put(to_i, class_index, name_and_type_index);
1588   } break;
1589 
1590   case JVM_CONSTANT_Float:
1591   {
1592     jfloat f = from_cp->float_at(from_i);
1593     to_cp->float_at_put(to_i, f);
1594   } break;
1595 
1596   case JVM_CONSTANT_Integer:
1597   {
1598     jint i = from_cp->int_at(from_i);
1599     to_cp->int_at_put(to_i, i);
1600   } break;
1601 
1602   case JVM_CONSTANT_InterfaceMethodref:
1603   {
1604     int class_index = from_cp->uncached_klass_ref_index_at(from_i);
1605     int name_and_type_index = from_cp->uncached_name_and_type_ref_index_at(from_i);
1606     to_cp->interface_method_at_put(to_i, class_index, name_and_type_index);
1607   } break;
1608 
1609   case JVM_CONSTANT_Long:
1610   {
1611     jlong l = from_cp->long_at(from_i);
1612     to_cp->long_at_put(to_i, l);
1613     // long takes two constant pool entries so init second entry's tag
1614     to_cp->tag_at_put(to_i + 1, JVM_CONSTANT_Invalid);
1615   } break;
1616 
1617   case JVM_CONSTANT_Methodref:
1618   {
1619     int class_index = from_cp->uncached_klass_ref_index_at(from_i);
1620     int name_and_type_index = from_cp->uncached_name_and_type_ref_index_at(from_i);
1621     to_cp->method_at_put(to_i, class_index, name_and_type_index);
1622   } break;
1623 
1624   case JVM_CONSTANT_NameAndType:
1625   {
1626     int name_ref_index = from_cp->name_ref_index_at(from_i);
1627     int signature_ref_index = from_cp->signature_ref_index_at(from_i);
1628     to_cp->name_and_type_at_put(to_i, name_ref_index, signature_ref_index);
1629   } break;
1630 
1631   case JVM_CONSTANT_StringIndex:
1632   {
1633     jint si = from_cp->string_index_at(from_i);
1634     to_cp->string_index_at_put(to_i, si);
1635   } break;
1636 
1637   case JVM_CONSTANT_Class:
1638   case JVM_CONSTANT_UnresolvedClass:
1639   case JVM_CONSTANT_UnresolvedClassInError:
1640   {
1641     // Revert to JVM_CONSTANT_ClassIndex
1642     int name_index = from_cp->klass_slot_at(from_i).name_index();
1643     assert(from_cp->tag_at(name_index).is_symbol(), "sanity");
1644     to_cp->klass_index_at_put(to_i, name_index);
1645   } break;
1646 
1647   case JVM_CONSTANT_String:
1648   {
1649     Symbol* s = from_cp->unresolved_string_at(from_i);
1650     to_cp->unresolved_string_at_put(to_i, s);
1651   } break;
1652 
1653   case JVM_CONSTANT_Utf8:
1654   {
1655     Symbol* s = from_cp->symbol_at(from_i);
1656     // Need to increase refcount, the old one will be thrown away and deferenced
1657     s->increment_refcount();
1658     to_cp->symbol_at_put(to_i, s);
1659   } break;
1660 
1661   case JVM_CONSTANT_MethodType:
1662   case JVM_CONSTANT_MethodTypeInError:
1663   {
1664     jint k = from_cp->method_type_index_at(from_i);
1665     to_cp->method_type_index_at_put(to_i, k);
1666   } break;
1667 
1668   case JVM_CONSTANT_MethodHandle:
1669   case JVM_CONSTANT_MethodHandleInError:
1670   {
1671     int k1 = from_cp->method_handle_ref_kind_at(from_i);
1672     int k2 = from_cp->method_handle_index_at(from_i);
1673     to_cp->method_handle_index_at_put(to_i, k1, k2);
1674   } break;
1675 
1676   case JVM_CONSTANT_Dynamic:
1677   case JVM_CONSTANT_DynamicInError:
1678   {
1679     int k1 = from_cp->bootstrap_methods_attribute_index(from_i);
1680     int k2 = from_cp->bootstrap_name_and_type_ref_index_at(from_i);
1681     k1 += operand_array_length(to_cp->operands());  // to_cp might already have operands
1682     to_cp->dynamic_constant_at_put(to_i, k1, k2);
1683   } break;
1684 
1685   case JVM_CONSTANT_InvokeDynamic:
1686   {
1687     int k1 = from_cp->bootstrap_methods_attribute_index(from_i);
1688     int k2 = from_cp->bootstrap_name_and_type_ref_index_at(from_i);
1689     k1 += operand_array_length(to_cp->operands());  // to_cp might already have operands
1690     to_cp->invoke_dynamic_at_put(to_i, k1, k2);
1691   } break;
1692 
1693   // Invalid is used as the tag for the second constant pool entry
1694   // occupied by JVM_CONSTANT_Double or JVM_CONSTANT_Long. It should
1695   // not be seen by itself.
1696   case JVM_CONSTANT_Invalid: // fall through
1697 
1698   default:
1699   {
1700     ShouldNotReachHere();
1701   } break;
1702   }
1703 } // end copy_entry_to()
1704 
1705 // Search constant pool search_cp for an entry that matches this
1706 // constant pool's entry at pattern_i. Returns the index of a
1707 // matching entry or zero (0) if there is no matching entry.
1708 int ConstantPool::find_matching_entry(int pattern_i,
1709       const constantPoolHandle& search_cp, TRAPS) {
1710 
1711   // index zero (0) is not used
1712   for (int i = 1; i < search_cp->length(); i++) {
1713     bool found = compare_entry_to(pattern_i, search_cp, i, CHECK_0);
1714     if (found) {
1715       return i;
1716     }
1717   }
1718 
1719   return 0;  // entry not found; return unused index zero (0)
1720 } // end find_matching_entry()
1721 
1722 
1723 // Compare this constant pool's bootstrap specifier at idx1 to the constant pool
1724 // cp2's bootstrap specifier at idx2.
1725 bool ConstantPool::compare_operand_to(int idx1, const constantPoolHandle& cp2, int idx2, TRAPS) {
1726   int k1 = operand_bootstrap_method_ref_index_at(idx1);
1727   int k2 = cp2->operand_bootstrap_method_ref_index_at(idx2);
1728   bool match = compare_entry_to(k1, cp2, k2, CHECK_false);
1729 
1730   if (!match) {
1731     return false;
1732   }
1733   int argc = operand_argument_count_at(idx1);
1734   if (argc == cp2->operand_argument_count_at(idx2)) {
1735     for (int j = 0; j < argc; j++) {
1736       k1 = operand_argument_index_at(idx1, j);
1737       k2 = cp2->operand_argument_index_at(idx2, j);
1738       match = compare_entry_to(k1, cp2, k2, CHECK_false);
1739       if (!match) {
1740         return false;
1741       }
1742     }
1743     return true;           // got through loop; all elements equal
1744   }
1745   return false;
1746 } // end compare_operand_to()
1747 
1748 // Search constant pool search_cp for a bootstrap specifier that matches
1749 // this constant pool's bootstrap specifier data at pattern_i index.
1750 // Return the index of a matching bootstrap attribute record or (-1) if there is no match.
1751 int ConstantPool::find_matching_operand(int pattern_i,
1752                     const constantPoolHandle& search_cp, int search_len, TRAPS) {
1753   for (int i = 0; i < search_len; i++) {
1754     bool found = compare_operand_to(pattern_i, search_cp, i, CHECK_(-1));
1755     if (found) {
1756       return i;
1757     }
1758   }
1759   return -1;  // bootstrap specifier data not found; return unused index (-1)
1760 } // end find_matching_operand()
1761 
1762 
1763 #ifndef PRODUCT
1764 
1765 const char* ConstantPool::printable_name_at(int which) {
1766 
1767   constantTag tag = tag_at(which);
1768 
1769   if (tag.is_string()) {
1770     return string_at_noresolve(which);
1771   } else if (tag.is_klass() || tag.is_unresolved_klass()) {
1772     return klass_name_at(which)->as_C_string();
1773   } else if (tag.is_symbol()) {
1774     return symbol_at(which)->as_C_string();
1775   }
1776   return "";
1777 }
1778 
1779 #endif // PRODUCT
1780 
1781 
1782 // JVMTI GetConstantPool support
1783 
1784 // For debugging of constant pool
1785 const bool debug_cpool = false;
1786 
1787 #define DBG(code) do { if (debug_cpool) { (code); } } while(0)
1788 
1789 static void print_cpool_bytes(jint cnt, u1 *bytes) {
1790   const char* WARN_MSG = "Must not be such entry!";
1791   jint size = 0;
1792   u2   idx1, idx2;
1793 
1794   for (jint idx = 1; idx < cnt; idx++) {
1795     jint ent_size = 0;
1796     u1   tag  = *bytes++;
1797     size++;                       // count tag
1798 
1799     printf("const #%03d, tag: %02d ", idx, tag);
1800     switch(tag) {
1801       case JVM_CONSTANT_Invalid: {
1802         printf("Invalid");
1803         break;
1804       }
1805       case JVM_CONSTANT_Unicode: {
1806         printf("Unicode      %s", WARN_MSG);
1807         break;
1808       }
1809       case JVM_CONSTANT_Utf8: {
1810         u2 len = Bytes::get_Java_u2(bytes);
1811         char str[128];
1812         if (len > 127) {
1813            len = 127;
1814         }
1815         strncpy(str, (char *) (bytes+2), len);
1816         str[len] = '\0';
1817         printf("Utf8          \"%s\"", str);
1818         ent_size = 2 + len;
1819         break;
1820       }
1821       case JVM_CONSTANT_Integer: {
1822         u4 val = Bytes::get_Java_u4(bytes);
1823         printf("int          %d", *(int *) &val);
1824         ent_size = 4;
1825         break;
1826       }
1827       case JVM_CONSTANT_Float: {
1828         u4 val = Bytes::get_Java_u4(bytes);
1829         printf("float        %5.3ff", *(float *) &val);
1830         ent_size = 4;
1831         break;
1832       }
1833       case JVM_CONSTANT_Long: {
1834         u8 val = Bytes::get_Java_u8(bytes);
1835         printf("long         " INT64_FORMAT, (int64_t) *(jlong *) &val);
1836         ent_size = 8;
1837         idx++; // Long takes two cpool slots
1838         break;
1839       }
1840       case JVM_CONSTANT_Double: {
1841         u8 val = Bytes::get_Java_u8(bytes);
1842         printf("double       %5.3fd", *(jdouble *)&val);
1843         ent_size = 8;
1844         idx++; // Double takes two cpool slots
1845         break;
1846       }
1847       case JVM_CONSTANT_Class: {
1848         idx1 = Bytes::get_Java_u2(bytes);
1849         printf("class        #%03d", idx1);
1850         ent_size = 2;
1851         break;
1852       }
1853       case JVM_CONSTANT_String: {
1854         idx1 = Bytes::get_Java_u2(bytes);
1855         printf("String       #%03d", idx1);
1856         ent_size = 2;
1857         break;
1858       }
1859       case JVM_CONSTANT_Fieldref: {
1860         idx1 = Bytes::get_Java_u2(bytes);
1861         idx2 = Bytes::get_Java_u2(bytes+2);
1862         printf("Field        #%03d, #%03d", (int) idx1, (int) idx2);
1863         ent_size = 4;
1864         break;
1865       }
1866       case JVM_CONSTANT_Methodref: {
1867         idx1 = Bytes::get_Java_u2(bytes);
1868         idx2 = Bytes::get_Java_u2(bytes+2);
1869         printf("Method       #%03d, #%03d", idx1, idx2);
1870         ent_size = 4;
1871         break;
1872       }
1873       case JVM_CONSTANT_InterfaceMethodref: {
1874         idx1 = Bytes::get_Java_u2(bytes);
1875         idx2 = Bytes::get_Java_u2(bytes+2);
1876         printf("InterfMethod #%03d, #%03d", idx1, idx2);
1877         ent_size = 4;
1878         break;
1879       }
1880       case JVM_CONSTANT_NameAndType: {
1881         idx1 = Bytes::get_Java_u2(bytes);
1882         idx2 = Bytes::get_Java_u2(bytes+2);
1883         printf("NameAndType  #%03d, #%03d", idx1, idx2);
1884         ent_size = 4;
1885         break;
1886       }
1887       case JVM_CONSTANT_ClassIndex: {
1888         printf("ClassIndex  %s", WARN_MSG);
1889         break;
1890       }
1891       case JVM_CONSTANT_UnresolvedClass: {
1892         printf("UnresolvedClass: %s", WARN_MSG);
1893         break;
1894       }
1895       case JVM_CONSTANT_UnresolvedClassInError: {
1896         printf("UnresolvedClassInErr: %s", WARN_MSG);
1897         break;
1898       }
1899       case JVM_CONSTANT_StringIndex: {
1900         printf("StringIndex: %s", WARN_MSG);
1901         break;
1902       }
1903     }
1904     printf(";\n");
1905     bytes += ent_size;
1906     size  += ent_size;
1907   }
1908   printf("Cpool size: %d\n", size);
1909   fflush(0);
1910   return;
1911 } /* end print_cpool_bytes */
1912 
1913 
1914 // Returns size of constant pool entry.
1915 jint ConstantPool::cpool_entry_size(jint idx) {
1916   switch(tag_at(idx).value()) {
1917     case JVM_CONSTANT_Invalid:
1918     case JVM_CONSTANT_Unicode:
1919       return 1;
1920 
1921     case JVM_CONSTANT_Utf8:
1922       return 3 + symbol_at(idx)->utf8_length();
1923 
1924     case JVM_CONSTANT_Class:
1925     case JVM_CONSTANT_String:
1926     case JVM_CONSTANT_ClassIndex:
1927     case JVM_CONSTANT_UnresolvedClass:
1928     case JVM_CONSTANT_UnresolvedClassInError:
1929     case JVM_CONSTANT_StringIndex:
1930     case JVM_CONSTANT_MethodType:
1931     case JVM_CONSTANT_MethodTypeInError:
1932       return 3;
1933 
1934     case JVM_CONSTANT_MethodHandle:
1935     case JVM_CONSTANT_MethodHandleInError:
1936       return 4; //tag, ref_kind, ref_index
1937 
1938     case JVM_CONSTANT_Integer:
1939     case JVM_CONSTANT_Float:
1940     case JVM_CONSTANT_Fieldref:
1941     case JVM_CONSTANT_Methodref:
1942     case JVM_CONSTANT_InterfaceMethodref:
1943     case JVM_CONSTANT_NameAndType:
1944       return 5;
1945 
1946     case JVM_CONSTANT_Dynamic:
1947     case JVM_CONSTANT_DynamicInError:
1948     case JVM_CONSTANT_InvokeDynamic:
1949       // u1 tag, u2 bsm, u2 nt
1950       return 5;
1951 
1952     case JVM_CONSTANT_Long:
1953     case JVM_CONSTANT_Double:
1954       return 9;
1955   }
1956   assert(false, "cpool_entry_size: Invalid constant pool entry tag");
1957   return 1;
1958 } /* end cpool_entry_size */
1959 
1960 
1961 // SymbolHashMap is used to find a constant pool index from a string.
1962 // This function fills in SymbolHashMaps, one for utf8s and one for
1963 // class names, returns size of the cpool raw bytes.
1964 jint ConstantPool::hash_entries_to(SymbolHashMap *symmap,
1965                                           SymbolHashMap *classmap) {
1966   jint size = 0;
1967 
1968   for (u2 idx = 1; idx < length(); idx++) {
1969     u2 tag = tag_at(idx).value();
1970     size += cpool_entry_size(idx);
1971 
1972     switch(tag) {
1973       case JVM_CONSTANT_Utf8: {
1974         Symbol* sym = symbol_at(idx);
1975         symmap->add_entry(sym, idx);
1976         DBG(printf("adding symbol entry %s = %d\n", sym->as_utf8(), idx));
1977         break;
1978       }
1979       case JVM_CONSTANT_Class:
1980       case JVM_CONSTANT_UnresolvedClass:
1981       case JVM_CONSTANT_UnresolvedClassInError: {
1982         Symbol* sym = klass_name_at(idx);
1983         classmap->add_entry(sym, idx);
1984         DBG(printf("adding class entry %s = %d\n", sym->as_utf8(), idx));
1985         break;
1986       }
1987       case JVM_CONSTANT_Long:
1988       case JVM_CONSTANT_Double: {
1989         idx++; // Both Long and Double take two cpool slots
1990         break;
1991       }
1992     }
1993   }
1994   return size;
1995 } /* end hash_utf8_entries_to */
1996 
1997 
1998 // Copy cpool bytes.
1999 // Returns:
2000 //    0, in case of OutOfMemoryError
2001 //   -1, in case of internal error
2002 //  > 0, count of the raw cpool bytes that have been copied
2003 int ConstantPool::copy_cpool_bytes(int cpool_size,
2004                                           SymbolHashMap* tbl,
2005                                           unsigned char *bytes) {
2006   u2   idx1, idx2;
2007   jint size  = 0;
2008   jint cnt   = length();
2009   unsigned char *start_bytes = bytes;
2010 
2011   for (jint idx = 1; idx < cnt; idx++) {
2012     u1   tag      = tag_at(idx).value();
2013     jint ent_size = cpool_entry_size(idx);
2014 
2015     assert(size + ent_size <= cpool_size, "Size mismatch");
2016 
2017     *bytes = tag;
2018     DBG(printf("#%03hd tag=%03hd, ", (short)idx, (short)tag));
2019     switch(tag) {
2020       case JVM_CONSTANT_Invalid: {
2021         DBG(printf("JVM_CONSTANT_Invalid"));
2022         break;
2023       }
2024       case JVM_CONSTANT_Unicode: {
2025         assert(false, "Wrong constant pool tag: JVM_CONSTANT_Unicode");
2026         DBG(printf("JVM_CONSTANT_Unicode"));
2027         break;
2028       }
2029       case JVM_CONSTANT_Utf8: {
2030         Symbol* sym = symbol_at(idx);
2031         char*     str = sym->as_utf8();
2032         // Warning! It's crashing on x86 with len = sym->utf8_length()
2033         int       len = (int) strlen(str);
2034         Bytes::put_Java_u2((address) (bytes+1), (u2) len);
2035         for (int i = 0; i < len; i++) {
2036             bytes[3+i] = (u1) str[i];
2037         }
2038         DBG(printf("JVM_CONSTANT_Utf8: %s ", str));
2039         break;
2040       }
2041       case JVM_CONSTANT_Integer: {
2042         jint val = int_at(idx);
2043         Bytes::put_Java_u4((address) (bytes+1), *(u4*)&val);
2044         break;
2045       }
2046       case JVM_CONSTANT_Float: {
2047         jfloat val = float_at(idx);
2048         Bytes::put_Java_u4((address) (bytes+1), *(u4*)&val);
2049         break;
2050       }
2051       case JVM_CONSTANT_Long: {
2052         jlong val = long_at(idx);
2053         Bytes::put_Java_u8((address) (bytes+1), *(u8*)&val);
2054         idx++;             // Long takes two cpool slots
2055         break;
2056       }
2057       case JVM_CONSTANT_Double: {
2058         jdouble val = double_at(idx);
2059         Bytes::put_Java_u8((address) (bytes+1), *(u8*)&val);
2060         idx++;             // Double takes two cpool slots
2061         break;
2062       }
2063       case JVM_CONSTANT_Class:
2064       case JVM_CONSTANT_UnresolvedClass:
2065       case JVM_CONSTANT_UnresolvedClassInError: {
2066         *bytes = JVM_CONSTANT_Class;
2067         Symbol* sym = klass_name_at(idx);
2068         idx1 = tbl->symbol_to_value(sym);
2069         assert(idx1 != 0, "Have not found a hashtable entry");
2070         Bytes::put_Java_u2((address) (bytes+1), idx1);
2071         DBG(printf("JVM_CONSTANT_Class: idx=#%03hd, %s", idx1, sym->as_utf8()));
2072         break;
2073       }
2074       case JVM_CONSTANT_String: {
2075         *bytes = JVM_CONSTANT_String;
2076         Symbol* sym = unresolved_string_at(idx);
2077         idx1 = tbl->symbol_to_value(sym);
2078         assert(idx1 != 0, "Have not found a hashtable entry");
2079         Bytes::put_Java_u2((address) (bytes+1), idx1);
2080         DBG(printf("JVM_CONSTANT_String: idx=#%03hd, %s", idx1, sym->as_utf8()));
2081         break;
2082       }
2083       case JVM_CONSTANT_Fieldref:
2084       case JVM_CONSTANT_Methodref:
2085       case JVM_CONSTANT_InterfaceMethodref: {
2086         idx1 = uncached_klass_ref_index_at(idx);
2087         idx2 = uncached_name_and_type_ref_index_at(idx);
2088         Bytes::put_Java_u2((address) (bytes+1), idx1);
2089         Bytes::put_Java_u2((address) (bytes+3), idx2);
2090         DBG(printf("JVM_CONSTANT_Methodref: %hd %hd", idx1, idx2));
2091         break;
2092       }
2093       case JVM_CONSTANT_NameAndType: {
2094         idx1 = name_ref_index_at(idx);
2095         idx2 = signature_ref_index_at(idx);
2096         Bytes::put_Java_u2((address) (bytes+1), idx1);
2097         Bytes::put_Java_u2((address) (bytes+3), idx2);
2098         DBG(printf("JVM_CONSTANT_NameAndType: %hd %hd", idx1, idx2));
2099         break;
2100       }
2101       case JVM_CONSTANT_ClassIndex: {
2102         *bytes = JVM_CONSTANT_Class;
2103         idx1 = klass_index_at(idx);
2104         Bytes::put_Java_u2((address) (bytes+1), idx1);
2105         DBG(printf("JVM_CONSTANT_ClassIndex: %hd", idx1));
2106         break;
2107       }
2108       case JVM_CONSTANT_StringIndex: {
2109         *bytes = JVM_CONSTANT_String;
2110         idx1 = string_index_at(idx);
2111         Bytes::put_Java_u2((address) (bytes+1), idx1);
2112         DBG(printf("JVM_CONSTANT_StringIndex: %hd", idx1));
2113         break;
2114       }
2115       case JVM_CONSTANT_MethodHandle:
2116       case JVM_CONSTANT_MethodHandleInError: {
2117         *bytes = JVM_CONSTANT_MethodHandle;
2118         int kind = method_handle_ref_kind_at(idx);
2119         idx1 = method_handle_index_at(idx);
2120         *(bytes+1) = (unsigned char) kind;
2121         Bytes::put_Java_u2((address) (bytes+2), idx1);
2122         DBG(printf("JVM_CONSTANT_MethodHandle: %d %hd", kind, idx1));
2123         break;
2124       }
2125       case JVM_CONSTANT_MethodType:
2126       case JVM_CONSTANT_MethodTypeInError: {
2127         *bytes = JVM_CONSTANT_MethodType;
2128         idx1 = method_type_index_at(idx);
2129         Bytes::put_Java_u2((address) (bytes+1), idx1);
2130         DBG(printf("JVM_CONSTANT_MethodType: %hd", idx1));
2131         break;
2132       }
2133       case JVM_CONSTANT_Dynamic:
2134       case JVM_CONSTANT_DynamicInError: {
2135         *bytes = tag;
2136         idx1 = extract_low_short_from_int(*int_at_addr(idx));
2137         idx2 = extract_high_short_from_int(*int_at_addr(idx));
2138         assert(idx2 == bootstrap_name_and_type_ref_index_at(idx), "correct half of u4");
2139         Bytes::put_Java_u2((address) (bytes+1), idx1);
2140         Bytes::put_Java_u2((address) (bytes+3), idx2);
2141         DBG(printf("JVM_CONSTANT_Dynamic: %hd %hd", idx1, idx2));
2142         break;
2143       }
2144       case JVM_CONSTANT_InvokeDynamic: {
2145         *bytes = tag;
2146         idx1 = extract_low_short_from_int(*int_at_addr(idx));
2147         idx2 = extract_high_short_from_int(*int_at_addr(idx));
2148         assert(idx2 == bootstrap_name_and_type_ref_index_at(idx), "correct half of u4");
2149         Bytes::put_Java_u2((address) (bytes+1), idx1);
2150         Bytes::put_Java_u2((address) (bytes+3), idx2);
2151         DBG(printf("JVM_CONSTANT_InvokeDynamic: %hd %hd", idx1, idx2));
2152         break;
2153       }
2154     }
2155     DBG(printf("\n"));
2156     bytes += ent_size;
2157     size  += ent_size;
2158   }
2159   assert(size == cpool_size, "Size mismatch");
2160 
2161   // Keep temorarily for debugging until it's stable.
2162   DBG(print_cpool_bytes(cnt, start_bytes));
2163   return (int)(bytes - start_bytes);
2164 } /* end copy_cpool_bytes */
2165 
2166 #undef DBG
2167 
2168 
2169 void ConstantPool::set_on_stack(const bool value) {
2170   if (value) {
2171     // Only record if it's not already set.
2172     if (!on_stack()) {
2173       assert(!is_shared(), "should always be set for shared constant pools");
2174       _flags |= _on_stack;
2175       MetadataOnStackMark::record(this);
2176     }
2177   } else {
2178     // Clearing is done single-threadedly.
2179     if (!is_shared()) {
2180       _flags &= ~_on_stack;
2181     }
2182   }
2183 }
2184 
2185 // JSR 292 support for patching constant pool oops after the class is linked and
2186 // the oop array for resolved references are created.
2187 // We can't do this during classfile parsing, which is how the other indexes are
2188 // patched.  The other patches are applied early for some error checking
2189 // so only defer the pseudo_strings.
2190 void ConstantPool::patch_resolved_references(GrowableArray<Handle>* cp_patches) {
2191   for (int index = 1; index < cp_patches->length(); index++) { // Index 0 is unused
2192     Handle patch = cp_patches->at(index);
2193     if (patch.not_null()) {
2194       assert (tag_at(index).is_string(), "should only be string left");
2195       // Patching a string means pre-resolving it.
2196       // The spelling in the constant pool is ignored.
2197       // The constant reference may be any object whatever.
2198       // If it is not a real interned string, the constant is referred
2199       // to as a "pseudo-string", and must be presented to the CP
2200       // explicitly, because it may require scavenging.
2201       int obj_index = cp_to_object_index(index);
2202       pseudo_string_at_put(index, obj_index, patch());
2203      DEBUG_ONLY(cp_patches->at_put(index, Handle());)
2204     }
2205   }
2206 #ifdef ASSERT
2207   // Ensure that all the patches have been used.
2208   for (int index = 0; index < cp_patches->length(); index++) {
2209     assert(cp_patches->at(index).is_null(),
2210            "Unused constant pool patch at %d in class file %s",
2211            index,
2212            pool_holder()->external_name());
2213   }
2214 #endif // ASSERT
2215 }
2216 
2217 // Printing
2218 
2219 void ConstantPool::print_on(outputStream* st) const {
2220   assert(is_constantPool(), "must be constantPool");
2221   st->print_cr("%s", internal_name());
2222   if (flags() != 0) {
2223     st->print(" - flags: 0x%x", flags());
2224     if (has_preresolution()) st->print(" has_preresolution");
2225     if (on_stack()) st->print(" on_stack");
2226     st->cr();
2227   }
2228   if (pool_holder() != NULL) {
2229     st->print_cr(" - holder: " INTPTR_FORMAT, p2i(pool_holder()));
2230   }
2231   st->print_cr(" - cache: " INTPTR_FORMAT, p2i(cache()));
2232   st->print_cr(" - resolved_references: " INTPTR_FORMAT, p2i(resolved_references()));
2233   st->print_cr(" - reference_map: " INTPTR_FORMAT, p2i(reference_map()));
2234   st->print_cr(" - resolved_klasses: " INTPTR_FORMAT, p2i(resolved_klasses()));
2235 
2236   for (int index = 1; index < length(); index++) {      // Index 0 is unused
2237     ((ConstantPool*)this)->print_entry_on(index, st);
2238     switch (tag_at(index).value()) {
2239       case JVM_CONSTANT_Long :
2240       case JVM_CONSTANT_Double :
2241         index++;   // Skip entry following eigth-byte constant
2242     }
2243 
2244   }
2245   st->cr();
2246 }
2247 
2248 // Print one constant pool entry
2249 void ConstantPool::print_entry_on(const int index, outputStream* st) {
2250   EXCEPTION_MARK;
2251   st->print(" - %3d : ", index);
2252   tag_at(index).print_on(st);
2253   st->print(" : ");
2254   switch (tag_at(index).value()) {
2255     case JVM_CONSTANT_Class :
2256       { Klass* k = klass_at(index, CATCH);
2257         guarantee(k != NULL, "need klass");
2258         k->print_value_on(st);
2259         st->print(" {" PTR_FORMAT "}", p2i(k));
2260       }
2261       break;
2262     case JVM_CONSTANT_Fieldref :
2263     case JVM_CONSTANT_Methodref :
2264     case JVM_CONSTANT_InterfaceMethodref :
2265       st->print("klass_index=%d", uncached_klass_ref_index_at(index));
2266       st->print(" name_and_type_index=%d", uncached_name_and_type_ref_index_at(index));
2267       break;
2268     case JVM_CONSTANT_String :
2269       if (is_pseudo_string_at(index)) {
2270         oop anObj = pseudo_string_at(index);
2271         anObj->print_value_on(st);
2272         st->print(" {" PTR_FORMAT "}", p2i(anObj));
2273       } else {
2274         unresolved_string_at(index)->print_value_on(st);
2275       }
2276       break;
2277     case JVM_CONSTANT_Integer :
2278       st->print("%d", int_at(index));
2279       break;
2280     case JVM_CONSTANT_Float :
2281       st->print("%f", float_at(index));
2282       break;
2283     case JVM_CONSTANT_Long :
2284       st->print_jlong(long_at(index));
2285       break;
2286     case JVM_CONSTANT_Double :
2287       st->print("%lf", double_at(index));
2288       break;
2289     case JVM_CONSTANT_NameAndType :
2290       st->print("name_index=%d", name_ref_index_at(index));
2291       st->print(" signature_index=%d", signature_ref_index_at(index));
2292       break;
2293     case JVM_CONSTANT_Utf8 :
2294       symbol_at(index)->print_value_on(st);
2295       break;
2296     case JVM_CONSTANT_ClassIndex: {
2297         int name_index = *int_at_addr(index);
2298         st->print("klass_index=%d ", name_index);
2299         symbol_at(name_index)->print_value_on(st);
2300       }
2301       break;
2302     case JVM_CONSTANT_UnresolvedClass :               // fall-through
2303     case JVM_CONSTANT_UnresolvedClassInError: {
2304         CPKlassSlot kslot = klass_slot_at(index);
2305         int resolved_klass_index = kslot.resolved_klass_index();
2306         int name_index = kslot.name_index();
2307         assert(tag_at(name_index).is_symbol(), "sanity");
2308 
2309         Klass* klass = resolved_klasses()->at(resolved_klass_index);
2310         if (klass != NULL) {
2311           klass->print_value_on(st);
2312         } else {
2313           symbol_at(name_index)->print_value_on(st);
2314         }
2315       }
2316       break;
2317     case JVM_CONSTANT_MethodHandle :
2318     case JVM_CONSTANT_MethodHandleInError :
2319       st->print("ref_kind=%d", method_handle_ref_kind_at(index));
2320       st->print(" ref_index=%d", method_handle_index_at(index));
2321       break;
2322     case JVM_CONSTANT_MethodType :
2323     case JVM_CONSTANT_MethodTypeInError :
2324       st->print("signature_index=%d", method_type_index_at(index));
2325       break;
2326     case JVM_CONSTANT_Dynamic :
2327     case JVM_CONSTANT_DynamicInError :
2328       {
2329         st->print("bootstrap_method_index=%d", bootstrap_method_ref_index_at(index));
2330         st->print(" type_index=%d", bootstrap_name_and_type_ref_index_at(index));
2331         int argc = bootstrap_argument_count_at(index);
2332         if (argc > 0) {
2333           for (int arg_i = 0; arg_i < argc; arg_i++) {
2334             int arg = bootstrap_argument_index_at(index, arg_i);
2335             st->print((arg_i == 0 ? " arguments={%d" : ", %d"), arg);
2336           }
2337           st->print("}");
2338         }
2339       }
2340       break;
2341     case JVM_CONSTANT_InvokeDynamic :
2342       {
2343         st->print("bootstrap_method_index=%d", bootstrap_method_ref_index_at(index));
2344         st->print(" name_and_type_index=%d", bootstrap_name_and_type_ref_index_at(index));
2345         int argc = bootstrap_argument_count_at(index);
2346         if (argc > 0) {
2347           for (int arg_i = 0; arg_i < argc; arg_i++) {
2348             int arg = bootstrap_argument_index_at(index, arg_i);
2349             st->print((arg_i == 0 ? " arguments={%d" : ", %d"), arg);
2350           }
2351           st->print("}");
2352         }
2353       }
2354       break;
2355     default:
2356       ShouldNotReachHere();
2357       break;
2358   }
2359   st->cr();
2360 }
2361 
2362 void ConstantPool::print_value_on(outputStream* st) const {
2363   assert(is_constantPool(), "must be constantPool");
2364   st->print("constant pool [%d]", length());
2365   if (has_preresolution()) st->print("/preresolution");
2366   if (operands() != NULL)  st->print("/operands[%d]", operands()->length());
2367   print_address_on(st);
2368   if (pool_holder() != NULL) {
2369     st->print(" for ");
2370     pool_holder()->print_value_on(st);
2371     bool extra = (pool_holder()->constants() != this);
2372     if (extra)  st->print(" (extra)");
2373   }
2374   if (cache() != NULL) {
2375     st->print(" cache=" PTR_FORMAT, p2i(cache()));
2376   }
2377 }
2378 
2379 #if INCLUDE_SERVICES
2380 // Size Statistics
2381 void ConstantPool::collect_statistics(KlassSizeStats *sz) const {
2382   sz->_cp_all_bytes += (sz->_cp_bytes          = sz->count(this));
2383   sz->_cp_all_bytes += (sz->_cp_tags_bytes     = sz->count_array(tags()));
2384   sz->_cp_all_bytes += (sz->_cp_cache_bytes    = sz->count(cache()));
2385   sz->_cp_all_bytes += (sz->_cp_operands_bytes = sz->count_array(operands()));
2386   sz->_cp_all_bytes += (sz->_cp_refmap_bytes   = sz->count_array(reference_map()));
2387 
2388   sz->_ro_bytes += sz->_cp_operands_bytes + sz->_cp_tags_bytes +
2389                    sz->_cp_refmap_bytes;
2390   sz->_rw_bytes += sz->_cp_bytes + sz->_cp_cache_bytes;
2391 }
2392 #endif // INCLUDE_SERVICES
2393 
2394 // Verification
2395 
2396 void ConstantPool::verify_on(outputStream* st) {
2397   guarantee(is_constantPool(), "object must be constant pool");
2398   for (int i = 0; i< length();  i++) {
2399     constantTag tag = tag_at(i);
2400     if (tag.is_klass() || tag.is_unresolved_klass()) {
2401       guarantee(klass_name_at(i)->refcount() != 0, "should have nonzero reference count");
2402     } else if (tag.is_symbol()) {
2403       CPSlot entry = slot_at(i);
2404       guarantee(entry.get_symbol()->refcount() != 0, "should have nonzero reference count");
2405     } else if (tag.is_string()) {
2406       CPSlot entry = slot_at(i);
2407       guarantee(entry.get_symbol()->refcount() != 0, "should have nonzero reference count");
2408     }
2409   }
2410   if (pool_holder() != NULL) {
2411     // Note: pool_holder() can be NULL in temporary constant pools
2412     // used during constant pool merging
2413     guarantee(pool_holder()->is_klass(),    "should be klass");
2414   }
2415 }
2416 
2417 
2418 SymbolHashMap::~SymbolHashMap() {
2419   SymbolHashMapEntry* next;
2420   for (int i = 0; i < _table_size; i++) {
2421     for (SymbolHashMapEntry* cur = bucket(i); cur != NULL; cur = next) {
2422       next = cur->next();
2423       delete(cur);
2424     }
2425   }
2426   FREE_C_HEAP_ARRAY(SymbolHashMapBucket, _buckets);
2427 }
2428 
2429 void SymbolHashMap::add_entry(Symbol* sym, u2 value) {
2430   char *str = sym->as_utf8();
2431   unsigned int hash = compute_hash(str, sym->utf8_length());
2432   unsigned int index = hash % table_size();
2433 
2434   // check if already in map
2435   // we prefer the first entry since it is more likely to be what was used in
2436   // the class file
2437   for (SymbolHashMapEntry *en = bucket(index); en != NULL; en = en->next()) {
2438     assert(en->symbol() != NULL, "SymbolHashMapEntry symbol is NULL");
2439     if (en->hash() == hash && en->symbol() == sym) {
2440         return;  // already there
2441     }
2442   }
2443 
2444   SymbolHashMapEntry* entry = new SymbolHashMapEntry(hash, sym, value);
2445   entry->set_next(bucket(index));
2446   _buckets[index].set_entry(entry);
2447   assert(entry->symbol() != NULL, "SymbolHashMapEntry symbol is NULL");
2448 }
2449 
2450 SymbolHashMapEntry* SymbolHashMap::find_entry(Symbol* sym) {
2451   assert(sym != NULL, "SymbolHashMap::find_entry - symbol is NULL");
2452   char *str = sym->as_utf8();
2453   int   len = sym->utf8_length();
2454   unsigned int hash = SymbolHashMap::compute_hash(str, len);
2455   unsigned int index = hash % table_size();
2456   for (SymbolHashMapEntry *en = bucket(index); en != NULL; en = en->next()) {
2457     assert(en->symbol() != NULL, "SymbolHashMapEntry symbol is NULL");
2458     if (en->hash() == hash && en->symbol() == sym) {
2459       return en;
2460     }
2461   }
2462   return NULL;
2463 }
2464 
2465 void SymbolHashMap::initialize_table(int table_size) {
2466   _table_size = table_size;
2467   _buckets = NEW_C_HEAP_ARRAY(SymbolHashMapBucket, table_size, mtSymbol);
2468   for (int index = 0; index < table_size; index++) {
2469     _buckets[index].clear();
2470   }
2471 }