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