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